SQL · Module 03: Aggregations, GROUP BY & CASE WHENTutorial 9 of 24

3.3 CASE WHEN, Conditional Aggregation & Pivoting Data

Write if-else logic inside SQL with CASE WHEN, compute multiple filtered KPIs in a single table scan using Conditional Aggregation (SUM(CASE WHEN ...)), and pivot rows into columns.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. If-Else Logic Inside SQL (CASE WHEN)

CASE WHEN is SQL's built-in if / elif / else expression. You can place it almost anywhere an expression is valid: inside SELECT to bucket metrics, inside ORDER BY for custom priority sorting, inside GROUP BY to group by dynamic tiers, or inside aggregate functions like SUM() and COUNT().

Crucially, CASE WHEN short-circuits from top to bottom and returns the value of the first branch that evaluates to TRUE. Once a row matches a WHEN condition, SQL skips all remaining branches — which means you should always order range thresholds from most restrictive to least restrictive (for example, >= 90 before >= 75).

SQL
SELECT
    name,
    score,
    CASE
        WHEN score >= 90 THEN 'A (Distinction)'
        WHEN score >= 75 THEN 'B (First Class)'
        WHEN score >= 50 THEN 'C (Pass)'
        ELSE 'F (Needs Review)'
    END AS grade
FROM students
ORDER BY score DESC;

3 Common CASE WHEN Pitfalls to Avoid

  1. Missing ELSE silently returns NULL: If no WHEN branch matches and you omit ELSE, SQL returns NULL — which can later break CONCAT() or skew averages. Always add an explicit ELSE unless NULL is intentional.
  2. Never write CASE col WHEN NULL: In SQL three-valued logic, col = NULL is always UNKNOWN, never TRUE! Always use the Searched CASE syntax (WHEN col IS NULL THEN ...) whenever checking for missing values.
  3. Keep THEN return types compatible: Every branch in a CASE expression must resolve to a compatible data type (don't return 'Free' in one branch and integer 100 in another — cast both to text or keep both numeric).

Simple CASE vs Searched CASE

StyleSyntaxBest For
Simple CASECASE status WHEN 'paid' THEN 1 ELSE 0 ENDExact equality checks on one non-null column
Searched CASE (Recommended)CASE WHEN score >= 90 AND active THEN 'Top' ELSE 'Std' ENDRanges (>=, <), IS NULL, and compound AND/OR logic

2. The Analytics Superpower: Conditional Aggregation (Pivoting Rows → Columns)

Suppose a product manager asks for one executive dashboard table showing each city's total_orders, paid_orders, cancelled_orders, paid_revenue, and conversion_pct.

Beginners run three separate queries with different WHERE status = ... filters and stitch them together in Python or Excel. On a 20-million-row orders table, that forces the database to scan the table three separate times. Senior engineers compute every metric in ONE single table scan using Conditional Aggregation — wrapping CASE WHEN inside SUM():

SQL
SELECT
    city,
    COUNT(*)                                                   AS total_orders,
    SUM(CASE WHEN status = 'paid'      THEN 1 ELSE 0 END)      AS paid_orders,
    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)      AS cancelled_orders,
    SUM(CASE WHEN status = 'paid'      THEN amount ELSE 0 END) AS paid_revenue,
    ROUND(
        100.0 * SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) / COUNT(*),
        1
    ) AS conversion_pct
FROM orders
GROUP BY city
ORDER BY paid_revenue DESC;

Classic SQL Interview Trap (SUM vs COUNT): Never write COUNT(CASE WHEN status = 'paid' THEN 1 ELSE 0 END)! Because COUNT() counts every non-NULL value (including 0), that expression returns the total row count instead of paid rows. Either use SUM(... THEN 1 ELSE 0 END) or drop the ELSE 0 so unmatched rows evaluate to NULL: COUNT(CASE WHEN status = 'paid' THEN 1 END).

PostgreSQL vs MySQL Shorthands

Standard SUM(CASE WHEN ...) works identically across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery, so it is your safest choice for interviews and portable SQL. However, both major engines also offer concise dialects:

  • PostgreSQL (ANSI SQL Standard): Supports the ultra-readable FILTER (WHERE ...) clause on any aggregate function:
SQL
SELECT
    city,
    COUNT(*)                                                AS total_orders,
    COUNT(*) FILTER (WHERE status = 'paid')                 AS paid_orders,
    COALESCE(SUM(amount) FILTER (WHERE status = 'paid'), 0) AS paid_revenue
FROM orders
GROUP BY city;
  • MySQL: Evaluates boolean expressions as 1 (true) or 0 (false), so you will often see SUM(status = 'paid') in MySQL codebases. Avoid relying on that in PostgreSQL, which strictly separates BOOLEAN from INTEGER.

3. Bonus Production Pattern: Custom ORDER BY Sorting with CASE WHEN

Alphabetical sorting fails whenever a column has business-defined priority levels like 'urgent', 'high', 'medium', and 'low' (alphabetically 'high' would wrongly come before 'urgent'). Put CASE WHEN directly inside ORDER BY to define any custom sort rank:

SQL
SELECT ticket_id, title, priority
FROM support_tickets
WHERE is_open = TRUE
ORDER BY
    CASE priority
        WHEN 'urgent' THEN 1
        WHEN 'high'   THEN 2
        WHEN 'medium' THEN 3
        ELSE 4
    END,
    created_at ASC;

4. Watch Conditional Aggregation Pivot a Table Live

Tracing Conditional Aggregation (SUM + CASE WHEN)
Interactive SQL Execution Tracer · Step 1 of 3 (1. FROM orders)
1SELECT city,
2 SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_cnt,
3 SUM(CASE WHEN status = 'paid' THEN amt ELSE 0 END) AS paid_rev
4→FROM orders
5GROUP BY city;
Live Table State · 1. FROM orders4 rows
citystatusamt
Bengalurupaid1200
Bengalurucancelled800
Bengalurupaid500
Punepaid900
What the DB engine just did: Raw orders table contains both paid and cancelled rows across 2 cities.

5. Quick Check Your Understanding

Module 3.3 Quick Quiz

Q1.What does COUNT(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) return on 10 rows where only 3 are paid?
Q2.In a CASE WHEN chain, what happens if two WHEN conditions are both TRUE for a row?

Keep Exploring: Related Lessons & Tools

All Courses →