Lesson 21: CASE Expressions

22 Jul 2026 1 min Swarnil Singhai

CASE lets you compute conditional values directly inside a query — an if/else that lives in SQL instead of application code.

Real-time example

Label each order's size as 'small', 'medium', or 'large' directly in a report query.

SELECT id, amount,
    CASE
        WHEN amount < 500 THEN 'small'
        WHEN amount < 2000 THEN 'medium'
        ELSE 'large'
    END AS order_size
FROM orders;

What's happening

CASE evaluates top to bottom and stops at the first matching WHEN — order your conditions from most to least specific.

CASE inside SUM() is a common trick for conditional aggregation, e.g. counting orders in different buckets in one pass.

Advertisement