SQL
INNER JOIN
Learn how to combine rows from two or more tables by matching values in a shared column: the essential building block of relational queries.
Why Do We Need to Join Tables?
Relational databases spread data across multiple tables to avoid duplication. A school database might store students in one table and enrollments in another. To answer "Which courses is Ada enrolled in?" you must connect rows that share the same student ID.
Key Terms to Know
Visualizing INNER JOIN
The Syntax of INNER JOIN
How Row Matching Works
Ada (id=1) matches two enrollment rows, so she appears twice. Bo (id=2) has no enrollment, so he is excluded entirely.
INNER vs. LEFT vs. CROSS JOIN
| INNER JOIN | LEFT JOIN | CROSS JOIN | |
|---|---|---|---|
| Returns | Only matched rows | All left rows + matches | Every combination |
| Unmatched left rows | Excluded | Kept (NULLs) | N/A |
| ON clause | Required | Required | None |
| Use when | You need only matches | You need all left rows | Generating combos |
Step-by-Step Approach
table_a.key = table_b.key.Example 1: Basic Join
Goal: List every student alongside the course they are enrolled in.
| name | course |
|---|---|
| Ada | Math |
| Ada | Art |
| Cal | Bio |
Example 2: Using Aliases
Table names can get long. Aliases let you abbreviate them for readability.
Example 3: Joining Three Tables
Goal: Show each student's name, course name, and teacher name.
Does Table Order Matter?
A JOIN B returns the same rows as B JOIN A.Explicit vs. Implicit Join Syntax
INNER JOIN enrollments
ON students.id = enrollments.student_id
WHERE students.id = enrollments.student_id
Query Execution Order
Common Mistakes
students.name vs. teachers.name.INNER JOIN Cheat Sheet
| Concept | Key Detail |
|---|---|
| What it returns | Only rows with a match in both tables |
| Required clause | ON table_a.key = table_b.key |
| Table order | Does not affect the result |
| Multiple joins | Chain: INNER JOIN ... ON ... INNER JOIN ... ON |
| Duplicates | One-to-many keys create multiple rows |
| Best practice | Use explicit syntax + table aliases |
Question 1 of 5
What does an INNER JOIN return?
Question 2 of 5
Given the tables orders (with column customer_id) and customers (with column id), which ON clause correctly joins them?
Question 3 of 5
Table A has 5 rows. Table B has 4 rows. Two rows in A have no match in B. How many rows does A INNER JOIN B return (assuming each matched A-row matches exactly one B-row)?
Question 4 of 5
Query:
SELECT s.name, e.course
FROM students s
INNER JOIN enrollments e
ON s.id = e.student_id
WHERE e.course = 'Math';
What does this query return?
Question 5 of 5
What happens if you write INNER JOIN but forget the ON clause entirely?