The CASE statement lets you apply conditional logic inside SQL queries โ like if/else in programming.
1๏ธโฃ Basic CASE Syntax
SELECT name, salary,
CASE
WHEN salary > 80000 THEN 'High'
WHEN salary BETWEEN 50000 AND 80000 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
โ Categorizes salaries as High, Medium, or Low.
2๏ธโฃ CASE in ORDER BY
Sort based on custom logic.
SELECT name, department
FROM employees
ORDER BY
CASE department
WHEN 'HR' THEN 1
WHEN 'Engineering' THEN 2
ELSE 3
END;
โ HR shows up first, then Engineering, then others.
3๏ธโฃ CASE in WHERE Clause
Control filtering logic conditionally.
SELECT *
FROM orders
WHERE status =
CASE
WHEN customer_type = 'VIP' THEN 'priority'
ELSE 'standard'
END;
4๏ธโฃ Nested CASE (Advanced)
SELECT name, marks,
CASE
WHEN marks >= 90 THEN 'A'
WHEN marks >= 75 THEN
CASE WHEN marks >= 85 THEN 'B+' ELSE 'B' END
ELSE 'C'
END AS grade
FROM students;
๐ฏ Use CASE When You Want To:
โข Create labels or buckets
โข Replace multiple IF conditions
โข Make results more readable
๐ Practice Tasks:
1. Add a column that shows โPassโ or โFailโ based on marks
2. Create a salary band (Low/Medium/High) using CASE
3. Use CASE to sort products as 'Electronics' first, then 'Clothing'
๐ฌ Tap โค๏ธ for more!