SQL JOIN types explained with examples

Asked by Patricia Johnson Sep 24, 2025 beginner 1650 views
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?

Solutions

1 answer
Accepted Answer
198

Let me explain with a practical example!

Sample Tables

-- 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          |

INNER JOIN

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)

LEFT JOIN

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)

RIGHT JOIN

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)

FULL OUTER JOIN

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

CROSS JOIN

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!

Quick Reference

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!

Answered by Patricia Johnson Oct 2, 2025