What is CASE?
- SQL course
- Intermediate
- Lesson 65/115
- 4 min
Use CASE for conditional output.
What is CASE?
CASE lets you write conditional expressions. It produces different results based on a column value.
SELECT name,
CASE WHEN price > 100 THEN 'pahalı'
ELSE 'ucuz' END AS tier
FROM products;This query tags each product as expensive or cheap.
name, CASE WHEN price > 100 THEN 'pahalı' ELSE 'ucuz' END … is selected from products.
What is CASE? — details
CASE WHEN sets the condition, THEN the result. ELSE is the default, END closes it.
For example, CASE WHEN price > 100 THEN 'pahalı' ELSE 'ucuz' END labels each product by its price.
Practice What is CASE?
Tag each product by price with CASE WHEN price > 100 THEN 'pahalı' ELSE 'ucuz' END.
Starter code
-- conditional tag
SELECT name,
CASE WHEN price > 100 THEN 'pahalı' ELSE 'ucuz'Sample solution
SELECT name,
CASE WHEN price > 100 THEN 'pahalı'
ELSE 'ucuz' END AS tier
FROM products;Expected output
name tier Laptop pahalı Kalem ucuz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does CASE do?
- Filtering
- Sorting
- Grouping
- A conditional expression Correct answer
Explanation: CASE produces conditional expressions.
2 Add END
SELECT name,
CASE WHEN price > 100 THEN 'pahalı' ELSE 'ucuz' ____ AS tier
FROM products;
SELECT name,
CASE WHEN price > 100 THEN 'pahalı' ELSE 'ucuz' END AS tier
FROM products;
Explanation: Every CASE expression ends with END, then AS names the column.
3 What is CASE: match the terms
| Term | Meaning |
|---|---|
CASE WHEN |
condition |
THEN |
result |
ELSE |
default |
END |
close |