sqlbeginner
CASE WHEN Conditional Expressions
Use CASE expressions for conditional logic in SELECT, WHERE, ORDER BY, and aggregations.
sqlPress ⌘/Ctrl + Shift + C to copy
-- Categorize data
SELECT name, price,
CASE
WHEN price < 10 THEN 'budget'
WHEN price < 50 THEN 'mid-range'
WHEN price < 200 THEN 'premium'
ELSE 'luxury'
END AS price_tier
FROM products;
-- Conditional aggregation
SELECT department,
COUNT(*) AS total,
COUNT(CASE WHEN status = 'active' THEN 1 END) AS active,
COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive
FROM employees
GROUP BY department;
-- Custom sort order
SELECT name, priority
FROM tickets
ORDER BY
CASE priority
WHEN 'critical' THEN 1
WHEN 'high' THEN 2
WHEN 'medium' THEN 3
WHEN 'low' THEN 4
END;Use Cases
- data categorization
- conditional aggregation
- custom sorting
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqlintermediate
Conditional Aggregation with FILTER / CASE
Compute multiple conditional aggregates in a single query using FILTER or CASE.
Best for: Pivot-style reports
#sql#conditional
sqladvanced
Recursive CTE for Hierarchical Data
Query hierarchical data like org charts, categories, and file trees using recursive CTEs.
Best for: Querying organizational hierarchies
#sql#cte
sqlintermediate
SQL Pivot and Crosstab Queries
Transform row data into columnar reports using CASE expressions, FILTER, and crosstab patterns.
Best for: Creating monthly revenue reports
#sql#pivot
sqlintermediate
SQL Upsert and Merge Patterns
Insert or update records atomically using ON CONFLICT, MERGE, and database-specific upsert syntax.
Best for: Syncing data from external sources
#sql#upsert