Learning navigation

Code with Animation

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.

SQL6 min readConcept 24 of 44

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.

SELECT name
FROM customers
WHERE EXISTS (SELECT 1 FROM tickets WHERE tickets.customer_id = customers.id);
tickets (4 rows)
idintegercustomer_idintegertopictext
2011Login
2021Billing
2032Login
204NULLPricing
customers (5 rows)
idintegernametexttickets found
1Asha2 matches, TRUE
2Ben1 match, TRUE
3Chen0 matches, FALSE
4Dara0 matches, FALSE
5Eli0 matches, FALSE
Result (2 rows)
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.

  1. 1`WHERE EXISTS (SELECT 1 FROM tickets WHERE tickets.customer_id = customers.id)` is evaluated for Chen, who has no tickets. What is the result?
  2. 2Which query correctly lists the customers with no tickets, even though one ticket has a NULL customer_id?
  3. 3What makes a subquery correlated?

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.