Skip to content
>_sqlbuddy

SQL Topic

Conditional Aggregation

Conditional aggregation uses CASE WHEN inside an aggregate to compute different buckets in one pass — the standard pivot technique: SUM(CASE WHEN quarter = 1 THEN revenue END) AS q1.

When is Conditional Aggregation used?

Pivoting rows into columns, computing several metrics per group in one query, and percentage calculations.

Core syntax

SELECT year, SUM(CASE WHEN quarter = 1 THEN revenue END) AS q1 FROM sales GROUP BY year.

Common mistakes

  • Forgetting ELSE 0 when NULLs must count as zero.
  • Using FILTER (WHERE ...), which SQLite does not support.
  • Grouping by the wrong granularity and getting one row per bucket instead of per group.

Practice Conditional Aggregation questions

Work through them in order — each question builds on the last.

Related topics

Interview preparation