Learn SQL
-- aggregations.conditional_agg

Conditional Aggregation & Dup Finder in SQL

Pivot without PIVOT; catch duplicates in one scan

--concept

CASE inside aggregates computes per-category counts in one pass — SUM(CASE WHEN department = 'Engineering' THEN 1 ELSE 0 END). PostgreSQL/SQLite offer cleaner FILTER (WHERE …). Same GROUP BY + HAVING COUNT(*) > 1 finds duplicates on supposed-unique columns (emails) — the data-quality audit.

--how it works
1

FILTER counts subsets

COUNT(*) FILTER (WHERE …) tallies one category inside a grouped query.

2

CASE is portable

SUM(CASE WHEN … THEN 1 ELSE 0 END) — same result where FILTER is unsupported.

3

One scan, many answers

Pivoted columns emerge from a single GROUP BY pass, not N queries.

4

HAVING finds dupes

GROUP BY key HAVING COUNT(*) > 1 is the duplicate detector and quality audit.

--visualization
FILTER: eng=3, sales=2 in ONE scan
engsales
32
Stage 1 / 1
One grouped pass replaces N queries. FILTER and CASE compile identically.
--example
query.sql
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
Result
engsales
32

One scan produces both pivoted counts: 3 Engineering, 2 Sales. The CASE fallback gives identical results on engines without FILTER.

--variants

Pivot headcount

Engineering vs Sales in one row.

query.sql
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
Result
engsales
32
1Full table scanned once.
2Each FILTER tallies its slice.
3CASE fallback: SUM(CASE WHEN …) identical.

Duplicate emails

supposed-unique column audit.

query.sql
1SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1;
Result
emailn
a@x.com2
1GROUP BY collapses per email.
2HAVING keeps only multi-row groups.
3WHERE could not do this — counts do not exist yet there.
--key facts
FILTERmodern; CASE-in-agg is portable fallback
Dup patternGROUP BY key HAVING COUNT(*) > 1
One passconditional agg beats N queries
--use cases
Funnel pivots: signups by channel in one query
Data-quality monitors: dupe, null-rate checks
--under the hood
FILTER/CASE aggregate in one grouped pass — N separate SELECTs would rescan N times.
HAVING without GROUP BY treats the table as one group.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.