Section 3 · Lesson 1
Keys and INNER JOIN
Understand primary and foreign keys, then combine two tables with INNER JOIN to answer questions neither table can answer alone.
So far each query used one table. But the interesting questions cut across tables: which industry spends the most on ads? Which customer segment brings the most revenue? The answer lives in two places, and a join brings them together.
Why data is split into tables
Our database could have stored the advertiser’s name and industry on every one of the 1,561
daily_stats rows. Instead, each fact is stored once, in the table it belongs to, and
tables point at each other. That avoids contradictions (one row saying “Retail”, another
“Retial”) and makes updates easy. This design is called normalization.
Primary keys and foreign keys
- A primary key uniquely identifies each row of a table.
advertisers.id,campaigns.id,customers.idandorders.idare primary keys. Indaily_stats, the key is the pair (campaign_id,date): one row per campaign per day. - A foreign key is a column that holds another table’s primary key, creating a link.
The links in our dataset:
| Foreign key | Points to | Relationship |
|---|---|---|
campaigns.advertiser_id |
advertisers.id |
one advertiser, many campaigns |
daily_stats.campaign_id |
campaigns.id |
one campaign, many days |
orders.customer_id |
customers.id |
one customer, many orders |
orders.campaign_id |
campaigns.id |
one campaign, many orders (or none) |
Whenever you join, you’ll almost always match a foreign key to the primary key it points at.
INNER JOIN
SELECT c.name AS campaign, c.channel, a.name AS advertiser
FROM campaigns AS c
JOIN advertisers AS a
ON a.id = c.advertiser_id;
JOIN(short forINNER JOIN) names the second table.ONsays which rows belong together. For each campaign, SQL finds the advertiser whoseidequals the campaign’sadvertiser_id.- An inner join keeps only rows that found a match on both sides. Rows without a partner disappear, which is usually fine but sometimes exactly what you don’t want (next lesson).
Aliases and ambiguous columns
Both campaigns and advertisers have columns called id and name. If you write just
name, SQLite can’t know which one you mean and stops with “ambiguous column name”. Give each
table a short alias (c, a) and prefix columns with it: c.name, a.name. Many teams
prefix every column in a join, even unambiguous ones, so readers instantly see where it comes
from.
Joins and GROUP BY together
Join first, then aggregate as usual. Here’s the combined daily budget of each advertiser industry’s campaigns:
SELECT a.industry, ROUND(SUM(c.daily_budget), 2) AS total_daily_budget
FROM campaigns AS c
JOIN advertisers AS a ON a.id = c.advertiser_id
GROUP BY a.industry
ORDER BY total_daily_budget DESC;
Sanity-check your row counts
The most common join bug is a missing or wrong ON. Without ON, SQLite pairs every row with
every row (a cross join): 40 campaigns × 12 advertisers = 480 rows of nonsense. Before
trusting a join, ask: “How many rows should this return?” Joining campaigns to their
advertiser should give exactly 40 rows, one per campaign, because each campaign has exactly one
advertiser.
About the video: the
JOIN ... ON ...syntax it walks through is the same in SQLite and every other major database, so you can follow along in the sandbox.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Who runs each campaign?
DoneList every campaign next to the advertiser that runs it. Return three columns: the campaign's name, the advertiser's name and the advertiser's industry. The starter returns far too many rows; fix the join.
Need a hint?
- Without
ON, every campaign is paired with every advertiser (40 × 12 rows). campaigns.advertiser_idpoints atadvertisers.id: addON a.id = c.advertiser_id.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT c.name, a.name, a.industry
FROM campaigns AS c
JOIN advertisers AS a;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Completed revenue by customer segment
DoneWhich customer segment brings in the most money? For completed orders only, return three columns: the customer's segment, the number of completed orders, and their total amount rounded to 2 decimals. Sort by total amount, highest first.
Need a hint?
segmentlives incustomers, so joinorderstocustomersoncustomers.id = orders.customer_id.- Group by
cu.segmentinstead ofcustomer_id, then sort by the total descending.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT customer_id, COUNT(*) AS orders, ROUND(SUM(amount), 2) AS total_amount
FROM orders
WHERE status = 'completed'
GROUP BY customer_id;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Top 5 campaigns by spend
DoneShow the 5 campaigns with the highest total spend over the whole period. Return the campaign name, its channel, and its total spend from daily_stats rounded to 2 decimals, sorted by total spend, highest first.
Need a hint?
- Join
daily_statstocampaignsonc.id = d.campaign_idto get the name and channel. - Group by the campaign (its
id, plus thenameandchannelyou select).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT campaign_id, ROUND(SUM(spend), 2) AS total_spend
FROM daily_stats
GROUP BY campaign_id
ORDER BY total_spend DESC
LIMIT 5;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)