Fan-out, Semi-join & Anti-join in SQL
Why SUM double-counts after JOIN — and EXISTS fixes it
One-to-many matches replicate the one-side row per match — aggregating after fan-out double-counts (SUM over duplicated salaries). Fix by pre-aggregating the many-side in a CTE, or use semi-join (EXISTS/IN — existence without duplication) and anti-join (NOT EXISTS — rows with no match, NULL-safe unlike NOT IN).
Fan-out replicates
One-to-many matches copy the one-side row per match. SUM after fan-out double-counts.
Pre-aggregate first
Roll the many-side to one row per key in a CTE, then join. Canonical fix.
Semi-join checks existence
EXISTS returns left rows having a match — never duplicated, short-circuits.
Anti-join checks absence
NOT EXISTS returns left rows with no match — NULL-safe. NOT IN is poisoned by NULLs.
1SELECT * FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id);
| dept_id | location | head |
|---|---|---|
| Engineering | Berlin | Cynthia |
| Sales | Madrid | Elena |
| Marketing | Lisbon | David |
Each department asks: does any employee point at me? All three do, each returned exactly once — no duplication even though Engineering matches three employees. A JOIN would have tripled it.
Semi-join without duplication
Engineering matches thrice but returns once.
1SELECT * FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id);
| dept_id | location | head |
|---|---|---|
| Engineering | Berlin | Cynthia |
| Sales | Madrid | Elena |
| Marketing | Lisbon | David |
Pre-aggregate before join
Fan-out-proof totals.
1SELECT d.dept_id, COALESCE(t.total, 0) AS total FROM departments d LEFT JOIN (SELECT department, SUM(salary) AS total FROM employees GROUP BY department) t ON t.department = d.dept_id;
| dept_id | total |
|---|---|
| Engineering | 249000 |
| Sales | 110000 |
| Marketing | 47000 |
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.