112
I always mix up the different types of SQL JOINs. Can someone explain with clear examples:
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL OUTER JOIN
- CROSS JOIN
What's the difference and when would I use each one?
I always mix up the different types of SQL JOINs. Can someone explain with clear examples:
What's the difference and when would I use each one?
Let me explain with a practical example!
-- employees table
| id | name | dept_id |
|----|---------|---------|
| 1 | Alice | 1 |
| 2 | Bob | 2 |
| 3 | Charlie | NULL |
-- departments table
| id | name |
|----|-------------|
| 1 | Engineering |
| 2 | Marketing |
| 3 | HR |Returns only matching rows from both tables.
SELECT e.name, d.name as dept
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;Result:
| name | dept |
|---|---|
| Alice | Engineering |
| Bob | Marketing |
(Charlie excluded - no matching dept)
Returns ALL rows from left table + matching from right.
SELECT e.name, d.name as dept
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id;Result:
| name | dept |
|---|---|
| Alice | Engineering |
| Bob | Marketing |
| Charlie | NULL |
(Charlie included with NULL dept)
Returns ALL rows from right table + matching from left.
SELECT e.name, d.name as dept
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.id;Result:
| name | dept |
|---|---|
| Alice | Engineering |
| Bob | Marketing |
| NULL | HR |
(HR included even though no employees)
Returns ALL rows from BOTH tables.
SELECT e.name, d.name as dept
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.id;Result:
| name | dept |
|---|---|
| Alice | Engineering |
| Bob | Marketing |
| Charlie | NULL |
| NULL | HR |
Returns Cartesian product (every combination).
SELECT e.name, d.name as dept
FROM employees e
CROSS JOIN departments d;Result: 3 employees × 3 departments = 9 rows!
| JOIN Type | Returns |
|---|---|
| INNER | Only matches |
| LEFT | All left + matches |
| RIGHT | All right + matches |
| FULL | Everything |
| CROSS | All combinations |
Pro tip: Start with LEFT JOIN if unsure - it's the most commonly needed!
Login to share your knowledge and help other students.
Login to Post a Solution