Example Tables
We will use two sample tables for our JOIN examples:
Students Table
| ID | Name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
Courses Table
| CourseID | Student_ID | Course |
|---|---|---|
| 101 | 1 | Math |
| 102 | 2 | Science |
| 103 | 4 | History |
1. INNER JOIN
Definition: Returns only the rows that have matching values in both tables.
ABB
SELECT students.name, courses.course
FROM students
INNER JOIN courses
ON students.id = courses.student_id;
Result:
| Name | Course |
|---|---|
| Alice | Math |
| Bob | Science |
2. LEFT JOIN
Returns all rows from the left table and matched rows from the right table. NULL if no match.
SELECT students.name, courses.course
FROM students
LEFT JOIN courses
ON students.id = courses.student_id;
Result:
| Name | Course |
|---|---|
| Alice | Math |
| Bob | Science |
| Charlie | NULL |
3. RIGHT JOIN
Returns all rows from the right table and matched rows from the left table. NULL if no match.
SELECT students.name, courses.course
FROM students
RIGHT JOIN courses
ON students.id = courses.student_id;
Result:
| Name | Course |
|---|---|
| Alice | Math |
| Bob | Science |
| NULL | History |
4. FULL OUTER JOIN
SELECT students.name, courses.course
FROM students
FULL OUTER JOIN courses
ON students.id = courses.student_id;
Result:
| Name | Course |
|---|---|
| Alice | Math |
| Bob | Science |
| Charlie | NULL |
| NULL | History |
5. CROSS JOIN
SELECT students.name, courses.course
FROM students
CROSS JOIN courses;
Result: 3 students × 3 courses = 9 rows