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 column1FROM table_nameWHERE 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.
EXISTS
Section titled “EXISTS”The approved suppliers who have sent at least one invoice:
SELECT NameFROM SuppliersWHERE 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
Section titled “NOT EXISTS”NOT EXISTS finds the rows with no match. The approved suppliers who have not invoiced yet:
SELECT NameFROM SuppliersWHERE 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 NameFROM Crew AS cWHERE 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.