Testing Whether a Related Row Exists

EXISTS asks whether a subquery has at least one row. A Boolean existence test avoids duplicating outer results for multiple matches.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace one author
  2. Choose a useful correlation
  3. Return parent rows without adding multiplicities
  4. Verify the inner query is connected to the parent

Trace one author

An author with three published titles can appear once in a list of authors with any published title. A matched-pair join can supply three author-title pairs instead.

Choose a useful correlation

Restrict the subquery to the current author's key under the query's relationship rule. Test an author with none and another with multiple. See semijoins and antijoins.[1]

Return parent rows without adding multiplicities

A catalogue report asks which folders contain any image. Folder one has two images. An existence predicate qualifies folder one once, since it tests whether at least one matching row exists. See existential tests.

WITH folders(id) AS (VALUES (1),(2)), files(folder_id, kind) AS (VALUES (1,'image'),(1,'image'),(2,'text'))
SELECT f.id FROM folders f WHERE EXISTS (
  SELECT 1 FROM files x WHERE x.folder_id = f.id AND x.kind = 'image'
);
-- Expected: folder 1 once.

Verify the inner query is connected to the parent

Omitting the matching folder ID would allow one image anywhere to qualify every folder. Include one folder with no qualifying image to catch that defect. Test the related filter itself separately.

References

  1. PostgreSQL Global Development Group, Queries ↩