Conditional logic & CASE
Concept  ·  SQL & Querying

SUM(CASE WHEN ... THEN amount END) is the pivot workhorse; a missing ELSE means NULL (usually right — the 0-vs-NULL choice made explicit).

SUM(CASE WHEN cond THEN x END) is the pivot workhorse — one column per condition, aggregated in a single pass. The classic slip is COUNT over a CASE with an ELSE 0: COUNT counts non-NULL values, and 0 is non-NULL, so it counts every row.

See it break
sales
regionamount
N100
S200
N50
The trap
SELECT
  COUNT(
    CASE
      WHEN region = 'N' THEN 1
      ELSE 0
    END
  ) AS n
FROM
  sales;
The fix
SELECT
  SUM(
    CASE
      WHEN region = 'N' THEN 1
      ELSE 0
    END
  ) AS n
FROM
  sales;
The trap
3
The fix
2

The 'North sales count' reads 3, not 2 — COUNT counts the ELSE 0 rows too, because 0 is not NULL; SUM adds the flags instead.

The rule

Sum the flags with SUM(CASE WHEN cond THEN 1 ELSE 0 END), or drop the ELSE and COUNT the CASE so the non-matches stay NULL.

SUM(CASE WHEN region = 'E' THEN amount END)
Shows up elsewhere
Pivot via conditional aggregation
Try one →Prove it in practice →