Counting Children for Every Parent
A report can keep parents without matching children by using an outer join and counting a present column identifying a matched child.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace two categories
Category A with two articles should give count two. Category B without articles should give zero. In a left join, B can still produce a row with null child fields. Count a non-nullable article ID rather than every result row. See SQL counts.
Check parent coverage
Starting only from articles would never observe B. One-to-many relationships explain why an independent category table can supply every parent.[1]
Count a child field after preserving parents
A left join retains a parent with no child by producing one row containing null child fields. Counting joined rows gives that parent one. Counting a non-null child identifier gives zero and matches the number of actual children. See left joins and unmatched rows.
WITH parents(id) AS (VALUES (1), (2)), children(id, parent_id) AS (VALUES (9,1), (10,1))
SELECT p.id, COUNT(*) AS rows, COUNT(c.id) AS children
FROM parents p LEFT JOIN children c ON c.parent_id = p.id GROUP BY p.id ORDER BY p.id;
-- Expected: (1,2,2), (2,1,0).
Check multiplicity when joining additional tables
Adding a second one-to-many join can multiply child rows. Compare known counts before and after that change. Use a distinct identifier or preaggregation where the query grain requires it.