What is INNER JOIN?
Students Table
| id | name |
|---|---|
| 1 | John |
| 2 | Mary |
| 3 | Peter |
3 rows
Enrollments Table
| enrollment_id | student_id | course |
|---|---|---|
| 101 | 1 | Math |
| 102 | 2 | Science |
2 rows
INNER JOIN combines rows from two tables when they match.
Simple analogy: Matching students with their classes - show only students who are enrolled in classes.
Basic Example
Students Table
| id | name |
|---|---|
| 1 | John |
| 2 | Mary |
| 3 | Peter |
3 rows
Enrollments Table
| enrollment_id | student_id | course |
|---|---|---|
| 101 | 1 | Math |
| 102 | 2 | Science |
2 rows
Two tables:
Students:
- ID 1: John
- ID 2: Mary
- ID 3: Peter (not enrolled)
Enrollments:
- John enrolled in Math
- Mary enrolled in Science
SELECT students.name, enrollments.course
FROM students
INNER JOIN enrollments ON students.id = enrollments.student_id;Result: Only John and Mary (Peter not shown because he has no enrollment)
Real-Life Example
Students Table
| id | name |
|---|---|
| 1 | John |
| 2 | Mary |
| 3 | Peter |
3 rows
Enrollments Table
| enrollment_id | student_id | course |
|---|---|---|
| 101 | 1 | Math |
| 102 | 2 | Science |
2 rows
Customers and Orders:
SELECT customers.name, orders.total
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id;Shows only customers who have orders.
When to Use
Students Table
| id | name |
|---|---|
| 1 | John |
| 2 | Mary |
| 3 | Peter |
3 rows
Enrollments Table
| enrollment_id | student_id | course |
|---|---|---|
| 101 | 1 | Math |
| 102 | 2 | Science |
2 rows
Use INNER JOIN when you want only matching records from both tables.
Example: Show students who are enrolled (exclude students with no classes)
What Comes Next
Students Table
| id | name |
|---|---|
| 1 | John |
| 2 | Mary |
| 3 | Peter |
3 rows
Enrollments Table
| enrollment_id | student_id | course |
|---|---|---|
| 101 | 1 | Math |
| 102 | 2 | Science |
2 rows
Next: LEFT JOIN (shows all records from left table, even without match)