Skip to content

SQL EXISTS Operator

EXISTS asks a yes-or-no question: does a subquery return at least one row? It is true if the subquery finds anything, and false if it finds nothing.

SELECT column1
FROM table_name
WHERE EXISTS (SELECT 1 FROM other_table WHERE condition);

The subquery usually refers to the row the outer query is looking at, so the question is asked afresh for each row. This is called a correlated subquery.

The examples use the tables from the example database.

The approved suppliers who have sent at least one invoice:

SELECT Name
FROM Suppliers
WHERE EXISTS (
SELECT 1 FROM Invoices WHERE Invoices.Supplier = Suppliers.Name
);
Name
Hartwell Lighting
Kestrel Catering

For each supplier, the subquery looks for an invoice under that supplier’s name. Kestrel Catering has two invoices but appears once, because EXISTS only asks whether there is a match, not how many.

What the subquery selects does not matter, since only whether it finds a row counts. SELECT 1 is a common way of saying so.

NOT EXISTS finds the rows with no match. The approved suppliers who have not invoiced yet:

SELECT Name
FROM Suppliers
WHERE NOT EXISTS (
SELECT 1 FROM Invoices WHERE Invoices.Supplier = Suppliers.Name
);
Name
Northgate Transport

It also answers the question that tripped up NOT IN: which crew members manage nobody?

SELECT Name
FROM Crew AS c
WHERE NOT EXISTS (
SELECT 1 FROM Crew AS r WHERE r.ReportsTo = c.CrewID
);
Name
Priya Nair
Owen Price
Lucy Brennan
Sam Ellis

Because NOT EXISTS only looks for matching rows, the NULLs in ReportsTo cause no trouble, and the right answer comes back without any special handling.