Part 06 / Topic 2 of 8
IN and EXISTS
A subquery returning a column of values powers IN — and a subquery used as a test powers EXISTS. Both answer "is there a match in that other query?", from two angles:
SELECT first_name FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE status = 'delivered')
ORDER BY customer_id;
first_name
------------
Asha
Ravi
Meera
Sara
(4 rows)
SELECT first_name FROM customers AS c
WHERE EXISTS (
SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id AND o.status = 'delivered'
)
ORDER BY customer_id;
first_name
------------
Asha
Ravi
Meera
Sara
(4 rows)
Same four customers. IN reads naturally for "value in that list"; EXISTS asks "at least one matching row?" and stops at the first hit (that SELECT 1 is convention — EXISTS ignores what the inner query selects). For positive membership they are interchangeable; the negative forms are not — next section.
🧪 Quick quiz — answer from memory, then check.
- What does
EXISTS (SELECT 1 ...)actually select? - When do IN and EXISTS give the same answer?
Show the answers
- Nothing meaningful — EXISTS only checks whether any row comes back;
1is a conventional placeholder. - For positive membership tests (does a match exist?) they are equivalent; their negations diverge when NULLs are involved.
Exercise 2: Big-order customers, twice
What to do: Customers who have at least one order line worth over 500. Write it with IN, then again with EXISTS — same four names both times.
Sample output (both):
first_name
------------
Asha
John
Meera
Ravi
(4 rows)
💡 Hint: the subquery joins orders to order_items and filters quantity * unit_price > 500.
Show the solution to Exercise 2
-- Exercise 2: Big-order customers, twice
-- Orders worth over 500 in a single order line are "big" here.
SELECT first_name FROM customers
WHERE customer_id IN (
SELECT o.customer_id FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE oi.quantity * oi.unit_price > 500
)
ORDER BY first_name;
SELECT c.first_name FROM customers c
WHERE 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.quantity * oi.unit_price > 500
)
ORDER BY c.first_name;