SQL IN vs EXISTS
Two different mechanisms that often land on the exact same answer.
What & Why
IN and EXISTS can solve the identical problem two different ways: IN builds a list of values first, then checks membership. EXISTS checks row-by-row, per outer row, whether a match exists at all.
See How It Works
BUSINESS QUESTION
Compare IN and EXISTS while returning the same campaigns that have at least one lead.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
| id | campaign_id | created_at | qualified_at | converted_at | lead_score | source | country | |
|---|---|---|---|---|---|---|---|---|
| 301 | 1 | ana@example.com | 2024-01-21 09:10:00+00 | 2024-01-22 11:00:00+00 | 2024-02-02 10:00:00+00 | 86 | google_ads | US |
| 302 | 1 | ben@example.com | 2024-01-24 12:40:00+00 | NULL | NULL | 52 | google_ads | CA |
| 303 | 2 | chloe@example.com | 2024-02-16 08:30:00+00 | 2024-02-18 14:20:00+00 | NULL | 74 | GB | |
| 304 | 3 | dev@example.com | 2024-03-20 17:15:00+00 | 2024-03-21 09:00:00+00 | 2024-04-04 16:00:00+00 | 91 | US |
Compare IN and EXISTS over the same Queryflo rowsStep 1 of 2
c.id IN (SELECT campaign_id FROM marketing.leads)
| campaign_id | name | IN result |
|---|---|---|
| 1 | Spring Launch | KEEP |
| 2 | Retention Webinar | KEEP |
| 3 | Finance Retargeting | KEEP |
| 4 | Enterprise Search | SKIP |
IN materializes the distinct campaign IDs 1, 2, and 3 from marketing.leads.
EXAMPLE QUERY
-- List membership
SELECT
c.id,
c.name,
c.channel
FROM marketing.campaigns c
WHERE c.id IN (
SELECT l.campaign_id
FROM marketing.leads l
WHERE l.campaign_id IS NOT NULL
)
ORDER BY c.id;
-- Correlated existence
SELECT
c.id,
c.name,
c.channel
FROM marketing.campaigns c
WHERE EXISTS (
SELECT 1
FROM marketing.leads l
WHERE l.campaign_id = c.id
)
ORDER BY c.id;This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario