skip to content

EXISTS, semi joins and anti joins

is there a match? the join that never duplicates, the one that keeps only the lonely rows, and relational division.

address
everything.joins.exists_semi_anti
part
part 3, joins and subqueries
chapter
chapter 7 of 11
reading time
8 min

EXISTS (subquery) asks one question per row: is there at least one match? keep the row once if there is, and that's a semi join. NOT EXISTS keeps the rows with no match at all, an anti join. neither one duplicates a row, and neither adds a column.

"which students took every CS course" is relational division, and it's a NOT EXISTS inside a NOT EXISTS.

the picture

you know how you wanted "customers who have ordered something", wrote a join, and got Maya Chen 57 times? a join answers "list every matching pair". you were asking "is there a match, yes or no?", which is a different question with a different shape.

think of a bouncer with a guest list. you're on it or you're not, and being on it twice doesn't get you in twice. that's EXISTS. the bouncer who only lets in people who are not on the list (the club for people who've never been banned) is NOT EXISTS.

join =
data =
customers.city ↓ stores.city →London sohoParis maraisBerlin mitteNULL online
London Ada✓···
London Alan✓···
Paris Grace·✓··
NULL Edsger····
semi join result
namecity
AdaLondon
AlanLondon
GraceParis
(3 rows)

EXISTS keeps each customers row once if it has at least one match: 3 rows, no duplicates, no stores columns.

model of SQL join semantics · checked against postgres 18.6
the two tiny tables from the first chapter. switch between inner, semi and anti, then press add a duplicate key: London gets a second store, inner gives Ada and Alan two rows each, semi still gives each of them one.

semi and anti are the two join types SQL has no keyword for. you write them as EXISTS and NOT EXISTS (or IN, carefully), and postgres runs them as joins.

EXISTS: is there at least one?

predict the output
sql
SELECT c.name
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE c.id = 1;

for real, and the EXISTS version next to it:

sqldb=shop
SELECT count(*) AS join_rows
FROM customers AS c JOIN orders AS o ON o.customer_id = c.id
WHERE c.id = 1;
 
SELECT c.name
FROM customers AS c
WHERE c.id = 1
  AND EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);
output, from postgres 18.6
#1 · SELECT 1
join_rowsint8
57
(1 row)
#2 · SELECT 1
nametext
Maya Chen
(1 row)

the subquery is correlated (it mentions c.id), so it's asked per customer. it stops at the first matching order it finds: one is enough to make EXISTS true. and what it selects doesn't matter at all. SELECT 1, SELECT *, even SELECT with nothing: EXISTS only looks at whether a row came back.

across the whole shop: 10,000 joined rows, 1,962 customers who have ordered.

sqldb=shop
SELECT count(*) AS joined FROM customers AS c JOIN orders AS o ON o.customer_id = c.id;
 
SELECT count(*) AS have_ordered
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);
output, from postgres 18.6
#1 · SELECT 1
joinedint8
10000
(1 row)
#2 · SELECT 1
have_orderedint8
1962
(1 row)

DISTINCT on the join would get the 1,962 too, by building all 10,000 rows and then throwing duplicates away. EXISTS never builds them. and WHERE c.id IN (SELECT customer_id FROM orders) asks the same question. postgres plans the two the same way, which you'll see in a minute.

NOT EXISTS: the lonely rows

flip it, and you get the rows nothing points at. customers who have never ordered, students with no enrollments, instructors with no course:

sqldb=shop
SELECT count(*) AS never_ordered
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);
 
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id)
ORDER BY c.id
LIMIT 3;
output, from postgres 18.6
#1 · SELECT 1
never_orderedint8
38
(1 row)
#2 · SELECT 3
idint4nametext
7Ming Li
475Diego Mehta
518Kofi Park
(3 rows)
sqldb=school
SELECT s.id, s.name
FROM students AS s
WHERE NOT EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.id)
ORDER BY s.id;
output, from postgres 18.6
SELECT 1
idint4nametext
40Sam Rivera
(1 row)

38 customers, Ming Li (customer 7) first, and one student, Sam Rivera. the same question has two other spellings you'll meet:

  • LEFT JOIN enrollments AS e ON e.student_id = s.id WHERE e.student_id IS NULL: an outer join, then keep only the padded rows. correct, and postgres turns it into the same anti join (below).
  • WHERE s.id NOT IN (SELECT student_id FROM enrollments): correct here, and wrong the moment the subquery can return a NULL. it returns nothing at all then. that's the NOT IN trap, and it's why NOT EXISTS is the one to reach for.

what postgres does with them

there's no SEMI JOIN keyword in SQL, but there is one in postgres's plans:

sqldb=school
EXPLAIN (COSTS OFF)
SELECT i.name FROM instructors AS i
WHERE EXISTS (SELECT 1 FROM courses AS c WHERE c.instructor_id = i.id);
 
EXPLAIN (COSTS OFF)
SELECT i.name FROM instructors AS i
WHERE i.id IN (SELECT c.instructor_id FROM courses AS c);
 
EXPLAIN (COSTS OFF)
SELECT i.name FROM instructors AS i
WHERE NOT EXISTS (SELECT 1 FROM courses AS c WHERE c.instructor_id = i.id);
 
