sqlbeginner

CASE WHEN Conditional Expressions

Use CASE expressions for conditional logic in SELECT, WHERE, ORDER BY, and aggregations.

sql
-- 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.