Finding Parents Without a Related Row

A NOT EXISTS predicate keeps a parent when a related-row query returns no rows meeting its criteria.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an incomplete catalogue
  2. Check more than an empty relationship
  3. Define which absent match qualifies a parent
  4. Check a fixture with no reports and one with duplicates

Trace an incomplete catalogue

An author with draft books only can count as having no published book if the subquery requires published status. Testing existence gives the matching predicate to complement.

Check more than an empty relationship

Use one author with no books, one with only drafts, and one with both types. They exercise different reasons for a false subquery outcome. Decision cases help keep the population explicit.[1]

Define which absent match qualifies a parent

A branch counts as missing a weekly report if no report with that branch ID and requested week exists. A report for a different week does not satisfy the condition. See negating quantified conditions.

Branches 1 and 2
Reports: branch 1 week 10, branch 2 week 9
Query for missing week 10 → branch 2 only

Check a fixture with no reports and one with duplicates

Duplicating a match still disqualifies its parent once under an absence predicate. An empty related table qualifies every parent for that condition. Keep the correlation and filter in the subquery.

References

  1. PostgreSQL Global Development Group, Queries ↩