TExcelTAD
Home › PostgreSQL › PostgreSQL LEFT JOIN

PostgreSQL LEFT JOIN

A LEFT JOIN (also written LEFT OUTER JOIN) returns every row of the left table, whether or not it has a match in the right table. Where there is no match, the right table's columns are filled with NULL.

text
SELECT …
FROM left_table
LEFT JOIN right_table ON condition;

Keeping rows without a partner

Every author with their books, including authors who have written none yet:

pgsql · try it yourself
SELECT a.name, b.title
FROM authors a
LEFT JOIN books b ON b.author_id = a.id
WHERE a.id IN (8, 9, 10)
ORDER BY a.name, b.title;
     name      |         title
---------------+------------------------
 Elena Petrova | Paper Lanterns
 Elena Petrova | Winter in Sofia
 Grace Liu     |
 Jonas Weber   | Algorithms on a Napkin
(4 rows)

Grace Liu has no books, so her title is NULL (shown empty). An INNER JOIN would have dropped her.

Finding rows with no match

The NULLs from a left join are useful in themselves. "Which customers have never ordered?" is a left join plus a test for NULL on the right side:

pgsql · try it yourself
SELECT c.id, c.first_name, c.last_name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL
ORDER BY c.id;
 id | first_name | last_name
----+------------+-----------
  7 | Gina       | Rossi
 13 | Mia        | Fischer
 15 | Olivia     | Martin
(3 rows)

The same pattern finds the books that were never sold:

pgsql · try it yourself
SELECT b.id, b.title
FROM books b
LEFT JOIN order_items oi ON oi.book_id = b.id
WHERE oi.book_id IS NULL
ORDER BY b.id;
 id |       title
----+-------------------
  2 | Harbor Lights
 12 | The Age of Canals
 16 | Winter in Sofia
(3 rows)

This is called an anti-join. WHERE NOT EXISTS (…) expresses the same idea and is just as fast in PostgreSQL.

Counting with a left join

To count orders per customer including the zeros, count a column from the right table. count(o.id) skips the NULLs, while count(*) would count the NULL row as 1:

pgsql · try it yourself
SELECT c.first_name,
       count(o.id) AS orders,
       count(*)    AS wrong_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE c.id IN (1, 2, 7, 13)
GROUP BY c.id, c.first_name
ORDER BY c.id;
 first_name | orders | wrong_count
------------+--------+-------------
 Anna       |      3 |           3
 Ben        |      3 |           3
 Gina       |      0 |           1
 Mia        |      0 |           1
(4 rows)

ON versus WHERE: a classic trap

With an inner join it doesn't matter whether a condition is in ON or WHERE. With a left join it matters a lot:

  • A condition in ON decides which right-hand rows match; left rows are kept anyway.
  • A condition in WHERE filters the final result, and throws away the left rows whose right side is NULL.
pgsql · try it yourself
-- Delivered orders per customer; customers without any still appear
SELECT c.first_name, count(o.id) AS delivered
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'delivered'
WHERE c.id IN (4, 7, 14)
GROUP BY c.id, c.first_name ORDER BY c.id;

-- Same filter in WHERE: the left join silently becomes an inner join
SELECT c.first_name, count(o.id) AS delivered
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE c.id IN (4, 7, 14) AND o.status = 'delivered'
GROUP BY c.id, c.first_name ORDER BY c.id;
 first_name | delivered
------------+-----------
 David      |         1
 Gina       |         0
 Noah       |         0
(3 rows)

 first_name | delivered
------------+-----------
 David      |         1
(1 row)

Gina (no orders) and Noah (only a shipped order) disappear from the second result.

Chaining left joins

When the first join is a left join, later joins that depend on it usually need to be left joins too, or they will remove the NULL rows again:

pgsql · try it yourself
SELECT cat.name AS category, b.title, a.name AS author
FROM categories cat
LEFT JOIN books b   ON b.category_id = cat.id
LEFT JOIN authors a ON a.id = b.author_id
WHERE cat.id IN (6, 7)
ORDER BY cat.name, b.title;
 category |      title       |   author
----------+------------------+-------------
 Children | Moon Socks       | Priya Nair
 Children | Ten Tiny Dragons | Aiko Tanaka
 Poetry   |                  |
(3 rows)

Test yourself

What does LEFT JOIN put in the right table's columns when there is no match?

  1. Empty strings
  2. Zeros
  3. NULL
  4. The row is dropped

How do you find customers without orders using a LEFT JOIN?

  1. WHERE o.id IS NOT NULL
  2. WHERE o.id IS NULL
  3. WHERE c.id IS NULL
  4. HAVING count(*) = 0

Why can a condition on the right table in WHERE turn a LEFT JOIN into an inner join?

  1. WHERE runs before the join
  2. NULL rows fail the condition and are filtered out
  3. PostgreSQL rewrites LEFT to INNER always
  4. It doesn't