Conditional Aggregation & Dup Finder in SQL
Pivot without PIVOT; catch duplicates in one scan
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.
FILTER counts subsets
COUNT(*) FILTER (WHERE …) tallies one category inside a grouped query.
CASE is portable
SUM(CASE WHEN … THEN 1 ELSE 0 END) — same result where FILTER is unsupported.
One scan, many answers
Pivoted columns emerge from a single GROUP BY pass, not N queries.
HAVING finds dupes
GROUP BY key HAVING COUNT(*) > 1 is the duplicate detector and quality audit.
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
| eng | sales |
|---|---|
| 3 | 2 |
One scan produces both pivoted counts: 3 Engineering, 2 Sales. The CASE fallback gives identical results on engines without FILTER.
Pivot headcount
Engineering vs Sales in one row.
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
| eng | sales |
|---|---|
| 3 | 2 |
Duplicate emails
supposed-unique column audit.
1SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1;
| n | |
|---|---|
| a@x.com | 2 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.