Outer joins

Topic 2 of 4 in Joining tables12 min readBeginnerFree course

Overview

An inner join only returns rows that find a partner. Often that’s exactly right — but just as often the rows without a partner are the interesting ones: customers who never ordered, products that never sold, categories with nothing in them. Outer joins keep those rows, filling the missing side with NULLs.

Inner, left, right and full joins, using categories c ? JOIN products p ON p.category_id = c.id. INNER JOIN returns only matching pairs: 11 rows, such as Coffee with its 3 products and Tea with its 4. LEFT JOIN adds unmatched left rows: 12 rows, including Accessories with no product. RIGHT JOIN adds unmatched right rows: 12 rows, including the Gift Card with no category. FULL JOIN adds unmatched rows on both sides: 13 rows. Equipment with its 4 products is in every result too. Missing sides are filled with NULLs. LEFT JOIN is the common one; RIGHT JOIN equals LEFT JOIN with the tables swapped. Find rows with no match, an anti-join, with LEFT JOIN … WHERE right_table.id IS NULL.

LEFT JOIN

LEFT JOIN (or LEFT OUTER JOIN — OUTER is optional) returns every row from the left table — the one in FROM — plus matching rows from the right. When a left row has no match, it still appears once, with NULLs in the right table’s columns.

Every category with its products:

SQL
SELECT c.name AS category, p.name AS product
FROM categories AS c
LEFT JOIN products AS p ON p.category_id = c.id
ORDER BY c.name, p.name;
Text
  category   |        product         
-------------+------------------------
 Accessories | 
 Coffee      | Colombian Supremo
 Coffee      | Decaf House Blend
 Coffee      | Ethiopian Yirgacheffe
 Equipment   | Burr Grinder
 Equipment   | Electric Kettle
 Equipment   | Glass Teapot
 Equipment   | Pour-Over Dripper
 Tea         | Assam Breakfast
 Tea         | Chamomile Calm
 Tea         | Darjeeling First Flush
 Tea         | Jasmine Green
(12 rows)

Twelve rows: the eleven matches, plus Accessories with an empty product. An inner join would have dropped it.

“Left” and “right” just mean the order you wrote the tables in: the table before LEFT JOIN is kept in full.

Counting with zeros

How many products does each category have — including those with none?

SQL
SELECT c.name AS category,
       count(p.id) AS products,
       count(*)    AS wrong_count
FROM categories AS c
LEFT JOIN products AS p ON p.category_id = c.id
GROUP BY c.name
ORDER BY c.name;
Text
  category   | products | wrong_count 
-------------+----------+-------------
 Accessories |        0 |           1
 Coffee      |        3 |           3
 Equipment   |        4 |           4
 Tea         |        4 |           4
(4 rows)

count(p.id) counts non-NULL product ids, so Accessories correctly gets 0. count(*) counts rows, and the outer join produced one row for Accessories (with NULLs), so it says 1. With outer joins, count a column from the right-hand table.

The same idea gives every customer’s number of orders, including the ones who haven’t ordered yet:

SQL
SELECT c.first_name,
       count(o.id) AS orders,
       COALESCE(sum(o.shipping_fee), 0) AS shipping_paid
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.first_name
ORDER BY orders DESC, c.first_name;
Text
 first_name | orders | shipping_paid 
------------+--------+---------------
 Asha       |      5 |          4.99
 Ben        |      4 |         26.00
 Chen       |      3 |         24.00
 Dee        |      3 |         28.50
 Farhan     |      3 |         14.97
 Elena      |      2 |         14.50
 Grace      |      2 |         11.98
 Hugo       |      2 |         14.50
 Isha       |      0 |             0
 Jack       |      0 |             0
(10 rows)

sum over no rows is NULL, so COALESCE(…, 0) turns it into a proper zero for Isha and Jack. Grouping by c.id as well as the name keeps two customers who happened to share a first name apart.

Finding what’s missing: the anti-join

Rows on the left with no match have NULL in every right-hand column — including the right table’s primary key, which can never be NULL in a real row. So filtering on right.id IS NULL keeps exactly the unmatched rows:

SQL
SELECT c.first_name, c.signup_date
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.id IS NULL
ORDER BY c.first_name;
Text
 first_name | signup_date 
------------+-------------
 Isha       | 2026-07-01
 Jack       | 2026-09-15
(2 rows)

Customers who’ve never ordered — a great list for a welcome-discount email. And products that have never sold:

SQL
SELECT p.name, p.stock
FROM products AS p
LEFT JOIN order_items AS oi ON oi.product_id = p.id
WHERE oi.product_id IS NULL;
Text
     name     | stock 
--------------+-------
 Glass Teapot |     0
(1 row)

This pattern is called an anti-join. You’ll meet a second way to write it, NOT EXISTS, in chapter 6.

The WHERE trap

This is the most common outer-join bug. You want every customer with their number of pending orders — zero for those with none. So you add a filter:

