SQL · Chapter 15 of 42

SQL JOIN Overview

JOIN combines rows from two or more tables based on a related column — usually a foreign key.

Main types: INNER, LEFT, RIGHT, FULL OUTER, and CROSS.

Syntax
SELECT ... FROM a JOIN b ON a.b_id = b.id;

Types at a glance

INNER: only matching rows. LEFT: all from left + matches from right. RIGHT: mirror of LEFT. FULL: all from both. CROSS: cartesian product.

ON clause

The `ON` clause states the matching condition, usually `left.fk = right.pk`.

Example 1 (sql)
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON o.user_id = u.id;
Output
one row per matching (user, order) pair

Classic parent-child join.

Example 2 (sql)
SELECT u.name, o.total
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;
Output
all users, orders where present, NULL otherwise

LEFT keeps every user.

Key points

  • INNER JOIN = only matches.
  • LEFT JOIN = all left rows.
  • The ON clause states the match condition.
  • Missing matches become NULLs on the outer side.
💡 Note: Almost every JOIN you'll write in real projects is INNER or LEFT. RIGHT and FULL are rare.

📝 Quick Quiz

1. Which JOIN returns only matching rows?

2. LEFT JOIN preserves rows from:

3. The match condition uses which keyword?