Lessons › SQL › Go further in SQL: Business questions
SQL lesson
Which customers bought in both February and March?
Which customers bought in both February and March? New tool: EXISTS. For each February order, it asks: is there at least one March order for the same customer? The inside query looks at the outside row (m.customer_id = o.customer_id), and EXISTS is true as soon as one row matches.
Try this lesson free →Example
EXISTS: is there a matching row?
SELECT DISTINCT o.customer_id
FROM orders o
WHERE o.order_date < '2026-03-01'
AND EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01')| customer_id |
|---|
| C101 |
| C102 |
| C103 |
| C104 |
Step by step
- One column, customer_id.
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date < '2026-03-01' AND EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01') - Two short names.
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date < '2026-03-01' AND EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01') - WHERE o.order_date < '2026-03-01'.
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date < '2026-03-01' AND EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01') - EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01').
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date < '2026-03-01' AND EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01')
Practice
1. Which customers bought in both February and March? Show customer_id.
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date < '2026-03-01' AND EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01')2. Which customers bought in February but not in March? Show customer_id.
SELECT DISTINCT o.customer_id FROM orders o WHERE o.order_date < '2026-03-01' AND NOT EXISTS (SELECT 1 FROM orders m WHERE m.customer_id = o.customer_id AND m.order_date >= '2026-03-01')3. Which customers have used a coupon at least once? Show customer_id and name.
SELECT c.customer_id, c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.coupon IS NOT NULL)4. Which stores sold both Earbuds and a Speaker? Show store.
SELECT DISTINCT o.store FROM orders o WHERE o.product = 'Earbuds' AND EXISTS (SELECT 1 FROM orders s WHERE s.store = o.store AND s.product = 'Speaker')5. Which customers have never placed an order? Show their name, using NOT EXISTS.
SELECT c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →