iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL LEFT JOIN

LEFT JOIN keeps every row from the left table; for rows with no match on the right, the right-side columns come back as NULL.

Example

SQL
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;

Customers without any order still appear — with total NULL.

The "find rows with no match" pattern

SQL
-- Customers who have never ordered
SELECT c.*
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

This is the classic anti-join — readable and well-optimised by most engines. NOT EXISTS is the equivalent (and NULL-safe) alternative.

Filtering: WHERE vs ON

Where you put the filter changes the meaning:

SQL
-- A: keep all customers, only show their 2026 orders
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o
  ON o.customer_id = c.id
 AND o.created_at >= '2026-01-01';

-- B: only customers who placed a 2026 order
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= '2026-01-01';
Tip: Putting a filter on the right-side table in the WHERE clause silently converts a LEFT JOIN into an INNER JOIN. If you don't want that, move it into the ON clause.

Example

Example
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
Try it Yourself »

Exercise

Keep every row from the left side, even unmatched ones.

JOIN orders ON ...

Test yourself

Q1. LEFT JOIN keeps every row from…
Q2. Anti-join "customers with no orders" uses…
Q3. Putting a right-side filter in WHERE silently turns LEFT JOIN into…

Discussion

Loading…