SQL · Module 7 · Lesson 31 min read

LEFT & RIGHT JOIN

LEFT JOIN (LEFT OUTER JOIN)

Returns every row from the left table, plus matching rows from the right table. Where there's no match, the right side's columns are NULL.

SQL
SELECT u.name, e.title
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id;

Maya and Hari appear with title = NULL.

RIGHT JOIN

The mirror image: every row from the right table. Any RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the tables, so most people just use LEFT JOIN for consistency.

Counting with LEFT JOIN ⚠️

  • count(*) counts the NULL-filled row too → Maya shows 1 ❌
  • count(e.id) counts only real matches → Maya shows 0 ✅
  • sum(e.amount) gives NULL for no matches → wrap in COALESCE(sum(e.amount), 0)

⚠️ The WHERE trap

A filter on the right table in WHERE turns a LEFT JOIN back into an INNER JOIN:

SQL
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id
WHERE e.spent_on >= '2026-11-01'   -- ❌ Maya/Hari vanish (NULL >= date is not true)

✅ Put conditions on the right table inside ON:

ini
LEFT JOIN expenses e ON e.user_id = u.id AND e.spent_on >= '2026-11-01'

Rule: conditions on the left table → WHERE; conditions that limit which right rows match → ON.

Typical uses

  • Lists that must include everyone (all users with their totals, all categories with counts)
  • Optional relationships (an expense may have no category)
  • Finding missing data — rows with no match (lesson 7.7)

Example

SQL
-- Every user, with their expense count and total (including users with none)
SELECT u.name,
       count(e.id)                   AS expenses,      -- ✅ count a right-side column
       COALESCE(sum(e.amount), 0)    AS total
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id
GROUP BY u.id
ORDER BY total DESC;
-- ... Maya Karki 0 | 0, Hari Shrestha 0 | 0

-- count(*) vs count(e.id)
SELECT u.name, count(*) AS wrong, count(e.id) AS right_count
FROM users u LEFT JOIN expenses e ON e.user_id = u.id
WHERE u.name IN ('Maya Karki', 'Asha Sharma')
GROUP BY u.name;
-- Asha 10 | 10, Maya 1 | 0

-- ❌ WHERE on the right table removes users without November expenses
SELECT u.name, sum(e.amount) AS nov_total
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id
WHERE e.spent_on >= '2026-11-01'
GROUP BY u.name;                               -- only 4 users

-- ✅ Condition in ON keeps everyone
SELECT u.name, COALESCE(sum(e.amount), 0) AS nov_total
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id AND e.spent_on >= '2026-11-01'
GROUP BY u.name
ORDER BY nov_total DESC;                       -- all 6 users

-- Every category with how often it's used (Health has 0)
SELECT c.name, count(e.id) AS times_used
FROM categories c
LEFT JOIN expenses e ON e.category_id = c.id
GROUP BY c.name
ORDER BY times_used DESC, c.name;

-- RIGHT JOIN = LEFT JOIN with tables swapped
SELECT u.name, e.title
FROM expenses e
RIGHT JOIN users u ON u.id = e.user_id
WHERE e.id IS NULL;                            -- Maya Karki, Hari Shrestha