Section 3 · Lesson 3

Joining three or more tables

Chain joins along the foreign keys to connect daily stats, campaigns, advertisers, orders and customers, without double counting.

30 min 3 practice tasks
Joining Multiple Tables in SQL (Visually Explained) | 3+ Table Joins | #SQL Course 10 by Data with Baraa on YouTube

Real questions often span three or more tables. “Revenue by advertiser industry” needs daily_stats (the numbers), campaigns (the link) and advertisers (the industry). The good news: there’s nothing new to learn syntactically. You add one JOIN ... ON ... per table.

Plan the path first

Before writing SQL, trace a route through the foreign keys from the table holding your numbers to the table holding your labels:

daily_stats ──campaign_id──▶ campaigns ──advertiser_id──▶ advertisers
orders ──campaign_id──▶ campaigns
orders ──customer_id──▶ customers

Each arrow is one join. To get from daily_stats to advertisers you must pass through campaigns, even if you don’t select a single column from it.

A chain of joins

SELECT a.name AS advertiser,
       c.name AS campaign,
       SUM(d.conversions) AS conversions
FROM daily_stats AS d
JOIN campaigns   AS c ON c.id = d.campaign_id
JOIN advertisers AS a ON a.id = c.advertiser_id
GROUP BY a.name, c.id, c.name
ORDER BY conversions DESC
LIMIT 5;

Read it top-down: start with the daily rows, attach each row’s campaign, then attach that campaign’s advertiser. Each new ON can refer to any table already joined above it.

A star: two joins from one table

Joins don’t have to form a line. orders points at both customers and campaigns, so one query can slice sales by customer attributes and campaign attributes:

SELECT cu.segment, c.channel, COUNT(*) AS orders
FROM orders AS o
JOIN customers AS cu ON cu.id = o.customer_id
JOIN campaigns AS c  ON c.id  = o.campaign_id
WHERE o.status = 'completed'
GROUP BY cu.segment, c.channel
ORDER BY cu.segment, c.channel;

Note that the inner join to campaigns silently removes unattributed orders. If you need them, make that join a LEFT JOIN and label the NULLs with COALESCE.

Know your grain

The grain of a result is what one row represents. daily_stats is one row per campaign per day; orders is one row per order. Every join can change the grain:

  • Joining up to a “one” side (daily_stats → campaigns → advertisers) keeps the grain: each daily row still appears once, now with extra columns. Sums stay correct.
  • Joining down to a “many” side multiplies rows. One campaign row joined to its orders becomes one row per order.

The double-counting trap

Trouble starts when you join two different “many” tables to the same parent. Suppose you want spend and orders per campaign and write:

-- WRONG: daily_stats and orders are both "many" sides of campaigns
SELECT c.name, SUM(d.spend) AS spend, COUNT(o.id) AS orders
FROM campaigns AS c
JOIN daily_stats AS d ON d.campaign_id = c.id
JOIN orders      AS o ON o.campaign_id = c.id
GROUP BY c.id, c.name;

Every daily row gets paired with every order of the same campaign. For BlueHarbor Conversions Search 38, which has 18 orders, true spend is about 61,285 USD, but this query reports more than 1.1 million: each day’s spend counted 18 times. No error, just a confidently wrong number.

The fix is to aggregate each “many” table separately down to one row per campaign, then join those summaries. You’ll do exactly that with CTEs in the next section. Until then, a quick safety check: compare a total from your join with the same total from the base table alone (SELECT SUM(spend) FROM daily_stats). If they disagree, rows were multiplied.

About the video: it’s recorded in SQL Server with a different sample database, but multi-table join syntax is identical in SQLite.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Spend and revenue by industry

Leadership wants ad performance by advertiser industry. Return three columns: the industry, total spend and total revenue from daily_stats (both rounded to 2 decimals). Sort by total revenue, highest first.

Need a hint?
  1. daily_stats has no advertiser columns. Go through campaigns: daily_stats → campaigns → advertisers.
  2. Add JOIN advertisers AS a ON a.id = c.advertiser_id, then group by a.industry.
SQL · SQLite
SELECT c.advertiser_id,
       ROUND(SUM(d.spend), 2) AS spend,
       ROUND(SUM(d.revenue), 2) AS revenue
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
GROUP BY c.advertiser_id
ORDER BY revenue DESC;
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 orders per advertiser

Which advertisers' campaigns drive the most completed sales? For completed orders that are attributed to a campaign, return the advertiser name, the number of orders, and their total amount rounded to 2 decimals. Sort by total amount, highest first.

Need a hint?
  1. The path is orders → campaigns → advertisers. An inner join to campaigns automatically drops unattributed orders.
  2. Group by the advertiser (a.id, a.name), not by campaign.
SQL · SQLite
SELECT o.campaign_id, COUNT(*) AS orders, ROUND(SUM(o.amount), 2) AS total_amount
FROM orders AS o
WHERE o.status = 'completed'
GROUP BY o.campaign_id
ORDER BY total_amount DESC;
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

US sales by campaign channel

For completed orders placed by customers whose country is US and that are attributed to a campaign, return the campaign channel, the number of orders, and their total amount rounded to 2 decimals. Sort by number of orders, highest first.

Need a hint?
  1. country lives in customers, so orders needs a second join: JOIN customers AS cu ON cu.id = o.customer_id.
  2. Then add cu.country = 'US' to the WHERE clause.
SQL · SQLite
SELECT c.channel, COUNT(*) AS orders, ROUND(SUM(o.amount), 2) AS total_amount
FROM orders AS o
JOIN campaigns AS c ON c.id = o.campaign_id
WHERE o.status = 'completed'
GROUP BY c.channel
ORDER BY orders DESC;
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