The snippet library.
Small, practical examples. Search by task or narrow things down below.
Find parents whose every child meets a rule
Postgres: Combine existence with the absence of a violating child to exclude parents with no children.
Postgres✓ Tested
Find parents with at least two child rows
Postgres: Use a correlated count when testing a per-parent threshold.
Postgres✓ Tested
Find records without any related rows
Postgres: NOT EXISTS avoids the NULL pitfalls of NOT IN when the subquery column can be missing.
Postgres✓ Tested
Generate every combination of two sets
Postgres: CROSS JOIN creates one result per possible pair, so the output size is the product of the input sizes.
Postgres✓ Tested
Include zero counts for missing relationships
Postgres: Count the non-null child key after a left join so a missing relationship produces zero.
Postgres✓ Tested
Join a parent to pre-aggregated totals
Postgres: Aggregate the child rows first to produce at most one joined row per parent.
Postgres✓ Tested
Join through a lookup table
Postgres: Use explicit aliases and join keys when enriching records through two relationships.
Postgres✓ Tested
Keep parent rows while filtering joined children
Postgres: Put a child filter in ON when unmatched parents must remain in the result.
Postgres✓ Tested
List unordered pairs without duplicate reversals
Postgres: Join using an increasing key comparison to omit self-pairs and reversed duplicates.
Postgres✓ Tested
Pair employees with their managers
Postgres: Alias a table twice to represent two different roles in one relationship.
Postgres✓ Tested