smartyfy.mrindigi.com

Databases & SQL Master Course — 034. Joining Three or More Tables

Lesson 034 Joining Three or More Tables

A sales report needs facts from three places: an author name, a book title, and the quantity on a sales line. Joining all three is manageable when you trace one relationship at a time and keep the output grain explicit. This lesson shows why unchanged row counts do not prove that a join preserved the same meaning.

Prerequisites and objectives

Complete Lesson 033. You should understand INNER and LEFT JOIN, filter placement, grouping, and aggregates. You will build a three-table path, inspect intermediate grain, aggregate a line-level measure correctly, and preserve optional relationships without accidentally turning them into required ones.

Step 1 Define every table’s grain

Run the fixture in a fresh empty SQLite scratch database with foreign keys enabled before a transaction. Authors are people, books are catalog titles, and sale_lines are recorded sales-line occurrences. A book can have several sales lines. A line’s quantity counts copies, while sale_price_cents is its realized price per copy in the fictional course currency.

PRAGMA foreign_keys = ON;
CREATE TABLE authors (
  author_id INTEGER PRIMARY KEY,
  author_name TEXT NOT NULL
);
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  author_id INTEGER NOT NULL REFERENCES authors(author_id),
  genre TEXT NOT NULL,
  price_cents INTEGER NOT NULL,
  stock INTEGER NOT NULL,
  subtitle TEXT
);
INSERT INTO authors VALUES
  (1,'Mira Chen'),(2,'Omar Silva'),(3,'Nia Patel'),(4,'Elio Park');
INSERT INTO books VALUES
  (101,'River Maps',1,'Travel',1800,4,NULL),
  (102,'SQL Trail',2,'Technology',2500,8,'Practice edition'),
  (103,'Garden Notes',3,'Nature',1200,0,NULL),
  (104,'Night Signals',1,'Fiction',1800,5,'');
CREATE TABLE sale_lines (
  sale_line_id INTEGER PRIMARY KEY,
  book_id INTEGER NOT NULL REFERENCES books(book_id),
  quantity INTEGER NOT NULL,
  sale_price_cents INTEGER NOT NULL
);
INSERT INTO sale_lines VALUES
  (1,101,2,1800),(2,101,1,1700),(3,102,1,2500),(4,104,3,1800);

River Maps has two sales lines at different prices. Garden Notes has no sale. Elio has no book. These cases distinguish catalog coverage, sales activity, and relationship absence. The line price is intentionally separate from the current listed book price, because a historical sale need not use today’s list price.

Step 2 Draw the relationship path

The path is authors.author_id to books.author_id, then books.book_id to sale_lines.book_id. Each ON condition should introduce the relationship of the newly joined table to a table already in the result. Avoid comparing unrelated primary keys merely because their names end with id.

Read the path aloud before writing the report: find each book’s author, then attach that book’s sales lines. The final detail result has one row per matching sales line, with descriptive author and book fields repeated as needed.

Step 3 Build the three-table detail

SELECT s.sale_line_id, a.author_name, b.title, s.quantity, s.sale_price_cents
FROM authors AS a
INNER JOIN books AS b ON b.author_id = a.author_id
INNER JOIN sale_lines AS s ON s.book_id = b.book_id
ORDER BY s.sale_line_id;

There are four result rows, one per sales line. River Maps appears twice because it sold on two recorded lines. Garden Notes and Elio do not appear because the INNER JOIN path requires a sale. The repeated title is evidence of the intended grain, not an error to remove with DISTINCT.

Step 4 Inspect cardinality at each stage

The author-to-book join has four matching rows. Adding sales still gives four rows in this fixture, but their meaning changed: one unsold book disappeared while a twice-sold book expanded. Equal before-and-after counts can conceal simultaneous losses and multiplication.

SELECT COUNT(*) AS sale_rows,
       COUNT(DISTINCT b.book_id) AS sold_titles,
       COUNT(DISTINCT a.author_id) AS selling_authors
FROM authors AS a
INNER JOIN books AS b ON b.author_id = a.author_id
INNER JOIN sale_lines AS s ON s.book_id = b.book_id;

The report contains four sale lines, three sold titles, and two authors with sales. These are different entity counts. A useful review tracks the relevant keys rather than relying on one total row count as proof that every relationship is correct.

Step 5 Calculate at the right grain

Revenue for this fictional line dataset is quantity multiplied by the line’s sale price. Add those line amounts only after confirming each sales line appears exactly once. This exercise does not include taxes, refunds, currency conversion, or accounting recognition rules.

SELECT a.author_id, a.author_name,
       SUM(s.quantity * s.sale_price_cents) AS recorded_sales_cents
