EXISTS & Correlated Subqueries
Ask "is there at least one matching row?" with EXISTS, understand subqueries that use the outer row, and fix NOT IN with NOT EXISTS.
EXISTS asks: is there any?
EXISTS (subquery) is true when the subquery returns at least one row, and false when it returns none. It never returns NULL. The values in the subquery's select list do not matter, so people write SELECT 1.
A correlated subquery uses a column of the outer query. The inner query is then run once for each outer row, with that row's value plugged in.
Has one, or has none
"Which customers have at least one ticket?" and "which customers have none?" are the most common questions of this kind. EXISTS and NOT EXISTS answer both directly, and they cope with NULL better than IN and NOT IN.
Customers with a ticket
SELECT name
FROM customers
WHERE EXISTS (
SELECT 1 FROM tickets
WHERE tickets.customer_id = customers.id
);For Asha (id 1), the inner query finds 2 tickets, so EXISTS is true. For Ben, 1 ticket, true. For Chen, Dara and Eli it finds none, so false. The result is Asha and Ben.
Add NOT to find the customers with no ticket: WHERE NOT EXISTS (...) returns Chen, Dara and Eli.
Same question, four tests
Switch between EXISTS, NOT EXISTS, IN and NOT IN, and read the badge for each customer. Then turn on Only Billing tickets and watch NOT IN change.
| idinteger | customer_idinteger | topictext |
|---|---|---|
| 201 | 1 | Login |
| 202 | 1 | Billing |
| 203 | 2 | Login |
| 204 | NULL | Pricing |
| idinteger | nametext | tickets found |
|---|---|---|
| 1 | Asha | 2 matches, TRUE |
| 2 | Ben | 1 match, TRUE |
| 3 | Chen | 0 matches, FALSE |
| 4 | Dara | 0 matches, FALSE |
| 5 | Eli | 0 matches, FALSE |
| nametext |
|---|
| Asha |
| Ben |
For each customer the inner query runs with that customer's id and counts the tickets that match. EXISTS is true when the count is at least 1. Asha has 2 tickets, Ben has 1.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- EXISTS is true if the subquery returns at least one row, false if none. It is never NULL.
- A correlated subquery refers to the outer row, so it is evaluated for each outer row.
- NOT EXISTS is safe with NULL values. NOT IN is not.
- Always link the inner query to the outer one, or EXISTS gives the same answer for every row.
Done with this concept?
Mark it complete to track your progress. No login needed.