Before continuing: This entry is part of the JOIN guide. If you are new to the topic, start with JOIN.
Query
If the business question is “this customer has no orders”, NOT EXISTS expresses exactly that condition. The subquery is correlated with the outer row through the related key.
WITH customers(id, name) AS (
VALUES (1, 'Amy'), (2, 'Bruno'), (3, 'Celia'), (4, 'David')
),
orders(id, customer_id) AS (
VALUES (101, 1), (102, 1), (103, 3)
)
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS p
WHERE p.customer_id = c.id
)
ORDER BY c.id;What goes in the inner SELECT list does not matter: EXISTS and NOT EXISTS only check whether the subquery returns any row. By convention you will usually see SELECT 1.
Cases that change the result
Alternative: LEFT JOIN + IS NULL
You can also keep every customer, join their orders and keep the rows where no right-hand match appeared.
WITH customers(id, name) AS (
VALUES (1, 'Amy'), (2, 'Bruno'), (3, 'Celia'), (4, 'David')
),
orders(id, customer_id) AS (
VALUES (101, 1), (102, 1), (103, 3)
)
SELECT c.id, c.name
FROM customers AS c
LEFT JOIN orders AS p
ON p.customer_id = c.id
WHERE p.id IS NULL
ORDER BY c.id;In the filter, use a column from the right table that you know cannot be NULL in a real row, such as a primary key. If you filter on a right-hand column that does allow nulls, you could confuse “there was a match but the value is null” with “there was no match”.
Why not start with NOT IN?
NOT IN can work, but it hides an important trap when the list or subquery contains NULL: three-valued logic can stop the exclusion from returning the rows you expect. For a question about a missing related row, NOT EXISTS usually expresses the intent better and does not depend on the inner set being free of nulls.
Rule of thumb: “no related row exists” → think of NOT EXISTSfirst. “the value is not in a known list with no NULLs” → NOT IN may be enough.
Performance: write the correct logic first, then measure
Modern optimisers can turn these forms into internal semi-join or anti-join strategies. Do not assume one syntax will always be faster. Make sure the relationship columns have sensible indexes, check the plan with your engine's tools and measure with your real data.