FROM authors AS a
INNER JOIN books AS b ON b.author_id = a.author_id
INNER JOIN sale_lines AS s ON s.book_id = b.book_id
GROUP BY a.author_id, a.author_name
ORDER BY a.author_id;

Mira’s lines contribute 3600, 1700, and 5400, totaling 10700. Omar contributes 2500. The combined amount is 13200. Using the current listed price for River Maps would misstate the second line, which explicitly records a sale price of 1700 rather than 1800.

Mira connects through books 101 and 104 to sale-line amounts 3600, 1700 and 5400 cents, totaling 10700. Omar connects through book 102 to one 2500-cent sale line. Four sale lines cover three sold titles and two selling authors, totaling 13200 fictional cents.
Follow the keys to sale-line grain before summing: four lines represent three sold titles and two selling authors. Use each recorded sale price, including River Maps line 2 at 1700 cents. Open full-size diagram

Step 6 Preserve a complete directory

To include authors without books and books without sales, both relationships on this path must be optional. A LEFT JOIN to books followed by an INNER JOIN to sales would remove rows whose intermediate book or sale is missing.

When expanding beyond three tables, add one relationship at a time and inspect keys immediately. Two independent one-to-many children joined to the same parent can multiply each other. Do not aggregate an amount until the result grain and multiplicity are established; later advanced reports address safe pre-aggregation strategies.

Practice with worked solutions

Exercise 1

List each sales-line ID and book title, keeping both River Maps occurrences.

Worked solution
SELECT s.sale_line_id, b.title
FROM books AS b INNER JOIN sale_lines AS s ON s.book_id = b.book_id
ORDER BY s.sale_line_id;

The line key distinguishes the two River Maps occurrences. Removing one repeated title would discard a real sales line and its quantity.

Exercise 2

Calculate copies sold by author for authors with recorded sales.

Worked solution
SELECT a.author_id, SUM(s.quantity) AS copies_sold
FROM authors AS a
INNER JOIN books AS b ON b.author_id = a.author_id
INNER JOIN sale_lines AS s ON s.book_id = b.book_id
GROUP BY a.author_id ORDER BY a.author_id;

Mira has six copies across three lines; Omar has one copy on one line. Counting lines would give three and one, which is a different measure from sold quantity.

Exercise 3

Show every author, optional book, and optional sales-line ID using two LEFT JOINs.

Worked solution
SELECT a.author_id, b.book_id, s.sale_line_id
FROM authors AS a
LEFT JOIN books AS b ON b.author_id = a.author_id
LEFT JOIN sale_lines AS s ON s.book_id = b.book_id
ORDER BY a.author_id, b.book_id, s.sale_line_id;

Six rows appear. Nia retains book 103 with no sale, and Elio retains a row with neither book nor sale. The different NULL patterns describe different missing stages of the path.

Exercise 4

Explain why joining sale_line_id to book_id is wrong, and run the faulty comparison in the scratch database.

Worked solution
SELECT s.sale_line_id, b.book_id
FROM books AS b INNER JOIN sale_lines AS s ON s.sale_line_id = b.book_id
ORDER BY s.sale_line_id;

No rows match in this fixture. sale_line_id identifies a transaction line; sale_lines.book_id is the reference to the catalog. Replace the former with the latter in ON.

Knowledge check

Question 1

What is the detail result grain after the three-table INNER JOIN?

  1. One row per author
  2. One row per sale line
  3. One row per genre
  4. One row per copy automatically
Answer and explanation

B. Each matching sale line carries repeated author and book descriptions.

Question 2

Why can equal row counts conceal a problem?

  1. Counts always fail
  2. All joins are random
  3. Some rows can disappear while others multiply
  4. Keys become irrelevant
Answer and explanation

C. Losses and expansions can offset numerically while changing membership and grain.

Question 3

Which price belongs in the historical line calculation?

  1. The line sale_price_cents
  2. The highest catalog price
  3. Any current list price
  4. The author ID
Answer and explanation

A. The recorded line price describes that sale; current catalog price is a separate fact.

Question 4

How many distinct sold titles appear?

  1. Two
  2. Four
  3. Seven
  4. Three
Answer and explanation

D. River Maps, SQL Trail, and Night Signals sold; Garden Notes did not.

Question 5

How can the full author-book-sale path preserve missing stages?

  1. Use INNER JOIN everywhere
  2. Use LEFT JOIN for both optional relationships
  3. Add DISTINCT at the end
  4. Remove all NULLs
Answer and explanation

B. Every optional stage must retain unmatched rows rather than reintroducing a required match.

Pitfalls and summary

Do not equate unchanged counts with unchanged grain, confuse line counts with quantities, or use current prices for historical line facts. Trace keys one relationship at a time, inspect intermediate membership, and aggregate only after establishing exactly what each result row represents.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references