CASE and Views
CASE turns a raw value into a label, row by row. A view saves that whole query under a name — and stays a query, not a copy of the answer.
Salary Bands
The View
Create the view first, then try the raise.
employees, with a CASE column
—Query
Counts
Overview
A CASE expression selects a result for each row based on conditions. A view stores a query definition under a name so other queries can reuse it. Neither changes the underlying rows by itself. They solve different problems: conditional logic in a result, and reuse of a query shape.
Use CASE for conditional values
A searched CASE checks conditions in order and returns the result for the first true condition. If none match, ELSE supplies the fallback; without it, the result is NULL.
The order matters: a condition that catches too much can make later branches unreachable. Comparisons with NULL are not true, so add an explicit WHEN total IS NULL branch if missing totals need their own label. A simple CASE expression WHEN value form is useful for equality checks, but cannot express ranges.
Conditional aggregation combines CASE with aggregates, for example SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END). For a portable alternative, some engines also support FILTER; check the target dialect.
A view is a saved query
Create a view when a query expresses a stable, reusable concept such as active customers:
Selecting from the view runs its underlying query; a regular view is not automatically a stored copy of the results. Updates through views have engine-specific restrictions. A materialized view stores results and needs a refresh strategy; SQLite does not provide native materialized views.
Views can reduce repetition and restrict which columns users see, but they are not a substitute for permissions on the underlying data. Keep the view definition clear, and inspect its query plan when it becomes slow. See query plans.
Keep branch results compatible
The result branches of a CASE expression should have compatible types. If one branch returns a number and another returns text, the database may coerce values or reject the expression depending on its type rules. Give the expression a meaningful alias so callers can understand the derived field. A view can also expose a stable set of columns while hiding joins from consumers, but changing its output columns can break dependent queries. Treat view definitions as part of the interface and migrate them deliberately.
Further reading
- SQLite expressions documents
CASEevaluation. - SQLite CREATE VIEW describes view behavior.