Memra

EXISTS and correlated subqueries

◈ 2 cards

Test for the existence of related rows.

Does a related row exist?

A correlated subquery references the outer row, running once per outer row. EXISTS returns true the moment it finds any matching row — efficient for "has at least one". "Books that have been reviewed":

SELECT title FROM books b
WHERE EXISTS (
  SELECT 1 FROM reviews r WHERE r.book_id = b.id
);

NOT EXISTS flips it — "books with no reviews". This is often clearer (and faster) than the LEFT JOIN ... IS NULL anti-join.

outer row binner probeEXISTSNOT EXISTSThe Glass Forest3 reviews foundtruefalseRivers of Saltno rowsfalsetrueThe inner query runs once per outer row.
The inner query mentions b.id, so it cannot run on its own — it is re-evaluated for every candidate book. EXISTS stops at the first row it finds, which is why it never has to count them.
NORMAL ~/memra/learn/postgresql/exists-correlated utf-8 LF