Learn SQL/Intermediate/Joins/SQL INNER vs OUTER JOIN

SQL INNER vs OUTER JOIN

LEFT, RIGHT, and FULL OUTER are all 'outer' joins — they preserve unmatched rows. INNER is the only one that doesn't.

What & Why

Every join type covered in this series falls into one of two families. INNER keeps only matched rows. OUTER (covering LEFT, RIGHT, and FULL OUTER) preserves at least some unmatched rows, filling gaps with NULL.

See How It Works

BUSINESS QUESTION

Marketing wants every campaign in a coverage report, even when a campaign has no leads.

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
EXAMPLE QUERY
SELECT
  c.name,
  COUNT(l.id) AS lead_count
FROM marketing.campaigns c
LEFT JOIN marketing.leads l ON l.campaign_id = c.id
GROUP BY c.name
ORDER BY lead_count ASC, c.name ASC;
RESULT — exact output from the displayed Queryflo rows
namelead_count
Enterprise Search0
Finance Retargeting1
Retention Webinar1
Spring Launch2

LEFT JOIN preserves Enterprise Search and COUNT(l.id) returns zero.

Now You Try

Practice this concept

Marketing wants every campaign with its lead count, including campaigns with zero leads. Order by lead_count ascending and campaign name ascending.

Available schema
marketing

Prefix tables with marketing.table_name.

namelead_count
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario