Memra

EXISTS and correlated subqueries

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.

NORMAL ~/memra/learn/postgresql/exists-correlated utf-8 LF