Conditional Logic in SQL With CASE Expressions
How to write if-then-else logic inside a query: searched and simple CASE, why WHEN order matters, the missing ELSE, NULL in simple CASE, type rules, CASE in ORDER BY, WHERE and aggregates (conditional counts and pivots), FILTER, and shorthand functions such as COALESCE, GREATEST and LEAST.
kvi5hnuCode Sprout team member11 min readOn this page
SQL is a declarative language without if statements, but queries constantly need conditional values: label a price as "budget" or "premium", show "sold out" instead of 0, count only the orders that shipped late. The CASE expression does all of this. It's standard, it works the same way in every product, and it can appear anywhere an expression can: in the select list, WHERE, ORDER BY, GROUP BY, inside aggregates, and in UPDATE statements.
CASE is an expression. It produces one value for each row. It doesn't control which statements run, unlike the IF and CASE statements of procedural languages such as PL/pgSQL and PL/SQL (Part 13).
Searched CASE and simple CASE
CASE comes in two forms:
-- Searched CASE: any condition in each WHEN
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
[ELSE default_result]
END
-- Simple CASE: one expression compared with values using =
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
[ELSE default_result]
END
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- Searched CASE: each WHEN has its own condition, tested top to bottom
SELECT name, price,
CASE
WHEN price >= 200 THEN 'premium'
WHEN price >= 50 THEN 'mid-range'
ELSE 'budget'
END AS price_band
FROM products
ORDER BY price DESC;
-- Simple CASE: compare one expression with a list of values
SELECT name, category,
CASE category
WHEN 'tents' THEN 'Shelter'
WHEN 'packs' THEN 'Carry'
WHEN 'lighting' THEN 'Light'
END AS department
FROM products
ORDER BY product_id;
name | price | price_band
-------------------+--------+------------
Summit 4 tent | 489.00 | premium
Ridge 2 tent | 249.99 | premium
Trail 30 backpack | 89.95 | mid-range
Day 18 backpack | 54.00 | mid-range
Glow head torch | 34.50 | budget
Basecamp lantern | 27.00 | budget
Merino socks | 16.00 | budget
(7 rows)
name | category | department
-------------------+----------+------------
Ridge 2 tent | tents | Shelter
Summit 4 tent | tents | Shelter
Glow head torch | lighting | Light
Basecamp lantern | lighting | Light
Trail 30 backpack | packs | Carry
Day 18 backpack | packs | Carry
Merino socks | clothing | (null)
(7 rows)
- The searched form puts a full condition in each
WHEN, so it can test ranges, several columns,IS NULL,LIKEand anything else. It's the more general form. - The simple form compares one expression with a list of values.
CASE category WHEN 'tents' THEN ...is shorthand forCASE WHEN category = 'tents' THEN .... It's shorter when every branch tests the same column for equality. - No
ELSEmeansELSE NULL. The socks are inclothing, which isn't listed, so their department is NULL. If an unlisted value should get a label, write anELSE. Even when you think every value is covered, anELSEsuch as'other'makes new values obvious instead of leaving silent holes.
How CASE is evaluated
For each row, the WHEN conditions are tested in order, from top to bottom. The first one that's true decides the result, and the rest aren't tested. A WHEN whose condition is false or unknown (NULL) passes control to the next one. If no WHEN is true, the result is the ELSE value, or NULL.

