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.

25 min 3 practice tasks
How to Join Tables in SQL | Clearly Explained | Beginners Start Here! by Maven Analytics on YouTube

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.id and orders.id are primary keys. In daily_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 for INNER JOIN) names the second table.
  • ON says which rows belong together. For each campaign, SQL finds the advertiser whose id equals the campaign’s advertiser_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.

1

Who runs each campaign?

List 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?
  1. Without ON, every campaign is paired with every advertiser (40 × 12 rows).
  2. campaigns.advertiser_id points at advertisers.id: add ON a.id = c.advertiser_id.
SQL · SQLite
SELECT c.name, a.name, a.industry
FROM campaigns AS c
JOIN advertisers AS a;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

Completed revenue by customer segment

Which 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?
  1. segment lives in customers, so join orders to customers on customers.id = orders.customer_id.
  2. Group by cu.segment instead of customer_id, then sort by the total descending.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
3

Top 5 campaigns by spend

Show 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?
  1. Join daily_stats to campaigns on c.id = d.campaign_id to get the name and channel.
  2. Group by the campaign (its id, plus the name and channel you select).
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue