Finding Matches and Missing Rows: EXISTS, NOT EXISTS, IN and NOT IN
How to ask "does a related row exist?" without duplicating rows: semi-joins with EXISTS and IN, anti-joins with NOT EXISTS, LEFT JOIN ... IS NULL and EXCEPT, the NOT IN trap with NULLs, correlated conditions inside EXISTS, and how databases execute these queries.
kvi5hnuCode Sprout team member10 min readOn this page
Many questions are about whether related rows exist, not about the related rows themselves:
- "Which customers have placed an order?"
- "Which products have never been sold?"
- "Which customers bought a tent?"
You want each customer or product once, with no columns from the other table. Two kinds of query do this:
- A semi-join returns the rows of A that have at least one match in B.
- An anti-join returns the rows of A that have no match in B.
SQL has no SEMI JOIN or ANTI JOIN keywords. You write them with EXISTS, IN, NOT EXISTS, NOT IN, outer joins or EXCEPT, and the optimizer recognizes the pattern. This article shows each form, and when each one is safe. The examples use the shop database from article 12.
Semi-joins: EXISTS and IN
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Semi-join with EXISTS: customers who have placed at least one order
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id;
-- The same with IN
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id IN (SELECT o.customer_id FROM orders o)
ORDER BY c.customer_id;
-- A plain join repeats customers who have several orders
SELECT c.customer_id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
ORDER BY c.customer_id;
customer_id | name
-------------+------------
1 | Asha Rao
2 | Ben Okafor
3 | Chen Wei
4 | Dana Cruz
(4 rows)
customer_id | name
-------------+------------
1 | Asha Rao
2 | Ben Okafor
3 | Chen Wei
4 | Dana Cruz
(4 rows)
customer_id | name
-------------+------------
1 | Asha Rao
1 | Asha Rao
2 | Ben Okafor
3 | Chen Wei
4 | Dana Cruz
(5 rows)
EXISTS (subquery) is true if the subquery returns at least one row. The subquery here is correlated: it refers to c.customer_id from the outer query, so it's conceptually evaluated once for each customer. "Is there an order whose customer is this customer?" For Asha, Ben, Chen and Dana there is. For Eli and Farah there isn't.
IN (subquery) is true if the value equals one of the values the subquery returns. It gives the same result here, and it's often easier to read for a single column.
The plain join in the third query returns Asha twice, because Asha has two orders. A join returns one row per matching pair, and a semi-join returns each row of A once, however many matches it has. Adding DISTINCT to the join would hide the duplicates, but it removes duplicates from the whole result, so legitimately identical rows would be merged too, and it costs an extra sort or hash. When you only need to know whether a match exists, EXISTS or IN states that directly.
What goes inside EXISTS
EXISTS only checks whether the subquery returns any row. The select list is ignored. SELECT 1, SELECT * and SELECT o.order_id all mean the same thing. SELECT 1 is a common convention that signals "I only care about existence". The last query in the next example even uses SELECT 1/0, which would be a division-by-zero error if it were ever evaluated, to prove the point.
The subquery can be as complex as needed, with joins and extra conditions:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- EXISTS with extra conditions: customers who bought a tent
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.customer_id = c.customer_id
AND p.category = 'tents')
ORDER BY c.name;
-- Products never ordered by anyone in Pune
SELECT p.name
FROM products p
WHERE NOT EXISTS (SELECT 1
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id
WHERE oi.product_id = p.product_id
AND c.city = 'Pune')
ORDER BY p.name;
-- The select list inside EXISTS doesn't matter: even 1/0 is never evaluated
SELECT COUNT(*) AS customers_with_orders
FROM customers c
WHERE EXISTS (SELECT 1/0 FROM orders o WHERE o.customer_id = c.customer_id);
name
----------
Asha Rao
Chen Wei
(2 rows)
name
------------------
Basecamp lantern
Day 18 backpack
(2 rows)
customers_with_orders
-----------------------
4
(1 row)
- Customers who bought a tent. The subquery joins orders, order lines and products, and it's correlated with the outer customer through
o.customer_id = c.customer_id. Asha bought the Ridge 2 tent and Chen bought the Summit 4 tent. - Products never ordered by anyone in Pune.
NOT EXISTSwith a joined subquery gives the lantern, which nobody ordered, and the Day 18 backpack, which only Dana in York ordered.
A common mistake is to forget the correlation, as in WHERE EXISTS (SELECT 1 FROM orders). Without a condition that links the subquery to the outer row, the subquery's result is the same for every row: if orders has any rows at all, the condition is true for every customer.
Anti-joins: three safe ways and one trap
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Anti-join: customers with no orders, three ways
SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
ORDER BY c.name;
SELECT c.name FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.name;
-- NOT IN looks the same, but orders.customer_id contains a NULL (the guest order)...
SELECT c.name FROM customers c
WHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o)
ORDER BY c.name;
-- ...so it returns nothing unless the NULLs are filtered out
SELECT c.name FROM customers c
WHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o WHERE o.customer_id IS NOT NULL)
ORDER BY c.name;
name
--------------
Eli Novak
Farah Haddad
(2 rows)
name
--------------
Eli Novak
Farah Haddad
(2 rows)
name
------
(0 rows)
name
--------------
Eli Novak
Farah Haddad
(2 rows)
The goal is the customers who have never ordered, and the right answer is Eli and Farah.
NOT EXISTSis true when the correlated subquery returns no rows. It's correct whatever NULLs the tables contain, and it reads exactly like the question.LEFT JOIN ... WHERE o.order_id IS NULLkeeps the customers whose join found no order (article 13). It's also correct, as long as you test a column that's never NULL in a real match, such as the primary key.NOT IN (subquery)returned no rows at all.NOT INwith the NULLs filtered out returned the right answer.
Why NOT IN returned nothing
The guest order 106 has a NULL customer_id, so the subquery returns 1, 2, 1, 3, 4 and NULL. For Eli, 5 NOT IN (1, 2, 1, 3, 4, NULL) means 5 <> 1 AND 5 <> 2 AND ... AND 5 <> NULL. All the comparisons are true except the last, which is unknown, and true AND unknown is unknown (article 8). The WHERE clause drops the row. The same happens for every customer, so NOT IN can never be true while the subquery contains a NULL.

