Skip to content
/Chapter 12 · Applied Practice: Website Analytics
Lesson 12.3·website_analytics
Lesson 12.3

SQL JOIN Practice: Attributing Sessions to Campaigns

Turn campaign ids into campaign names, and watch which campaigns quietly fall out of an inner join.

Each paid, social, or email session carries a campaign_id, but a report needs the campaign's name. That lives in the campaigns table, reached by joining on the key.

Grouping the joined rows by campaign_name answers a core marketing question: which campaigns actually brought people to the site?

An INNER JOIN only keeps matches

The campaigns table lists a Retargeting campaign, but no session references it. Because an INNER JOIN keeps only rows that match on both sides, that campaign never appears in the result. Sessions with a NULL campaign_id (organic and direct traffic) drop out too. That is exactly what you want when the question is about campaigns.

Pattern
select dim.label, dim.attribute, count(*) as events
from fact_table as fact
join dim_table as dim on fact.dim_id = dim.dim_id
group by dim.label, dim.attribute
order by events desc, dim.label
Schema · Website AnalyticsTable · campaigns5 columns · 5 rows
Table · campaigns

Marketing campaigns with their channel and UTM tags.

5 columns · 5 rows
campaign_id intcampaign_name textchannel textutm_source textutm_medium text
Your task

For each campaign that drove traffic, return the campaign_name, its channel, and the number of sessions (sessions). Sort by sessions descending, then campaign name.

SQL Workbench
query.sqlwebsite_analytics · SQL engine loading
⌘↵ to run
·
Expected answer
  • Columns: campaign_name, channel, sessions.
  • Rows: 4 campaigns that actually drove sessions.
  • Social Promo leads with 8 sessions; the Retargeting campaign drops out with zero.