SQL CASE WHEN Explained for Beginners (With Examples)
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
Searching for "SQL CASE WHEN explained for beginners"? Here is the short answer. CASE WHEN is how SQL does "if this, then that". It looks at each row, checks a condition, and gives back a value you choose. You can use it to turn numbers into labels like "cheap" or "expensive" without changing your data.
In this guide you will learn what CASE WHEN is, how to write it, and how to use it in real queries. We define every new word the first time we use it. You need no experience beyond a basic SELECT.
SQL (Structured Query Language) is the language used to read and change data stored in a database. A CASE expression is a piece of a query that works like an if/else rule. An expression is just something that produces a value.
Think of a teacher giving grades. If the score is 90 or more, the grade is A. If it is 80 or more, the grade is B. Otherwise, the grade is C. CASE WHEN lets SQL follow the same kind of rule for every row in a table.
A table is a grid of data with columns and rows. Here is a small table called products. You can create it in any SQL database to follow along.
CREATE TABLE products (
id INT,
name VARCHAR(50),
price INT,
stock INT
);
INSERT INTO products (id, name, price, stock) VALUES
(1, 'Notebook', 5, 120),
(2, 'Backpack', 45, 0),
(3, 'Headphones', 80, 15),
(4, 'Pen', 2, 300),
(5, 'Desk Lamp', 30, 4);The first statement builds the table with four columns. The second statement adds five rows. The price and stock columns hold whole numbers, which is perfect for our examples.
Syntax means the exact way you must write something. A CASE expression has this shape:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
ENDSQL checks the WHEN lines from top to bottom. The first one that is true wins, and SQL stops looking at the rest. That order matters, as you will see soon.
Let us add a new column to our results that says whether each product is cheap, normal, or expensive.
SELECT
name,
price,
CASE
WHEN price < 10 THEN 'Cheap'
WHEN price < 50 THEN 'Normal'
ELSE 'Expensive'
END AS price_label
FROM products;Line by line: SELECT name, price shows two normal columns. Then the CASE block checks the price. If it is under 10, the label is Cheap. If not, SQL tries the next line: under 50 gives Normal. Anything left over gets Expensive from the ELSE. AS price_label gives the new column a friendly name, which is called an alias. FROM products says which table to read.
| name | price | price_label |
|---|---|---|
| Notebook | 5 | Cheap |
| Backpack | 45 | Normal |
| Headphones | 80 | Expensive |
| Pen | 2 | Cheap |
| Desk Lamp | 30 | Normal |
Notice that the Backpack costs 45, which is under 50, so it is Normal. We did not need to write "price >= 10 AND price < 50" because the Cheap line already caught everything below 10. This is why the order of WHEN lines matters.
CASE WHEN works with any column. Let us tell customers if an item is available.
SELECT
name,
stock,
CASE
WHEN stock = 0 THEN 'Out of stock'
WHEN stock <= 5 THEN 'Low stock'
ELSE 'In stock'
END AS stock_status
FROM products;Here the first WHEN checks for exactly zero using =. The second catches small amounts of 5 or fewer using <=. Everything else is In stock. Our Backpack shows Out of stock, and the Desk Lamp shows Low stock.
When you are only checking one column for exact matches, there is a shorter style. You write the column once after CASE, and then list the values.
SELECT
name,
CASE id
WHEN 1 THEN 'First item'
WHEN 2 THEN 'Second item'
ELSE 'Other item'
END AS position
FROM products;CASE id means "look at the id column". Each WHEN is then compared with = automatically. This form cannot use < or >, so for ranges use the first style from the earlier examples.
CASE becomes very powerful when you combine it with grouping. GROUP BY puts rows with the same value together so you can count or add them. Let us count how many products are in each price label.
SELECT
CASE
WHEN price < 10 THEN 'Cheap'
WHEN price < 50 THEN 'Normal'
ELSE 'Expensive'
END AS price_label,
COUNT(*) AS total
FROM products
GROUP BY price_label;The CASE creates the labels. GROUP BY gathers the rows by label. COUNT(*) counts how many rows are in each group. The result is Cheap 2, Normal 2, Expensive 1. Some databases, such as SQL Server, need you to repeat the whole CASE inside GROUP BY instead of using the alias. If you see an error, try that.
A popular trick is putting CASE inside a function like SUM. This lets you count rows that match a rule, all in one query.
SELECT
SUM(CASE WHEN stock = 0 THEN 1 ELSE 0 END) AS sold_out,
SUM(CASE WHEN stock > 0 THEN 1 ELSE 0 END) AS available
FROM products;For each row, the CASE returns 1 if the rule is true and 0 if not. SUM then adds up all those ones and zeros. So sold_out becomes 1 and available becomes 4. It is a neat way to build a small report.
You can also use CASE to sort in a custom order. Maybe you want out-of-stock products shown last.
SELECT name, stock
FROM products
ORDER BY
CASE WHEN stock = 0 THEN 1 ELSE 0 END,
name;Rows with stock available get 0, and sold-out rows get 1. Sorting is from small to large, so 0 comes first and 1 comes last. After that, name sorts each group alphabetically.
| Where you use it | What it does |
|---|---|
| SELECT | Creates a new label or value column |
| GROUP BY | Groups rows by your custom labels |
| Inside SUM or COUNT | Counts only rows that match a rule |
| ORDER BY | Sorts rows in a custom order |
Want to see how counting and grouping work on their own? Read our beginner guide to GROUP BY first, then come back and combine it with CASE.
Read: SQL GROUP BY ExplainedCASE WHEN checks conditions one by one and returns a value for the first condition that is true. It works like if/else in other languages. You use it to create labels, categories, or custom values in your query results.
Yes. Combine tests with AND or OR, for example WHEN price < 50 AND stock > 0 THEN 'Buy now'. Use brackets if you mix AND and OR so the logic is clear.
No, but it is a good habit. If no WHEN matches and there is no ELSE, SQL returns NULL for that row. Adding ELSE makes the result predictable.
No. In a SELECT query it only changes what you see in the results. Your stored data stays the same. You can use CASE inside UPDATE if you do want to change stored values.
Yes. CASE WHEN is part of standard SQL, so it works in all major databases. Small differences exist, such as using an alias in GROUP BY, but the basic syntax is the same.
Learning SQL or building something with a database? Our team can help you design, build and launch it.
Talk to FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
JavaScript promises explained for beginners: learn pending, fulfilled and rejected, then(), catch(), finally() and Promise.all with simple runnable examples.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.