Lesson 4 of 4

Progress: 0/3 exercises solved (0%)

← PreviousFinal lesson

Solve all exercises below to unlock the next lesson.

Joining three or more tables

Lesson Description

Learn how to connect related tables safely so your results stay accurate, readable, and business-ready.

Easy Project

Mini project: Build a people-and-departments report that lists employee names, department names, and validates row counts to prove your join is correct.

JOIN Visual

employees

departments

Match keys first, then verify row counts after the join.

SQL allows chaining as many JOINs as needed. Each JOIN adds one table to the query.

Three-table join example

Employee → Department → Location:

SELECT
  e.first_name,
  e.last_name,
  d.name   AS department,
  l.city   AS city
FROM employees    e
JOIN departments  d ON d.id  = e.department_id
JOIN locations    l ON l.id  = d.location_id;

Four-table join example (store)

Customer → Order → Order Item → Product:

SELECT
  c.first_name   AS customer,
  o.order_date,
  p.name         AS product,
  oi.quantity,
  oi.unit_price
FROM orders      o
JOIN customers   c  ON c.id  = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products    p  ON p.id  = oi.product_id
ORDER BY o.order_date, c.last_name;

Key rules

  1. Each JOIN has its own ON clause.
  2. You can mix JOIN, LEFT JOIN, etc. in the same query.
  3. Order of JOINs does not affect the logical result (though it can affect performance).

Readability tips

  • Use short, consistent aliases (e, d, o, c, p).
  • Align ON conditions vertically so the join structure is obvious at a glance.
  • Break across multiple lines — there is no penalty for whitespace.

Many-to-many relationships

A junction table (like order_items) sits between two tables to represent a many-to-many relationship. Always join through it:

customers → orders → order_items → products

Tips

  • If a multi-join query returns more rows than expected, a fan-out from a one-to-many join is likely the cause.
  • EXPLAIN ANALYZE shows the join strategy PostgreSQL chose and where time is spent.

Learning context

This lesson is part of Joins. Focus on the core idea in Joining three or more tables, then validate with deliberate practice.

What to master

  • Choose the base table (one row = what?)
  • Match join keys on true primary/foreign pairs
  • Validate row count after every join

Common mistakes

  • Joining many-to-many without pre-aggregation
  • Using DISTINCT to hide a bad join
  • Forgetting LEFT JOIN when keeping base rows

High-level strategy

  • Start with INNER JOIN to verify key matches
  • Switch to LEFT JOIN only when preserving base rows matters
  • Use COUNT(*) and COUNT(DISTINCT key) as join safety checks

Task ladder

  1. Baseline query: get a correct first output.
  2. Add one complication: edge case, join, filter, or ranking rule.
  3. Re-run and refine until output is stable and explainable.

Transparent data checks

  • Check row count before and after each major clause.
  • Validate one manual sample row for correctness.
  • Confirm final ordering and column naming for trust.

Retention loop

  • Run the solution once.
  • Rewrite from memory with one variation.
  • Explain the logic in plain English in one sentence.

Logical reasoning for commands

JOIN ... ON

Why: Connects rows only when keys truly match.

Memory cue: No key match = no trusted relationship.

LEFT JOIN

Why: Keeps base table rows even when lookup data is missing.

Memory cue: Left keeps the story intact.

COUNT(DISTINCT key)

Why: Confirms joins did not multiply business entities.

Memory cue: Distinct key count should stay believable.

Concept check

Quick check: Joining three or more tables

3 quick questions. One at a time. Instant score at the end.

Exercise 1

Employee with department and job title

Enterprise Workforce Analyticseasy

From the HR sandbox, return first_name, last_name, department name (alias department), and job title (alias job_title) for every employee. Order by last_name.

Run a query to see results here.
Exercise 2

Order items: customer, product, quantity

Commerce Operations Intelligenceeasy

From the store sandbox, join orders, customers, order_items, and products. Return customer first_name, product name, quantity, and unit_price. Order by orders.id, then products.name.

Run a query to see results here.
Exercise 3

Appointments with patient, doctor, and department

Clinical Care Performanceeasy

From the hospital sandbox, join appointments, patients, doctors, and departments. Return patient first_name, doctor first_name, department name (alias department), and appointment_date. Order by appointment_date, then patients.last_name.

Run a query to see results here.

Final checkpoint

End-of-course high-level quiz

Pass mark: 80%. Review each explanation after you submit.

1. Which clause should you use to filter grouped results?

2. What is the safest way to avoid accidental row multiplication in joins?

3. Which feature is best for ranking rows within partitions?

4. Why should final analytical queries usually include ORDER BY?

5. When query logic gets complex, what improves readability most?

Lesson 4 of 4

0/3 solved (0%)

← PreviousFinal lesson

Finish this lesson to unlock next.