Case Statements: CASE WHEN … THEN … END

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)

idcustomercups
1Alice2
2Ben6
3Charlie4
4Diana8

SQL Query Using CASE

SELECT customer, cups,
  CASE
    WHEN cups > 5 THEN 'Big order'
    ELSE 'Small order'
  END AS order_size
FROM orders;

Output

customercupsorder_size
Alice2Small order
Ben6Big order
Charlie4Small order
Diana8Big 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top