A label such as "out of stock" or "low" is not in the table. CASE makes it from the values in each row.
sql
SELECT name, price,
CASE
WHEN price < 10 THEN 'budget'
WHEN price < 30 THEN 'standard'
ELSE 'premium'
END AS band
FROM products;CASEstartWHEN price < 10 THEN 'budget'if this is true, return thisWHEN price < 30 THEN 'standard'else, if this is true…ELSE 'premium'no WHEN was trueENDend
CASE tests the WHEN conditions from top to bottom, for each row. It returns the THEN value of the first condition that is true, and stops.
result
| name | price | band |
|---|---|---|
| Cluster Socks | 9.50 | budget |
| Kernel Panic Mug | 14.00 | standard |
| Root Hoodie | 49.95 | premium |
- The order of the WHEN lines matters. Put the narrowest condition first.
ELSEis optional. Without it, a row with no true WHEN gets NULL.ENDcloses the CASE. Give the column a name with AS.- A CASE is an expression. You can use it in the SELECT list, in WHERE and in ORDER BY.