EXPLAIN (COSTS OFF)
SELECT i.name FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id
WHERE c.instructor_id IS NULL;
output, from postgres 18.6
#1 · EXPLAIN
Hash Right Semi Join Hash Cond: (c.instructor_id = i.id) -> Seq Scan on courses c -> Hash -> Seq Scan on instructors i
#2 · EXPLAIN
Hash Right Semi Join Hash Cond: (c.instructor_id = i.id) -> Seq Scan on courses c -> Hash -> Seq Scan on instructors i
#3 · EXPLAIN
Hash Anti Join Hash Cond: (i.id = c.instructor_id) -> Seq Scan on instructors i -> Hash -> Seq Scan on courses c
#4 · EXPLAIN
Hash Anti Join Hash Cond: (i.id = c.instructor_id) -> Seq Scan on instructors i -> Hash -> Seq Scan on courses c

EXISTS and IN become the same Hash Right Semi Join (right, because the planner chose to hash instructors, the outer side). NOT EXISTS becomes a Hash Anti Join, and so does the LEFT JOIN that keeps only its padded rows. the subquery is gone: it was rewritten into a join before planning, so it can use any of the join algorithms, and the planner can pick which side to hash. how subqueries get planned has the rules for when that rewrite is allowed.

relational division: every single one

some questions say "all": students who took every CS course, customers who bought from every category, suppliers who stock every part. the textbook name is relational division, and it's the one classic query that isn't a single join.

the school has five CS courses (CS499, the senior thesis, is in dept GEN, not CS). here are the ten students who took at least three of them:

query.sql
  1. 1SELECT s.id, s.name, e.course_code
  2. 2FROM students AS s
  3. 3JOIN enrollments AS e ON e.student_id = s.id
  4. 4JOIN courses AS c ON c.code = e.course_code
  5. 5WHERE c.dept = 'CS' AND s.id IN (5, 7, 9, 18, 22, 27, 29, 31, 34, 36)
  6. 6ORDER BY s.id, e.course_code;
students ↓ CS courses →CS101CS201CS301CS350CS401
Emma Dubois✓✓··✓
Priya Nair✓✓✓✓✓
Sofia Romano✓·✓✓✓
Clara Novak·✓✓✓✓
Zara Ahmed✓✓·✓·
Mateo Garcia·✓✓✓·
Ivan Sokolov✓✓·✓·
Tariq Aziz·✓✓✓·
Ravi Shankar✓✓·✓✓
Lars Eriksson·✓✓·✓
pairs
50
pass ON
35
matched all
1

who took which CS course. a full row is a student who took all five: only Priya Nair.

real output, postgres 18.6 (PGlite 0.5.12) · division
students down the side, CS courses across. a tick is an enrollment. division keeps the rows with a tick in every column: Priya Nair, and nobody else.

SQL has no "for all", so you say it with two negatives: a student took every CS course if there is no CS course that they did not take.

sqldb=school
SELECT s.id, s.name
FROM students AS s
WHERE NOT EXISTS (
  SELECT 1 FROM courses AS c
  WHERE c.dept = 'CS'
    AND NOT EXISTS (
      SELECT 1 FROM enrollments AS e
      WHERE e.student_id = s.id AND e.course_code = c.code))
ORDER BY s.id;
output, from postgres 18.6
SELECT 1
idint4nametext
7Priya Nair
(1 row)

read it from the inside out. the innermost query is "did this student take this course?". the middle one is "is there a CS course where the answer is no?". the outer one keeps students where the answer to that is no. Priya Nair is the only student with no missing CS course.

the other way is to count: a student who took as many distinct CS courses as there are CS courses took them all.

sqldb=school
SELECT s.id, s.name
FROM students AS s
JOIN enrollments AS e ON e.student_id = s.id
JOIN courses AS c ON c.code = e.course_code
WHERE c.dept = 'CS'
GROUP BY s.id
HAVING count(DISTINCT c.code) = (SELECT count(*) FROM courses WHERE dept = 'CS')
ORDER BY s.id;
output, from postgres 18.6
SELECT 1
idint4nametext
7Priya Nair
(1 row)

same answer. easier to read, too. but the two don't always agree:

divide by =
method =
query.sql
  1. 1SELECT s.id, s.name
  2. 2FROM students AS s
  3. 3WHERE NOT EXISTS (
  4. 4 SELECT 1 FROM courses AS c
  5. 5 WHERE c.dept = 'CS'
  6. 6 AND NOT EXISTS (
  7. 7 SELECT 1 FROM enrollments AS e
  8. 8 WHERE e.student_id = s.id AND e.course_code = c.code))
  9. 9ORDER BY s.id;
the result for dept = 'CS' | double NOT EXISTS
idint4nametext
7Priya Nair
(1 row)

double NOT EXISTS: students for whom there is no CS course they didn't take. Priya Nair, alone.

real output, postgres 18.6 (PGlite 0.5.12) · division
change what you divide by. code LIKE 'CS%' drags in CS499, which nobody has taken, so nobody took them all. and with no LAW courses at all, double NOT EXISTS says every student qualifies, while counting says nobody does.

the LAW case is the edge that matters. there are no LAW courses, so "there is no LAW course the student didn't take" is true for everyone, Sam Rivera with no enrollments at all included: 40 students. that's the logician's answer (everybody has done all of nothing). the counting query starts from the student's enrollments in LAW courses, finds none to group, and returns nobody. neither is a bug. decide which one your question means, and if "nobody" is the answer you want for an empty divisor, check for it first.

keylines

  • EXISTS keeps a row once if at least one match exists: a semi join.
  • NOT EXISTS keeps the rows with no match: an anti join. NULLs can't break it.
  • neither duplicates rows or adds columns. postgres plans them as Semi and Anti joins.
  • IN (subquery) plans like EXISTS. NOT IN does not, and it has a trap.
  • "every" is relational division: a double NOT EXISTS, or a count that has to match.