Multiple Table Queries
SQL Joins: Combining Rows from Related Tables
A relational database stores each fact once, so the data behind a single question is usually spread across several tables: customers in one, their orders in another. A join pairs rows from two tables and returns their columns side by side as one result. You write joins whenever a report needs columns from more than one table. You also need to predict exactly which rows a join keeps, because the wrong join type silently drops or duplicates data.
The join condition
A join compares rows of one table with rows of another and keeps each pair that satisfies the join condition, the Boolean expression written after ON. Most join conditions match a foreign key to the primary key it refers to:
SELECT c.name, o.order_id
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id;The aliases c and o shorten the table names and say which table each column comes from. Aliases or full table names are required when both tables contain a column with the same name.
In the figure, Ana matches two orders, Ben matches one and Chloe matches none. Order 104 was a guest checkout, so its customer_id is NULL. An equality test involving NULL is never true: NULL does not equal anything, not even another NULL. The query above therefore returns three rows: (Ana, 101), (Ana, 102) and (Ben, 103).
Inner and outer joins
An INNER JOIN keeps only matched pairs. An outer join also keeps rows that found no partner and fills the other table's columns with NULL. The keyword decides whose unmatched rows survive, and left and right refer to the order in which the tables are written in the FROM clause.
Join type | Rows kept | Rows for the figure data |
|---|---|---|
INNER JOIN | Matched pairs only | 3 |
LEFT JOIN | Matched pairs plus unmatched left rows | 4, adding (Chloe, NULL) |
RIGHT JOIN | Matched pairs plus unmatched right rows | 4, adding (NULL, 104) |
FULL OUTER JOIN | Matched pairs plus unmatched rows of both tables | 5 |
CROSS JOIN | Every pair, with no condition | 12 |
A RIGHT JOIN B returns the same rows as B LEFT JOIN A, so many developers write only left joins. JOIN on its own means INNER JOIN, and LEFT JOIN is shorthand for LEFT OUTER JOIN; some systems, such as MySQL, do not support FULL OUTER JOIN directly. A CROSS JOIN produces the Cartesian product, here 3×4=12 rows. It is useful for generating combinations but is usually a bug when it comes from a missing join condition. A self-join joins a table to itself under two aliases, for example employees e JOIN employees m ON e.manager_id = m.emp_id to pair each employee with their manager.
Predicting row counts
Suppose row a of the left table A matches ma rows of the right table B. An inner join returns ∑ma rows. A left join returns one row per match, plus one NULL-padded row for each left row with no match:
For the figure, Ana, Ben and Chloe have ma equal to 2, 1 and 0, so the left join returns 2+1+1=4 rows. A full outer join adds one row for each unmatched right row, giving 4+1=5. Two consequences follow. A join can return more rows than either table when a key value repeats on both sides, and a left join with no WHERE clause never returns fewer rows than its left table.
What to remember
- A join keeps the row pairs for which the ON condition is true; NULL keys never match.
- INNER keeps matches only; LEFT, RIGHT and FULL OUTER also keep unmatched rows from the left, right or both tables, padded with NULL.
- A left join returns ∑max(1,ma) rows: never fewer than the left table, often more.
- Filters on the optional side of an outer join belong in ON, not WHERE.
Example: Tracing Joins in a Course-Enrollment Database
A university registrar keeps students, courses and enrollments in three tables. Each row of enrollments records that one student is taking one course, with student_id and course_id as foreign keys.
students
student_id | name |
|---|---|
1 | Priya |
2 | Marcus |
3 | Lena |
4 | Diego |
courses
course_id | title | credits |
|---|---|---|
CS201 | Data Structures | 4 |
CS220 | Databases | 3 |
MA210 | Linear Algebra | 3 |
enrollments
student_id | course_id |
|---|---|
1 | CS201 |
1 | CS220 |
2 | CS220 |
2 | MA210 |
3 | CS220 |
a) Predict how many rows this query returns, and say which student is missing from the result.
SELECT s.name, c.title
FROM students s
INNER JOIN enrollments e ON s.student_id = e.student_id
INNER JOIN courses c ON e.course_id = c.course_id;Work through the joins in the order they are written. The first inner join pairs each student with their enrollment rows: Priya matches ________ rows, Marcus matches ________ rows, Lena matches ________ row and Diego matches none, so Diego is dropped.
Every course_id in enrollments exists in courses, so the second inner join attaches exactly one course to each surviving row and leaves the count unchanged.
Adding the matches gives a result of 5 rows. Diego does not appear, because an inner join discards a row that has no partner.
b) The registrar wants a list of students who are not enrolled in any course. What does this query return, and why does it work?
SELECT s.name
FROM students s
LEFT JOIN enrollments e ON s.student_id = e.student_id
WHERE e.student_id IS NULL;The left join keeps every student. Priya, Marcus and Lena keep their five matched rows, and Diego appears once with NULL in every enrollments column, so before WHERE runs the intermediate result holds ________ rows.
WHERE e.student_id IS NULL keeps only the rows where the enrollment side is missing. In a matched row e.student_id equals the student's id and is never NULL, so only Diego's row survives. The query returns one row: Diego.
This pattern is an anti-join: a query that returns the rows of one table that have no match in another. Test the join column, or another column that cannot be NULL in a real match, and write IS NULL; the test e.student_id = NULL is never true and would return no rows.
c) A colleague counts each student's courses with the query below. What does it report for Diego, and how should it be corrected?
SELECT s.name, COUNT(*) AS courses_taken
FROM students s
LEFT JOIN enrollments e ON s.student_id = e.student_id
GROUP BY s.student_id, s.name;After the left join, Diego's group contains ________ row, the NULL-padded one from part b. COUNT(*) counts rows regardless of their contents, so it reports 1 course for Diego, which is wrong.
After an outer join, count a column from the optional side, not the rows. Replace COUNT(*) with COUNT(e.course_id), which counts only non-NULL values. In Diego's row e.course_id is ________, so the count for Diego becomes 0.
The corrected query reports Priya 2, Marcus 2, Lena 1 and Diego 0. The other three counts are the same under both versions, because every one of their rows contains a real course_id.
A project attendance report combines two tables:
- Memberships(project_id, member_id, role), with alias m.
- Checkins(project_id, member_id, checkin_date), with alias c.
A member may belong to several projects, and each project may have several members. Together, project_id and member_id uniquely identify a membership. Each check-in must match the membership for the same project and the same member.
The query begins as follows:
SELECT m.project_id, m.member_id, m.role, c.checkin_date
FROM Memberships AS m
INNER JOIN Checkins AS c
ON m.project_id = c.project_idComplete the condition by filling the two statements below.
The additional comparison is between m.member_id and the Checkins column named . The SQL logical operator connecting the project comparison and the member comparison is .
A logistics database has a warehouses table, one row per warehouse with key warehouse_id, and a shipments table, one row per shipment with columns warehouse_id and ship_month (text such as '2026-10'). You need a report listing every warehouse with its October 2026 shipments, in which a warehouse that shipped nothing that month still appears once with NULL shipment columns. Which FROM clause produces this report?