TutreNews Learn

Combining tables

LEFT JOIN and NULL

Goal: Keep unmatched rows and find missing relationships · 9 min

A LEFT JOIN keeps all rows of the left table, even when there is no match on the right. The missing right-hand columns are filled with NULL.

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

Dan has no orders, so he appears once with o.id = NULL. A classic use: "Which customers have never ordered?" → WHERE o.id IS NULL.

COUNT(o.id) counts only matches, so a LEFT JOIN with COUNT gives 0 for customers without orders — COUNT(*) would wrongly give 1.

Worked example: Orders per customer including zero

  1. LEFT JOIN keeps Dan.
  2. COUNT(o.id) ignores his NULL.
  3. Dan: 0, Ada: 2, others: 1.
SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY c.id;

Output:

Ada | 2
Ben | 1
Cleo | 1
Dan | 0
Eva | 1