Video in progress
Where is the `CASE` expression used in SQL? Give an example.
CASE is if/else inside SQL: it returns a different value for each row depending on a condition. You can use it in SELECT to compute a column, in ORDER BY for a custom sort order, and inside an aggregate for conditional counting.
📖 Answer
Turning a status into a readable name:
SELECT id,
CASE status
WHEN 'NEW' THEN 'Yangi'
WHEN 'PAID' THEN 'To''langan'
ELSE 'Boshqa'
END AS status_label
FROM orders;
Its most useful role is several calculations in one query:
SELECT count(*) AS jami,
sum(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END) AS tolangan,
sum(CASE WHEN status = 'CANCELLED' THEN total END) AS bekor_summa
FROM orders
WHERE created_at >= date_trunc('month', now());
In PostgreSQL you can write this more briefly: count(*) FILTER (WHERE status = 'PAID').
For a custom sort order:
ORDER BY CASE priority WHEN 'HIGH' THEN 1 WHEN 'MEDIUM' THEN 2 ELSE 3 END;
If you leave out ELSE and no condition matches, the result is NULL. People forget this a lot.
Sign up to mark studied questions and save your progress.