π SQL CASE β Apply Conditional Logic in Queries
π§² Introduction β What is SQL CASE?
The CASE expression in SQL allows you to apply conditional logic inside your queries. Think of it as SQLβs version of IF...ELSE. It’s used to return custom values based on conditionsβideal for categorizing, labeling, or transforming query output.
π― In this guide, youβll learn:
- Basic syntax of
CASEandWHEN - Use
CASEinSELECT,WHERE, andORDER BY - The difference between simple and searched CASE
- Best practices and performance tips
β 1. Basic CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
β Use it to return different values based on matching conditions.
π― 2. CASE in SELECT Clause
SELECT name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
ELSE 'F'
END AS grade
FROM students;
β Assigns letter grades based on score ranges.
π§ 3. CASE in ORDER BY
SELECT name, status
FROM tasks
ORDER BY
CASE status
WHEN 'urgent' THEN 1
WHEN 'normal' THEN 2
ELSE 3
END;
β Custom sorting logic based on priority.
π 4. CASE in WHERE Clause
SELECT * FROM orders
WHERE
CASE
WHEN customer_type = 'VIP' THEN total > 500
ELSE total > 1000
END;
β Applies different filters based on customer type.
π§Ύ 5. Simple vs. Searched CASE
Simple CASE
CASE status
WHEN 'active' THEN 'In Use'
WHEN 'inactive' THEN 'Disabled'
ELSE 'Unknown'
END
Searched CASE
CASE
WHEN status = 'active' AND last_login > '2023-01-01' THEN 'Returning'
WHEN status = 'inactive' THEN 'Churned'
ELSE 'Unknown'
END
β Simple matches a fixed column; searched uses boolean logic.
π Best Practices
| β Recommended | β Avoid This |
|---|---|
| Use searched CASE for complex logic | Nesting too many CASE expressions |
| Add ELSE to avoid NULLs in edge cases | Leaving out ELSE (defaults to NULL) |
| Format code for readability | Cramming CASE into one line |
π Summary β Recap & Next Steps
The SQL CASE expression empowers you to add decision-making logic directly inside your queriesβno procedural code required.
π Key Takeaways:
- Use
CASEto replace IF…ELSE logic in SQL - Integrate with SELECT, WHERE, ORDER BY, GROUP BY
- Prefer searched CASE for custom conditions
βοΈ Real-World Relevance:
Used in reporting, dashboards, conditional formatting, dynamic sorting, and business rules.
β‘οΈ Next: Explore COALESCE and NULLIF for advanced expression control.
β FAQ β SQL CASE Expression
β What is SQL CASE used for?
β To apply conditional logic and return values based on different conditions.
β Is CASE an IF statement?
β
Yes. CASE is SQLβs way of writing IF...ELSE logic inside queries.
β Can I use CASE in WHERE clause?
β Yes, but itβs less readable. Prefer boolean logic where possible.
β What happens if no WHEN condition matches?
β
If thereβs no ELSE, it returns NULL.
β Can I nest CASE statements?
β Yes, but keep it readable and avoid excessive nesting.
Share Now :
