Ad space (banner)
🗄️SQL Lessons
Lesson 40 / 50

Conditional Aggregation with CASE

This lesson covers conditional aggregation with CASE, so a single query can count several conditions at once. It's for anyone searching "SQL conditional COUNT CASE."

Nesting a CASE expression inside COUNT() lets you count only the rows that match a condition — computing "how many scored 80+" and "how many didn't" in the same query, side by side.

The example uses COUNT(CASE WHEN score >= 80 THEN 1 END), which counts 1 only for matching rows — non-matching rows become NULL (since ELSE is omitted) and are excluded from the count. This is a neat trick built on the fact that COUNT() ignores NULL values.

A common early mistake is not understanding why ELSE can be safely skipped — a CASE with no ELSE defaults to NULL for non-matches, and since COUNT() ignores NULL, the net effect is "count only the matching rows." Getting several conditional counts side by side in a single query — without running it multiple times and stitching results together — is a technique that meaningfully speeds up building dashboards and reports.

SQL
OUTPUT

💡 The SQL engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)