Imagine This
You’re running a lemonade stand. At the end of the day, you look at your sales and want to say something about each customer’s order:
- If they bought more than 5 cups, say: “Big order”
- If they bought 5 or less, say: “Small order”
Instead of checking and writing this by hand, you want the database to decide it for you. That’s what a CASE
statement does in SQL — it makes decisions based on conditions.
Your Sales Table (orders)
id | customer | cups |
---|---|---|
1 | Alice | 2 |
2 | Ben | 6 |
3 | Charlie | 4 |
4 | Diana | 8 |
SQL Query Using CASE
SELECT customer, cups,
CASE
WHEN cups > 5 THEN 'Big order'
ELSE 'Small order'
END AS order_size
FROM orders;
Output
customer | cups | order_size |
---|---|---|
Alice | 2 | Small order |
Ben | 6 | Big order |
Charlie | 4 | Small order |
Diana | 8 | Big order |
How It Works
- The database looks at each row, one at a time.
- It checks: Is
cups > 5
? - If yes, it writes “Big order”.
- If no, it writes “Small order”.
The result is a new column that tells you something meaningful about each order.
Why Use CASE?
- To add labels or categories to your data automatically
- To apply logic or conditions inside a query
- To make results more readable and easier to understand