Learn SQL/Advanced/Subqueries/SQL IN vs EXISTS

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.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
Compare IN and EXISTS over the same Queryflo rowsStep 1 of 2
c.id IN (SELECT campaign_id FROM marketing.leads)
campaign_idnameIN result
1Spring LaunchKEEP
2Retention WebinarKEEP
3Finance RetargetingKEEP
4Enterprise SearchSKIP

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.

Advanced business practice

Sign up free to try it on a real business scenario