Sub topic 10
Equivalent queries with joins and EXISTS
INTERSECT and EXCEPT have close relatives written with joins and EXISTS. This chapter shows the rewrites, where each one differs from the set operator, and how to pick one. It assumes you can write JOIN, LEFT JOIN, and correlated subqueries. It also assumes you know that NULL = NULL is not true, and that you have read the earlier chapters on INTERSECT, EXCEPT, and NULL handling.
The examples use three tables, each with an email column: customers, newsletter_subscribers, and unsubscribed.
Why rewrite at all
A set operator compares whole rows and removes duplicates. A join or EXISTS query compares only the columns you name in the condition, and it never removes duplicates unless you ask. Rewriting therefore means reproducing three behaviors:
- Matching rule. Which columns decide that two rows are the same.
- Duplicate handling.
INTERSECTandEXCEPTreturn each distinct row once. - NULL handling. Set operators treat two NULLs as the same value. The
=operator does not.
A rewrite that ignores any of these can return different rows. Sometimes that difference is what you want, but you should know it is there.
INTERSECT as a join or EXISTS
This query finds emails present in both tables:
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;An inner join gives the same rows, with one addition:
SELECT DISTINCT c.email
FROM customers c
JOIN newsletter_subscribers s ON s.email = c.email;DISTINCT is required. If customers holds an email once and newsletter_subscribers holds it three times, the join returns three rows. INTERSECT would return one.
An EXISTS version asks the question directly: does a matching row exist in the other table?
SELECT DISTINCT c.email
FROM customers c
WHERE EXISTS (
SELECT 1 FROM newsletter_subscribers s WHERE s.email = c.email
);Here the join cannot multiply rows, because EXISTS only checks whether at least one match exists. Duplicates still come from customers itself, so DISTINCT is still needed to match INTERSECT.
Both rewrites drop rows where email is NULL, because s.email = c.email is never true for NULL. INTERSECT keeps a NULL row if both sides contain one.
EXCEPT as NOT EXISTS, an anti-join, or NOT IN
This query finds subscribers who have not unsubscribed:
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed;There are three common rewrites.
NOT EXISTS is the closest match:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);LEFT JOIN with an IS NULL test, often called an anti-join, keeps the rows of the first table that found no partner:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
LEFT JOIN unsubscribed u ON u.email = s.email
WHERE u.email IS NULL;The test must be on a column of u that can never be NULL in a real match. Testing u.email works here only because a matched row must have a non-NULL u.email. A primary key column is the safest choice.
NOT IN is the shortest to write and the most dangerous:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE s.email NOT IN (SELECT email FROM unsubscribed);Seeing the differences on real data
This script creates small tables that contain a duplicate and NULLs. It runs as written in PostgreSQL.
CREATE TABLE newsletter_subscribers (email TEXT);
CREATE TABLE unsubscribed (email TEXT);
INSERT INTO newsletter_subscribers (email) VALUES
('[email protected]'),
('[email protected]'),
('[email protected]'),
(NULL);
INSERT INTO unsubscribed (email) VALUES
('[email protected]'),
(NULL);Run each form against these tables:
| Form | Rows returned |
|---|---|
| `EXCEPT` | `[email protected]` |
| `NOT EXISTS` with `DISTINCT` | `[email protected]`, NULL |
| `LEFT JOIN ... IS NULL` with `DISTINCT` | `[email protected]`, NULL |
| `NOT IN` | none |
EXCEPT removes the NULL row because it treats the NULL in unsubscribed as equal to the NULL in newsletter_subscribers. The NOT EXISTS and join forms keep it, because u.email = s.email is never true when either side is NULL. NOT IN returns nothing because of the NULL in unsubscribed.
If you want the rewrite to match EXCEPT exactly, use a NULL-safe comparison:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email IS NOT DISTINCT FROM s.email
);IS NOT DISTINCT FROM is standard SQL. It is true when both values are equal or both are NULL. PostgreSQL supports it, and so do recent versions of SQL Server and SQLite. MySQL spells it <=>. Oracle has no direct equivalent, so there you write (u.email = s.email OR (u.email IS NULL AND s.email IS NULL)).
Multiple columns
Set operators compare every column in the select list. A rewrite must compare every one of them as well.
SELECT first_name, last_name FROM customers
EXCEPT
SELECT first_name, last_name FROM unsubscribed_people;The NOT EXISTS form lists each column in the correlation condition:
SELECT DISTINCT c.first_name, c.last_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM unsubscribed_people u
WHERE u.first_name = c.first_name
AND u.last_name = c.last_name
);Forgetting one condition is a common error. If you omit the last_name line, every customer whose first name appears in the other table is excluded. NOT IN with several columns, written as (a, b) NOT IN (SELECT ...), is not supported in every database, which is another reason to avoid it.
What each form can do that the set operator cannot
A set operator returns only the columns of its select lists. A join lets you return more:
SELECT c.email, c.signup_date, s.subscribed_at
FROM customers c
JOIN newsletter_subscribers s ON s.email = c.email;This query returns customers who are also subscribers, along with data from both tables. You cannot write that with INTERSECT, because INTERSECT needs identical column lists on both sides.
A set operator also cannot match on a subset of columns while returning others. If two rows are "the same person" when they share an email, but you want to see each side's name column, you need a join or EXISTS.
Choosing between the forms
| Situation | Preferred form |
|---|---|
| Compare whole rows, return only those columns, NULLs should match | `INTERSECT` or `EXCEPT` |
| Need extra columns from the other table | `JOIN` |
| Only need to know whether a match exists | `EXISTS` or `NOT EXISTS` |
| Need rows with no match, and extra columns are irrelevant | `NOT EXISTS`, or `LEFT JOIN ... IS NULL` |
| Database lacks `INTERSECT` or `EXCEPT` (older MySQL) | `EXISTS` or `NOT EXISTS` rewrite |
| Subquery column might contain NULL | Avoid `NOT IN` |
On older MySQL versions (before 8.0.31) INTERSECT and EXCEPT do not exist, so these rewrites are not optional there.
A note on speed
For these rewrites, performance mostly depends on whether the database can use an index on the matching column. Most optimizers turn EXISTS into a semi-join and NOT EXISTS into an anti-join. Many also recognize the LEFT JOIN ... IS NULL pattern, so the three forms often produce the same plan. NOT IN is the form most likely to get a worse plan, because of its NULL rules. A set operator typically needs a sort or hash step to remove duplicates, but a join with DISTINCT needs the same step.
Do not assume one form is faster. Compare query plans on your own data. The performance chapter returns to this.
Exercise
Using the sample data from this chapter, newsletter_subscribers contains '[email protected]' twice. You write SELECT s.email FROM newsletter_subscribers s WHERE NOT EXISTS (SELECT 1 FROM unsubscribed u WHERE u.email = s.email), with no DISTINCT. How does the result differ from the EXCEPT version, and how many ways can you list?
Show answer
The query returns '[email protected]' twice, because EXCEPT removes duplicates and NOT EXISTS does not. It also returns the NULL row, which EXCEPT removes since the NULL in unsubscribed counts as a match. Adding DISTINCT fixes the duplicate. Changing the correlation to u.email IS NOT DISTINCT FROM s.email fixes the NULL difference.
Exercise
A query uses WHERE email NOT IN (SELECT email FROM unsubscribed) and unexpectedly returns zero rows, although many subscribers have not unsubscribed. What is the likely cause, and what are two fixes?
Show answer
The unsubscribed table contains at least one NULL email. For any email that does not match, the NOT IN comparison evaluates to unknown, so WHERE discards every row. One fix is to filter inside the subquery with WHERE email IS NOT NULL. Another is to rewrite the query with NOT EXISTS.
Exercise
Write an INTERSECT-equivalent query for SELECT first_name, last_name FROM customers INTERSECT SELECT first_name, last_name FROM newsletter_people using EXISTS. Name one case where your rewrite differs from INTERSECT.
Show answer
SELECT DISTINCT c.firstname, c.lastname FROM customers c WHERE EXISTS (SELECT 1 FROM newsletterpeople n WHERE n.firstname = c.firstname AND n.lastname = c.lastname); It differs when a row has NULL in firstname or last_name. INTERSECT treats NULLs as equal and keeps such a row if both tables have it, but the = comparison never matches NULL, so the rewrite drops it.