Sub topic 12
Double NOT EXISTS: "for all" questions
SQL has no FOR ALL operator, but you can express the idea with two nested NOT EXISTS tests. This chapter shows how to read and write that pattern, where it goes wrong, and how it compares with a counting approach.
This chapter assumes you can write a correlated subquery and use EXISTS and NOT EXISTS. It also assumes you know JOIN, GROUP BY with HAVING, and how COUNT(DISTINCT ...) behaves.
The question SQL does not ask directly
Most questions in this tutorial have been "has at least one" or "has none". Some questions are about every item in a set:
- Which customers have ordered every product?
- Which students have passed every required course?
- Which suppliers deliver to every warehouse?
These are "for all" questions. The relational algebra name for this operation is division. SQL lacks a keyword for it, so you use logic instead. "For all x, P(x)" is equivalent to "there is no x for which P(x) is false". In SQL terms, that is NOT EXISTS around a condition that looks for a counterexample.
Applied to our schema, "the customer ordered every product" becomes "there is no product that the customer has not ordered". Each "no" is a NOT EXISTS, so the query has two of them.
A small dataset to run
The examples use this schema and data. They run on PostgreSQL, SQLite, and MySQL.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
category VARCHAR(30) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
PRIMARY KEY (order_id, product_id)
);
INSERT INTO customers VALUES (1, 'Ana'), (2, 'Ben'), (3, 'Cy');
INSERT INTO products VALUES
(10, 'Pen', 'Office'),
(20, 'Notebook', 'Office'),
(30, 'Atlas', 'Books');
INSERT INTO orders VALUES
(100, 1, '2026-01-05'),
(101, 1, '2026-02-10'),
(102, 2, '2026-02-11');
INSERT INTO order_items VALUES
(100, 10), (100, 20),
(101, 30),
(102, 10);Ana ordered all three products, but across two separate orders. Ben ordered only the pen. Cy has no orders. The correct answer to "who ordered every product?" is Ana alone.
The double NOT EXISTS query
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM products p
WHERE NOT EXISTS (
SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = c.customer_id
AND oi.product_id = p.product_id
)
);With the sample data this returns Ana.
Reading it from the outside in
Read the query one layer at a time, and say each layer out loud.
- Outer query. For each customer
c, keep the row if the middleNOT EXISTSis true. - Middle query. It scans products
p. It returns a row for each product that the innermost query cannot find among the customer's purchases. The middleNOT EXISTSis true only when this scan returns zero rows. - Innermost query. It looks for evidence that customer
cordered productp. If it finds a row, the middle query'sWHERE NOT EXISTSis false for that product, sopis not a counterexample.
In plain language, the whole query says: keep customer c if there is no product p for which there is no order of p by c.
The innermost query is correlated with both levels. It refers to c.customer_id from the outermost query and p.product_id from the middle one. If either reference is missing, the query answers a different question, as the section on common mistakes shows.
The database may not run it in exactly this order, but the result must match this logic. A real optimizer can stop at the first counterexample, which is why a customer who missed the first product is rejected quickly.
Why orders can be combined
The innermost query joins orders to order_items without restricting to one order. That means a product ordered in any of the customer's orders counts. Ana's pen and notebook came from order 100, and her atlas came from order 101. She qualifies because the question is about the customer, not about a single order.
If you wanted "customers who bought every product in one single order", you would correlate on the order instead. You would loop over orders in the outer query and compare against order_items for that order_id.
Restricting the "all"
Often you do not need all rows in the universe. You may need every product in one category. Put that filter in the middle query's WHERE, next to the NOT EXISTS:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM products p
WHERE p.category = 'Office'
AND NOT EXISTS (
SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = c.customer_id
AND oi.product_id = p.product_id
)
);The filter defines who counts as a possible counterexample. Only Office products can disqualify a customer. Ana qualifies. Ben does not, because he never ordered the notebook.
Put the category filter in the middle query, never in the innermost one. If you move p.category = 'Office' into the innermost query, the check stops restricting which products must be ordered. Instead, it asks for products that were not ordered as Office items, which is a different question.
Edge cases
An empty universe. If products has no rows, the middle query returns nothing for every customer. Every NOT EXISTS is therefore true, and every customer qualifies, including Cy, who has no orders. Logicians call this vacuous truth: a statement about every member of an empty set is true. Decide whether that is what you want. If not, add a guard such as AND EXISTS (SELECT 1 FROM products) to the outer WHERE.
Customers with no orders. When the product set is not empty, Cy fails correctly. The innermost query finds nothing for any product, so every product is a counterexample.
NULLs. NOT EXISTS only tests whether rows exist, so a NULL in a compared column simply fails the equality and produces no match. Unlike NOT IN, it does not turn the whole test into UNKNOWN. In this schema the foreign keys are NOT NULL, but the pattern stays correct if they were nullable.
Duplicates. The innermost query only has to find one row. Duplicate rows in order_items or repeated orders of the same product do not change the result, and you need no DISTINCT.
The counting alternative
Another way to answer the same question is to count the distinct products each customer ordered and compare with the total number of products:
SELECT c.customer_id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.name
HAVING COUNT(DISTINCT oi.product_id) = (SELECT COUNT(*) FROM products);This also returns Ana. Many people find it easier to read. The two approaches differ in ways that matter:
| Aspect | Double NOT EXISTS | COUNT comparison |
|---|---|---|
| Reads as | "No product is missing" | "Ordered as many distinct products as exist" |
| Empty `products` table | Every customer qualifies | No customer qualifies, because `COUNT(DISTINCT ...)` is at least 1 for any customer in the join and the total is 0 |
| Customers with no orders | Handled by the logic | Never appear, because the inner joins drop them |
| Filtered universe | Add a filter in the middle query | The filter must appear in both the join and the total count, and they must match |
| Items not in the universe | Ignored | Can inflate the count unless the filter is applied to `oi.product_id` |
| Cost profile | Can stop early at the first counterexample | Must aggregate all of each customer's items |
The counting version has a trap with restricted universes. To limit it to Office products, you must join products and filter in the WHERE clause, and the total must be (SELECT COUNT(*) FROM products WHERE category = 'Office'). If the two filters drift apart, the comparison silently returns wrong answers. The double NOT EXISTS states the universe once.
Counting is a good choice when the requirement is "at least N of M" rather than "all", or when the team reads GROUP BY more fluently than nested subqueries.
Performance
The cost is roughly customers times products times the lookup cost of the innermost query, in the worst case. The database avoids most of that if the innermost lookup is cheap. Two indexes help:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);
CREATE INDEX idx_order_items_product_order ON order_items (product_id, order_id);The first finds a customer's orders. The second lets the engine check for a given product and order without scanning order_items. The primary key (order_id, product_id) already serves lookups that start from the order.
Check the plan with EXPLAIN before trusting any of this. Some optimizers rewrite the nested anti-joins well, and others run them as repeated probes. A counterexample found early saves a lot of work, so the query is fastest when most customers fail quickly.
Common mistakes
- Dropping the correlation to
c. If the innermost query has noo.customer_id = c.customer_id, it asks whether anyone ordered each product. Every customer then gets the same answer. - Dropping the correlation to
p. Withoutoi.product_id = p.product_id, the innermost query is true whenever the customer has any order, so any customer with an order qualifies. - Using one
NOT EXISTSand thinking it is "all". A singleNOT EXISTSfinds customers with no match. "All" needs the second negation. - Putting the universe filter in the wrong layer. As shown above, it belongs in the middle query.
- Forgetting the empty-universe case. Test the query against an empty
productstable before you rely on it.
Exercises
Exercise
Using the sample data, write a double NOT EXISTS query that returns customers who have ordered every product in the 'Books' category. Which customers does it return, and why?
Show answer
SELECT c.customerid, c.name FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM products p WHERE p.category = 'Books' AND NOT EXISTS ( SELECT 1 FROM orders o JOIN orderitems oi ON oi.orderid = o.orderid WHERE o.customerid = c.customerid AND oi.productid = p.productid ) ); It returns only Ana. The only Books product is the Atlas (30), which Ana ordered in order 101. Ben never ordered it, and Cy has no orders at all.
Exercise
The products table is emptied. What does the double NOT EXISTS query return, and what does the COUNT(DISTINCT ...) version return? Why do they differ?
Show answer
The double NOT EXISTS query returns every customer, including Cy, because there is no product that could be a counterexample, so the middle NOT EXISTS is true for each customer. The COUNT version returns no rows. Customers without orders are dropped by the inner joins, and the customers that remain have a distinct-product count of at least 1 or none at all, which never equals the total of 0 because no order item can reference a product that does not exist. The difference comes from how each version treats an empty set of required items.
Exercise
A colleague removes the condition oi.productid = p.productid from the innermost query. Describe what the query now returns on the sample data.
Show answer
The innermost query becomes true for any customer who has at least one order item, for every product. So the middle query finds no counterexample for Ana or Ben, and both are returned. Cy still fails: with no orders the innermost query finds nothing, so every product counts as a counterexample. The query now means "customers with at least one ordered item", not "customers who ordered every product".