That rule is the source of two common bugs:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- Simple CASE compares with =, so WHEN NULL never matches
SELECT name, brand,
CASE brand WHEN NULL THEN 'no brand' ELSE 'branded' END AS simple_case,
CASE WHEN brand IS NULL THEN 'no brand' ELSE 'branded' END AS searched_case
FROM products
WHERE category = 'lighting'
ORDER BY product_id;
-- Order matters: the first true WHEN wins, so this mislabels every expensive product
SELECT name, price,
CASE
WHEN price >= 50 THEN 'mid-range'
WHEN price >= 200 THEN 'premium'
ELSE 'budget'
END AS wrong_band
FROM products
WHERE category = 'tents'
ORDER BY price;
-- Every branch must have a compatible type
SELECT CASE WHEN stock > 0 THEN stock ELSE 'sold out' END FROM products;
SELECT name, CASE WHEN stock > 0 THEN CAST(stock AS VARCHAR(10)) ELSE 'sold out' END AS availability
FROM products
WHERE category = 'packs'
ORDER BY product_id;
name | brand | simple_case | searched_case
------------------+--------+-------------+---------------
Glow head torch | Lumen | branded | branded
Basecamp lantern | (null) | branded | no brand
(2 rows)
name | price | wrong_band
---------------+--------+------------
Ridge 2 tent | 249.99 | mid-range
Summit 4 tent | 489.00 | mid-range
(2 rows)
psql:/workspace/solution.sql:40: ERROR: invalid input syntax for type integer: "sold out"
LINE 1: SELECT CASE WHEN stock > 0 THEN stock ELSE 'sold out' END FR...
^
name | availability
-------------------+--------------
Trail 30 backpack | 22
Day 18 backpack | sold out
(2 rows)
WHEN NULLin a simple CASE never matches.CASE brand WHEN NULL ...meansbrand = NULL, which is unknown for every row (article 8). The lantern was labelledbranded, which is wrong. Use the searched form withWHEN brand IS NULL.- Overlapping conditions in the wrong order. In the second query,
price >= 50comes first, so it catches every tent before theprice >= 200test is reached. When ranges overlap, put the most specific (here, the highest) range first, or write non-overlapping ranges such asWHEN price >= 50 AND price < 200. - All results must have compatible types. The result of a
CASEhas one type, worked out from all itsTHENandELSEvalues.stockis an integer, so PostgreSQL tried to convert'sold out'to an integer and failed. Convert explicitly so that every branch is text, as the fixed query does withCAST(stock AS VARCHAR(10)). MySQL accepts the query and quietly makes the whole result a string, and SQLite returns a mixture of integers and text in one column. Both hide the problem until a client program trips over it.
CASE anywhere an expression goes
Because CASE is just an expression, you can use it in every clause:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Conditional counting and summing: a pivot in one pass
SELECT COUNT(*) AS products,
SUM(CASE WHEN stock = 0 THEN 1 ELSE 0 END) AS sold_out,
SUM(CASE WHEN category = 'tents' THEN stock END) AS tent_units,
COUNT(CASE WHEN price < 50 THEN 1 END) AS under_50,
COUNT(*) FILTER (WHERE price < 50) AS under_50_filter
FROM products;
-- CASE inside WHERE: a different threshold for each category
SELECT name, category, stock
FROM products
WHERE stock < CASE category WHEN 'tents' THEN 5 WHEN 'packs' THEN 10 ELSE 20 END
ORDER BY product_id;
products | sold_out | tent_units | under_50 | under_50_filter
----------+----------+------------+----------+-----------------
7 | 1 | 15 | 3 | 3
(1 row)
name | category | stock
------------------+----------+-------
Summit 4 tent | tents | 3
Basecamp lantern | lighting | 15
Day 18 backpack | packs | 0
(3 rows)
Inside aggregates: conditional counts and sums
The first query computes several counts in one pass over the table:
SUM(CASE WHEN stock = 0 THEN 1 ELSE 0 END)counts sold-out products: each row adds 1 or 0.SUM(CASE WHEN category = 'tents' THEN stock END)adds the stock of tents only. Other rows produce NULL, because there's noELSE, andSUMignores NULLs.COUNT(CASE WHEN price < 50 THEN 1 END)counts the rows where theCASEisn't NULL. The value1doesn't matter:COUNTonly checks for NULL. Don't writeELSE 0here:COUNTcounts zeros too, so you'd count every row.COUNT(*) FILTER (WHERE price < 50)is the standard SQL way to write the same thing. It's clearer, and PostgreSQL and SQLite support it. MySQL, SQL Server and Oracle don't, so conditional aggregation withCASEis the portable form.
This technique is called conditional aggregation, and it's the standard way to turn rows into columns (a pivot), for example one column per category or per month. Article 21 covers it in depth, and article 44 uses it for pivots.
In WHERE
In the second query, the low-stock threshold depends on the category: under 5 for tents, under 10 for packs and under 20 for everything else. CASE computes the threshold for each row. Conditions like this can usually be written with AND/OR as well, and those are often easier for the optimizer to use with indexes. Use CASE in WHERE when it's clearly the more readable choice.
In ORDER BY and GROUP BY
Article 9 used CASE to sort in a custom order. You can also group by a CASE expression, for example to count products per price band. Part 4 shows how.
Does CASE protect against errors?
Because only the chosen branch is evaluated for each row, CASE WHEN qty = 0 THEN NULL ELSE total / qty END is a common way to avoid dividing by zero, and it works in every product. There are two exceptions to keep in mind:
- Aggregates are computed before the
CASEsees them. InCASE WHEN COUNT(*) > 0 THEN SUM(a / b) END, theSUM(a / b)is computed for the whole group first, so a zerobstill raises an error. - Constant expressions may be computed early, while the query is being planned, so a branch like
ELSE 1/0can fail even if it's never chosen. Products differ in when they do this.
For division, total / NULLIF(qty, 0) (article 8) is shorter and avoids both problems.
Shorthand functions
Several common CASE patterns have shorter forms:
| Function | Equivalent CASE | Notes |
|---|---|---|
COALESCE(a, b) | CASE WHEN a IS NOT NULL THEN a ELSE b END | standard, any number of arguments |
NULLIF(a, b) | CASE WHEN a = b THEN NULL ELSE a END | standard |
GREATEST(a, b, ...) | the largest argument | standard since SQL; NULL handling varies |
LEAST(a, b, ...) | the smallest argument | standard since SQL; NULL handling varies |
IIF(cond, a, b) | CASE WHEN cond THEN a ELSE b END | SQL Server and SQLite only |
IF(cond, a, b) | CASE WHEN cond THEN a ELSE b END | MySQL only |
DECODE(x, v1, r1, ..., default) | simple CASE (but treats NULL = NULL as a match) | Oracle only |
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- Shorthand forms that are really CASE: COALESCE, NULLIF, GREATEST, LEAST
SELECT name, stock, weight_g,
GREATEST(stock - 10, 0) AS above_safety_stock,
LEAST(price, 50.00) AS capped_price,
GREATEST(weight_g, 100) AS weight_at_least_100
FROM products
WHERE category IN ('lighting', 'packs')
ORDER BY product_id;
-- A CASE that sorts statuses and labels them in one query
CREATE TABLE shipments (shipment_id INTEGER PRIMARY KEY, status VARCHAR(10));
INSERT INTO shipments VALUES (1, 'shipped'), (2, 'pending'), (3, 'lost'), (4, 'delivered'), (5, 'pending');
SELECT shipment_id, status,
CASE status
WHEN 'pending' THEN 'Waiting to ship'
WHEN 'shipped' THEN 'On its way'
WHEN 'delivered' THEN 'Arrived'
ELSE 'Check with support'
END AS customer_message
FROM shipments
ORDER BY CASE status WHEN 'pending' THEN 1 WHEN 'shipped' THEN 2 WHEN 'delivered' THEN 3 ELSE 4 END,
shipment_id;
name | stock | weight_g | above_safety_stock | capped_price | weight_at_least_100
-------------------+-------+----------+--------------------+--------------+---------------------
Glow head torch | 40 | 90 | 30 | 34.50 | 100
Basecamp lantern | 15 | (null) | 5 | 27.00 | 100
Trail 30 backpack | 22 | 1150 | 12 | 50.00 | 1150
Day 18 backpack | 0 | 640 | 0 | 50.00 | 640
(4 rows)
shipment_id | status | customer_message
-------------+-----------+--------------------
2 | pending | Waiting to ship
5 | pending | Waiting to ship
1 | shipped | On its way
4 | delivered | Arrived
3 | lost | Check with support
(5 rows)
GREATEST(stock - 10, 0)gives the stock above a safety level of 10, never going below zero.LEAST(price, 50.00)caps the price at 50.GREATESTandLEASTdisagree about NULL. PostgreSQL and SQL Server ignore NULL arguments, so the lantern's NULL weight became 100. MySQL and Oracle return NULL if any argument is NULL. If your code must run on several products, wrap the arguments inCOALESCEso that NULLs never reach the function.- The last query uses one
CASEto turn status codes into messages for customers, and a second one to sort the statuses in a business order. If many queries need the same mapping, store it in a table (for example,statuses(code, message, sort_order)) and join to it instead of repeatingCASEeverywhere.
Prefer CASE and the standard functions (COALESCE, NULLIF, GREATEST, LEAST) to IF, IIF and DECODE. They read the same in every product.
What's current
GREATESTandLEASTwere standardized in SQL. SQL Server added them in 2022, so they're now available in PostgreSQL, MySQL, SQL Server and Oracle. SQLite uses multi-argumentmax(a, b)andmin(a, b)instead. NULL handling still differs.- Oracle 23ai and later have a real
BOOLEANtype, so a condition such asprice > 100can be selected directly as a column. In older Oracle versions, you needCASE WHEN price > 100 THEN 'Y' ELSE 'N' END. PostgreSQL, MySQL (as 0/1) and SQLite (as 0/1) already allowed it, and SQL Server still doesn't.
Common questions
Is CASE a statement or an expression?
In a query, it's an expression that returns a value. Procedural languages, such as PL/pgSQL, PL/SQL and T-SQL, also have IF statements, and PL/SQL and PL/pgSQL have CASE statements, which choose which code runs. Part 13 covers them.
What happens if no WHEN matches and there's no ELSE? The result is NULL.
Can a CASE return different types in different branches? Not in standard SQL or PostgreSQL. The branches must have compatible types, such as integer and decimal, and the result has a single common type. Convert values explicitly if the branches would otherwise mix text and numbers.
Can I use a column alias defined in the same SELECT inside a CASE? No. The aliases aren't defined yet when the select list is computed (article 4). Repeat the expression, or compute it in a subquery or common table expression (article 24) and use the alias in the outer query.
Can I nest CASE expressions?
Yes. A THEN or ELSE value can be another CASE. Deep nesting is hard to read, though. Often a single searched CASE with combined conditions is clearer.
Is there a limit to the number of WHEN branches?
Not a practical one for the number of branches, although SQL Server limits nesting of CASE inside CASE to 10 levels. If you have dozens of branches, the mapping is data, and it belongs in a lookup table.
Summary
CASEis a standard expression that returns a value for each row, and it can be used in any clause.- The searched form (
CASE WHEN condition THEN ...) is general. The simple form (CASE expr WHEN value THEN ...) compares with=. WHENs are tested in order, and the first true one wins. With overlapping conditions, put the most specific first.- Without
ELSE, unmatched rows get NULL. A simpleCASE x WHEN NULLnever matches: useWHEN x IS NULL. - All branches must have compatible types.
- Conditional aggregation with
SUM(CASE ...)andCOUNT(CASE ...)computes several counts in one pass and builds pivots.FILTER (WHERE ...)is the standard alternative in PostgreSQL and SQLite. COALESCE,NULLIF,GREATESTandLEASTare shorthand for commonCASEpatterns.GREATESTandLEASThandle NULL differently from product to product.
Practice questions
Write a query that shows each product's name and a stock status: out of stock when stock is 0, low when it's under 15, and ok otherwise.
Answer
SELECT name,
CASE
WHEN stock = 0 THEN 'out of stock'
WHEN stock < 15 THEN 'low'
ELSE 'ok'
END AS stock_status
FROM products
ORDER BY product_id;
The order of the WHENs matters: if stock < 15 came first, the out-of-stock backpack would be labelled low. The Summit 4 tent (3) and the Ridge 2 tent (12) are low, and the lantern (15) is ok, because 15 isn't under 15.
A report uses COUNT(CASE WHEN status = 'late' THEN 1 ELSE 0 END) to count late shipments, but the count always equals the total number of shipments. Why, and how do you fix it?
Answer
COUNT(expression) counts the rows where the expression isn't NULL, and 0 isn't NULL, so every row is counted. Either drop the ELSE, so non-late rows give NULL: COUNT(CASE WHEN status = 'late' THEN 1 END). Or use SUM: SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END). In PostgreSQL and SQLite, COUNT(*) FILTER (WHERE status = 'late') is clearer still.
What does this expression return for a row where brand is NULL, and why? CASE brand WHEN NULL THEN 'none' WHEN 'Lumen' THEN 'L' ELSE 'other' END
Answer
It returns 'other'. A simple CASE compares with =, so the first test is brand = NULL, which is unknown, and the second is NULL = 'Lumen', which is also unknown. Since no WHEN is true, the ELSE value is used. To label the NULL rows 'none', use the searched form: CASE WHEN brand IS NULL THEN 'none' WHEN brand = 'Lumen' THEN 'L' ELSE 'other' END.
In one query, return the number of tents, the number of packs and the total stock of everything else, as three columns.
Answer
SELECT COUNT(CASE WHEN category = 'tents' THEN 1 END) AS tents,
COUNT(CASE WHEN category = 'packs' THEN 1 END) AS packs,
SUM(CASE WHEN category NOT IN ('tents', 'packs') THEN stock END) AS other_stock
FROM products;
This returns 2 tents, 2 packs and 130 units of other stock (40 + 15 + 75). Each row contributes to only the columns whose condition it meets.
Previous: DISTINCT, LIMIT, FETCH FIRST and Pagination in SQL

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.