SQL Interview & Case Lab
Back to Interview SQL Patterns

Pivot Using CASE WHEN — Cross-Database Compatibility

PIVOT is vendor-specific. CASE WHEN works everywhere. Here's the canonical pattern. FIND_VIDEO: search 'SQL pivot CASE WHEN tutorial' — recommended channel: Alex Freberg / EverSQL. Aim for 9 min or under.

6 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Problem Overview — Introduces the fintech interview problem requiring net user balances from credit and debit transactions.
  2. Conditional Aggregation Setup — Constructs the `CASE WHEN` aggregation and applies `LOWER()` to normalize transaction types.
  3. CTE Encapsulation — Wraps aggregated credit and debit columns into a CTE to calculate net balance via column subtraction.
  4. NULL Value Handling — Demonstrates why NULL categories break balance subtraction and resolves the issue using `IFNULL()`.
PDF notes

Frequently asked questions

Why use conditional aggregation over native PIVOT syntax?

Conditional aggregation using `CASE WHEN` works identically across all SQL dialects, whereas `PIVOT` is vendor-specific and not supported in engines like MySQL.

Why does subtracting a NULL debit from a credit result in NULL?

Standard SQL three-valued logic dictates that any arithmetic operation involving `NULL` evaluates to `NULL`, which is why missing categories must default to 0 via `IFNULL`.

Can I provide ELSE 0 inside the CASE WHEN instead of IFNULL?

Yes, specifying `ELSE 0` inside `SUM(CASE WHEN ... ELSE 0 END)` ensures the sum returns 0 instead of `NULL` when no matching rows exist for a group.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.