This is one of the most dangerous bugs in SQL, because:
- the query is valid and gives no error;
- it works correctly in testing, until a single NULL appears in the subquery's column;
- the symptom is an empty result, which can look like "there's nothing to report".
The positive form, IN, doesn't have this problem: 1 IN (1, NULL) is true, and 5 IN (1, NULL) is unknown, which WHERE treats the same as false. Only NOT IN breaks.
Rule: use NOT EXISTS for anti-joins. Use NOT IN only with a literal list, or with a subquery on a column declared NOT NULL, and even then, remember that the column might become nullable later.
EXCEPT
When you only need the key, EXCEPT works too: SELECT customer_id FROM customers EXCEPT SELECT customer_id FROM orders. It treats NULLs as equal, so the NULL in orders doesn't cause trouble (article 15). The limitation is that it returns only the compared columns. To get the names as well, you'd have to join the result back to customers.
Comparing the options
| Form | Correct with NULLs? | Returns other columns of A? | Notes |
|---|---|---|---|
NOT EXISTS (correlated subquery) | yes | yes | the clearest and safest default |
LEFT JOIN ... WHERE b.key IS NULL | yes, if you test a non-nullable column | yes | common in older code |
NOT IN (subquery) | no: empty if the subquery returns a NULL | yes | safe only for non-nullable columns |
EXCEPT | yes (NULLs compare as equal) | only the compared columns | compares whole rows |
How databases execute semi-joins and anti-joins
The name "correlated subquery" suggests the subquery runs once per outer row, and in the worst case, it can. But modern optimizers recognize EXISTS, IN, NOT EXISTS and LEFT JOIN ... IS NULL as semi-joins and anti-joins. They execute them with the same hash, merge and nested-loop algorithms as other joins, and they stop scanning for an outer row as soon as one match is found. In PostgreSQL, a query plan shows this as Hash Semi Join or Hash Anti Join.
Some consequences:
EXISTSandINusually perform the same in PostgreSQL, Oracle and SQL Server. Older advice that "EXISTSis always faster thanIN" (or the reverse) came from optimizers of 20 years ago.NOT INis often slower as well as risky. Because of the NULL rule, PostgreSQL generally can't turnNOT IN (subquery)into an ordinary anti-join, and falls back to checking a list of the subquery's values, which can be much slower when that list is large.- An index on the subquery's correlated column, such as
orders.customer_id, helps every form.
What's current
- PostgreSQL, Oracle, SQL Server and MySQL 8 all transform
EXISTSandINsubqueries into semi-joins, andNOT EXISTSinto anti-joins. MySQL 8.0.17 and later also convertNOT EXISTSandNOT INsubqueries into anti-joins. - None of them changes the meaning of
NOT INwith NULLs, which is fixed by the SQL standard. The trap is the same in every product.
Common questions
Is EXISTS faster than IN?
In modern optimizers, usually not. They're typically executed the same way. Choose the one that reads better: IN for a simple list of keys, EXISTS when the condition involves several columns or extra filters.
Why use SELECT 1 inside EXISTS?
It's a convention. EXISTS ignores the select list, so SELECT 1, SELECT * or any column gives the same result and the same performance.
Is NOT IN ever safe?
Yes, with a literal list that contains no NULL, or with a subquery whose column is declared NOT NULL. Adding WHERE col IS NOT NULL to the subquery also makes it safe, but NOT EXISTS avoids having to remember.
Can I use IN with several columns?
Yes, with row values, as in WHERE (a, b) IN (SELECT x, y FROM t), in PostgreSQL, MySQL, Oracle and SQLite. SQL Server doesn't support it, so use EXISTS there.
Why does my EXISTS return every row?
The subquery isn't correlated. Without a condition linking it to the outer query, it returns the same rows for every outer row. Add the linking condition, such as WHERE o.customer_id = c.customer_id.
When should I use a join instead? When you need columns from the other table, such as the order dates. When you only need to filter, a semi-join avoids duplicates.
Summary
- A semi-join returns rows of A that have at least one match in B, each once. Write it with
EXISTSorIN. - An anti-join returns rows of A that have no match in B. Write it with
NOT EXISTS,LEFT JOIN ... WHERE b.key IS NULLorEXCEPT. - A plain join repeats A's rows for each match. Don't use a join plus
DISTINCTwhen you only need existence. EXISTSignores its select list. The subquery must be correlated with the outer row.NOT IN (subquery)returns no rows if the subquery returns any NULL. PreferNOT EXISTS.- Optimizers execute semi-joins and anti-joins efficiently, and
EXISTSandINusually perform the same. Index the correlated column.
Practice questions
Write a query that returns the products that have been ordered at least once, each listed once, using EXISTS.
Answer
SELECT p.name
FROM products p
WHERE EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id)
ORDER BY p.name;
This returns six products, every one except the Basecamp lantern. Even the socks, which appear in three orders, are listed once.
A query uses WHERE product_id NOT IN (SELECT product_id FROM returns) to find products that were never returned. It worked for months, then started returning no rows. What probably changed?
Answer
A row with a NULL product_id was added to returns, perhaps a return logged before the product was identified. From then on, NOT IN compares every product with a NULL, the condition is unknown for every row, and nothing is returned. Rewrite it as WHERE NOT EXISTS (SELECT 1 FROM returns r WHERE r.product_id = p.product_id), which ignores the NULL row.
What's wrong with this query, which should list customers who have a pending order?
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.status = 'pending');
Answer
The subquery isn't correlated with the outer customer. It checks whether any pending order exists in the whole table, and since order 104 is pending, the condition is true for every customer, so all six are returned. Add the link: WHERE o.customer_id = c.customer_id AND o.status = 'pending'. Then only Chen is returned.
Write a query that returns customers who have orders but have never bought anything from the clothing category.
Answer
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
AND NOT EXISTS (SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.customer_id = c.customer_id
AND p.category = 'clothing')
ORDER BY c.name;
This returns Ben, Chen and Dana. Asha is excluded because orders 101 and 103 include socks. Eli and Farah are excluded because they have no orders. The first EXISTS is a semi-join and the NOT EXISTS is an anti-join, combined with AND.
Previous: SQL Set Operations: UNION, UNION ALL, INTERSECT and EXCEPT
Next: SQL Join Pitfalls: Fan-Out, Duplicates and Comparing Two Tables

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.