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.
| customers.city ↓ stores.city → | London soho | Paris marais | Berlin mitte | NULL online |
|---|---|---|---|---|
| London Ada | ✓ | · | · | · |
| London Alan | ✓ | · | · | · |
| Paris Grace | · | ✓ | · | · |
| NULL Edsger | · | · | · | · |
| name | city |
|---|---|
| Ada | London |
| Alan | London |
| Grace | Paris |
EXISTS keeps each customers row once if it has at least one match: 3 rows, no duplicates, no stores columns.
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?
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:
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);| join_rowsint8 |
|---|
| 57 |
| nametext |
|---|
| Maya Chen |
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.
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);| joinedint8 |
|---|
| 10000 |
| have_orderedint8 |
|---|
| 1962 |
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:
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;| never_orderedint8 |
|---|
| 38 |
| idint4 | nametext |
|---|---|
| 7 | Ming Li |
| 475 | Diego Mehta |
| 518 | Kofi Park |
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;| idint4 | nametext |
|---|---|
| 40 | Sam Rivera |
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:
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;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:
- 1SELECT s.id, s.name, e.course_code
- 2FROM students AS s
- 3JOIN enrollments AS e ON e.student_id = s.id
- 4JOIN courses AS c ON c.code = e.course_code
- 5WHERE c.dept = 'CS' AND s.id IN (5, 7, 9, 18, 22, 27, 29, 31, 34, 36)
- 6ORDER BY s.id, e.course_code;
| students ↓ CS courses → | CS101 | CS201 | CS301 | CS350 | CS401 |
|---|---|---|---|---|---|
| Emma Dubois | ✓ | ✓ | · | · | ✓ |
| Priya Nair | ✓ | ✓ | ✓ | ✓ | ✓ |
| Sofia Romano | ✓ | · | ✓ | ✓ | ✓ |
| Clara Novak | · | ✓ | ✓ | ✓ | ✓ |
| Zara Ahmed | ✓ | ✓ | · | ✓ | · |
| Mateo Garcia | · | ✓ | ✓ | ✓ | · |
| Ivan Sokolov | ✓ | ✓ | · | ✓ | · |
| Tariq Aziz | · | ✓ | ✓ | ✓ | · |
| Ravi Shankar | ✓ | ✓ | · | ✓ | ✓ |
| Lars Eriksson | · | ✓ | ✓ | · | ✓ |
who took which CS course. a full row is a student who took all five: only Priya Nair.
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.
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;| idint4 | nametext |
|---|---|
| 7 | Priya Nair |
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.
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;| idint4 | nametext |
|---|---|
| 7 | Priya Nair |
same answer. easier to read, too. but the two don't always agree:
- 1SELECT s.id, s.name
- 2FROM students AS s
- 3WHERE NOT EXISTS (
- 4 SELECT 1 FROM courses AS c
- 5 WHERE c.dept = 'CS'
- 6 AND NOT EXISTS (
- 7 SELECT 1 FROM enrollments AS e
- 8 WHERE e.student_id = s.id AND e.course_code = c.code))
- 9ORDER BY s.id;
| idint4 | nametext |
|---|---|
| 7 | Priya Nair |
double NOT EXISTS: students for whom there is no CS course they didn't take. Priya Nair, alone.
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.