SQL Practice Logo

SQLPractice Online

LEFT/RIGHT/FULL OUTER JOIN: Concept

Module: Joins & Relationships

OUTER JOINs preserve rows that don't have matches. LEFT JOIN keeps all left table rows, RIGHT JOIN keeps all right table rows, FULL OUTER JOIN keeps all rows from both tables. When a row has no match, the other table's columns are filled with NULL. Think of INNER JOIN as "only matches" and OUTER JOIN as "matches plus non-matches".

**What Are OUTER JOINs?**

OUTER JOINs preserve rows without matches, unlike INNER JOIN which excludes them.

**LEFT JOIN (LEFT OUTER JOIN):**

Returns ALL rows from left table + matching rows from right table.

SELECT * FROM customers c LEFT JOIN orders o ON c.id = o.customer_id;

Result:

- All customers appear (even without orders)

- Customers with orders: order columns populated

- Customers without orders: order columns NULL

**RIGHT JOIN (RIGHT OUTER JOIN):**

Returns ALL rows from right table + matching rows from left table.

SELECT * FROM orders o RIGHT JOIN customers c ON o.customer_id = c.id;

Result: Same as LEFT JOIN above (just tables swapped)

RIGHT JOIN is rarely used because you can always rewrite as LEFT JOIN:

A RIGHT JOIN B = B LEFT JOIN A

**FULL OUTER JOIN:**

Returns ALL rows from both tables.

SELECT * FROM customers c FULL OUTER JOIN orders o ON c.id = o.customer_id;

Result:

- All customers (even without orders)

- All orders (even without customers)

- Matched rows: both sides populated

- Unmatched rows: one side NULL

Not supported in MySQL/SQLite (use UNION of LEFT and RIGHT JOIN).

**Visual Comparison:**

INNER JOIN: Only intersection (matches only)

LEFT JOIN: All left + intersection

RIGHT JOIN: All right + intersection

FULL OUTER JOIN: All left + all right + intersection

**When to Use Each:**

**Use LEFT JOIN when:**

- You need all rows from main table

- Example: "All customers including those without orders"

- Example: "All products including those never sold"

- Example: "All employees including those without departments"

**Use RIGHT JOIN when:**

- Rarely! Usually rewrite as LEFT JOIN

- Only when query logic is clearer with RIGHT JOIN

- Most developers avoid RIGHT JOIN for consistency