SQL
SELECT c.first_name, count(o.id) AS pending_orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'pending'
GROUP BY c.id, c.first_name
ORDER BY c.first_name;
Text
 first_name | pending_orders 
------------+----------------
 Asha       |              1
 Dee        |              1
(2 rows)

Only two customers came back — where did the zeros go? Follow the logical order: the LEFT JOIN produced rows for everyone (with NULL status for Isha and Jack). Then WHERE o.status = 'pending' ran on those rows, and NULL = 'pending' isn’t true, so every customer without a pending order was thrown away. The WHERE turned the outer join into an inner one.

The fix is to put conditions on the right-hand table in the ON clause, so they decide what matches rather than what survives:

SQL
SELECT c.first_name, count(o.id) AS pending_orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
                     AND o.status = 'pending'
GROUP BY c.id, c.first_name
ORDER BY c.first_name;
Text
 first_name | pending_orders 
------------+----------------
 Asha       |              1
 Ben        |              0
 Chen       |              0
 Dee        |              1
 Elena      |              0
 Farhan     |              0
 Grace      |              0
 Hugo       |              0
 Isha       |              0
 Jack       |              0
(10 rows)

Everyone is back, with zeros where they belong. The rule:

  • Conditions on the left (preserved) table → WHERE.
  • Conditions on the right (optional) table → ON.
  • The one exception is the anti-join’s WHERE right.id IS NULL, which deliberately tests the outer-join NULLs.

RIGHT JOIN

RIGHT JOIN is the mirror image: it keeps every row of the right table. Products with their category, keeping products that have none:

SQL
SELECT c.name AS category, p.name AS product
FROM categories AS c
RIGHT JOIN products AS p ON p.category_id = c.id
WHERE c.id IS NULL OR c.id = 3
ORDER BY p.name;
Text
 category  |      product      
-----------+-------------------
 Equipment | Burr Grinder
 Equipment | Electric Kettle
           | Gift Card
 Equipment | Glass Teapot
 Equipment | Pour-Over Dripper
(5 rows)

Any RIGHT JOIN can be written as a LEFT JOIN by swapping the tables (FROM products LEFT JOIN categories), and most people find that easier to read — start from the table you want to keep. You’ll rarely write RIGHT JOIN, but you should recognise it.

FULL JOIN

FULL JOIN keeps unmatched rows from both sides — useful for comparing two lists to see what’s only in one, only in the other, or in both:

SQL
SELECT c.name AS category, p.name AS product
FROM categories AS c
FULL JOIN products AS p ON p.category_id = c.id
WHERE c.id IS NULL OR p.id IS NULL
ORDER BY category, product;
Text
  category   |  product  
-------------+-----------
 Accessories | 
             | Gift Card
(2 rows)

The WHERE keeps just the mismatches: a category with no products, and a product with no category. Reconciling two data sources — “which invoices have no payment, and which payments have no invoice?” — is the classic use.

Reports with every period

Outer joins also fill in gaps in time. GROUP BY can’t produce a month with no orders, but you can generate every month with generate_series and LEFT JOIN the orders to it:

SQL
SELECT m.month::date AS month,
       count(o.id)   AS orders
FROM generate_series(date '2026-06-01', date '2026-12-01', interval '1 month') AS m(month)
LEFT JOIN orders AS o
       ON o.ordered_at >= m.month
      AND o.ordered_at <  m.month + interval '1 month'
GROUP BY m.month
ORDER BY m.month;
Text
   month    | orders 
------------+--------
 2026-06-01 |      2
 2026-07-01 |      1
 2026-08-01 |      1
 2026-09-01 |      2
 2026-10-01 |      2
 2026-11-01 |      3
 2026-12-01 |      0
(7 rows)

December shows up with 0 orders instead of being missing — exactly what a chart needs.

Other databases: LEFT and RIGHT JOIN are universal. FULL JOIN isn’t supported by MySQL (emulate it with a UNION of a left and a right join); SQLite added it in version 3.39.

Exercise

Sales for every product

Write a sales report that includes every product — even ones that have never been ordered. Return each product's name and units_sold (the total quantity across all order items, showing 0 rather than NULL for products never sold), sorted by units sold (most first) and then by name. Start from products and LEFT JOIN order_items. The Glass Teapot should appear at the bottom with 0.

SQL
SELECT p.name
FROM products AS p
ORDER BY p.name;

Summary

  • LEFT JOIN keeps every row of the left table; where there's no match, the right table's columns are NULL.
  • RIGHT JOIN keeps every row of the right table, and FULL JOIN keeps unmatched rows from both sides.
  • LEFT JOIN … WHERE right.id IS NULL finds rows with no match — the anti-join pattern.
  • Conditions on the right-hand table belong in ON; putting them in WHERE throws away the NULL rows and turns the join back into an inner join.
  • With outer joins, count(right.id) counts real matches (giving 0), whereas count(*) would count the NULL row as 1.