Sub topic 8
FULL OUTER JOIN
This chapter assumes you can write SELECT ... WHERE queries and INNER JOIN ... ON. It also assumes you know how LEFT JOIN pads unmatched rows with NULL, and why a WHERE filter on the right table can undo a left join. Here you will see what happens when both sides of a join are preserved.
What a FULL OUTER JOIN returns
A LEFT JOIN preserves every row of the left table. A RIGHT JOIN preserves every row of the right table. A FULL OUTER JOIN preserves both. Its result is the union of three groups of rows:
- Matched rows, the same ones an inner join returns.
- Left rows with no match, with the right table's columns set to
NULL. - Right rows with no match, with the left table's columns set to
NULL.
OUTER is optional. FULL JOIN and FULL OUTER JOIN mean the same thing.
The sample data
The examples use the same tables as the earlier chapters. Cleo has no orders, and order 104 has no customer.
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT REFERENCES customers (customer_id),
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cleo');
INSERT INTO orders (order_id, customer_id, total) VALUES
(101, 1, 50.00),
(102, 1, 20.00),
(103, 2, 35.00),
(104, NULL, 15.00);A first FULL OUTER JOIN
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101
-- Ada 102
-- Ben 103
-- Cleo NULL
-- NULL 104Ada and Ben appear once per matching order. Cleo appears once with NULL in the order column, as she would in a left join. Order 104 appears once with NULL in the customer column, as it would in a right join.
Order 104 is unmatched because its customer_id is NULL. The condition o.customer_id = c.customer_id evaluates to unknown when either side is NULL, and unknown is never true. A NULL key therefore never matches anything, not even another NULL.
SQL does not guarantee the order of these rows. Add ORDER BY if you need a stable order.
Telling the three kinds of row apart
Every row in a full join result is matched, left-only, or right-only. You can't tell which by looking for any NULL, because a matched row can still contain a NULL from a nullable column. Test a column that can't be NULL in its own table, such as a primary key:
SELECT c.name,
o.order_id,
CASE
WHEN o.order_id IS NULL THEN 'customer without orders'
WHEN c.customer_id IS NULL THEN 'order without customer'
ELSE 'matched'
END AS status
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 matched
-- Ada 102 matched
-- Ben 103 matched
-- Cleo NULL customer without orders
-- NULL 104 order without customerDon't test o.customer_id IS NULL for this. Order 104 has a genuinely NULL customer_id, so that test would flag a row that exists in orders. o.order_id is the primary key, so it is NULL only when the join padded it.
Finding mismatches on either side
A LEFT JOIN ... WHERE o.order_id IS NULL finds left rows with no match. The full-join version finds unmatched rows on both sides in one query:
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL OR o.order_id IS NULL;
-- Cleo NULL
-- NULL 104This is the main use of a full join: comparing two sets of rows and seeing what is missing from each. Typical cases are reconciling an invoice table against a payments table, or checking a staging table against production. If you only care about one direction, a LEFT JOIN or NOT EXISTS states that more clearly.
Filtering in ON versus WHERE
The rule from the left join chapter still applies, with a bigger effect. WHERE runs after the join, so any condition on a column from either table discards the NULL-padded rows on the opposite side.
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 30;
-- Ada 101
-- Ben 103Cleo's padded row has o.total equal to NULL, so the comparison is unknown and the row is dropped. The query ends up behaving like an inner join. Order 104 also fails, because its total is 15.00.
Moving the condition into ON does something different:
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 30;
-- Ada 101
-- Ben 103
-- Cleo NULL
-- NULL 102
-- NULL 104In a left join, a condition in ON only decides which right rows can match, and the left rows stay. In a full join this applies to both tables, so orders that fail the condition are not discarded. Order 102 belongs to Ada, but at 20.00 it fails o.total > 30, so it no longer matches Ada. It becomes an unmatched order and appears with a NULL name. Ada appears only for order 101.
You can read this as: "pair customers with orders only when the order is over 30, but keep every row from both tables regardless."
Pre-filtering is usually the clearest way to express "full join only the large orders":
WITH big_orders AS (
SELECT order_id, customer_id, total
FROM orders
WHERE total > 30
)
SELECT c.name, b.order_id
FROM customers c
FULL OUTER JOIN big_orders b ON b.customer_id = c.customer_id;
-- Ada 101
-- Ben 103
-- Cleo NULLOrders 102 and 104 are gone because they were removed before the join.
Aggregating over a full join
Counting and summing follow the left join rules: use a column from the table that can be padded, and use COALESCE for sums. A full join adds one more case. The unmatched orders land in a group where the customer columns are NULL.
SELECT COALESCE(c.name, '(no customer)') AS customer,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total), 0) AS total_spent
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;
-- Ada 2 70.00
-- Ben 1 35.00
-- Cleo 0 0
-- (no customer) 1 15.00GROUP BY treats all NULLs as one group, so every unmatched order falls into a single (no customer) row. That row's total is useful for reconciliation. The per-customer totals plus the orphan row add up to 120.00, the sum of the whole orders table. A plain inner join would silently lose the 15.00.
COUNT(o.order_id) counts only real orders, so Cleo gets 0. COUNT(*) would count her padded row and report 1.
If you group by a column that comes from only one side, such as c.name, remember that unmatched rows from the other side all collapse into a NULL group. When both tables carry the key, group by COALESCE(c.customer_id, o.customer_id) to keep a single key column.
Merging the key column with USING
When both tables name the join column identically, USING (customer_id) replaces ON and produces one merged customer_id column. In a full join, that column holds the left value if the left row exists and the right value otherwise, which is what COALESCE(c.customer_id, o.customer_id) would give. USING is convenient for comparing two tables with the same key. Support differs between databases, and the ON form is the portable one. This chapter uses ON throughout.
Database support and limits
| Database | FULL OUTER JOIN |
|---|---|
| PostgreSQL | Supported |
| SQL Server | Supported |
| Oracle | Supported |
| SQLite | Supported from version 3.39.0 |
| MySQL, MariaDB | Not supported |
On MySQL and MariaDB, you build the result from a LEFT JOIN plus the unmatched rows of a RIGHT JOIN, combined with UNION ALL. A later chapter covers this emulation in detail.
Common mistakes
- Using a full join when a left join would do. If you only need unmatched rows from one table, a full join adds rows you then have to filter out.
- Testing the wrong column for padding. Test a non-nullable column from the table you suspect is missing. Don't test a foreign key that is itself nullable.
- Expecting
NULLkeys to match. Rows with aNULLjoin key always show up as unmatched on both sides, even if both tables containNULLkeys. - Putting a table condition in
WHERE. It turns the full join into a left, right or inner join without any warning. - Relying on row order. The order of a full join result is unspecified.
Exercise
Using the sample data, write a query that returns each customer name and order total for customers with no orders and for orders with no customer, and nothing else. Then say what it returns.
Show answer
SELECT c.name, o.total FROM customers c FULL OUTER JOIN orders o ON o.customerid = c.customerid WHERE c.customerid IS NULL OR o.orderid IS NULL; It returns two rows: (Cleo, NULL) for the customer with no orders, and (NULL, 15.00) for order 104, which has no customer. The WHERE tests use primary keys, which are NULL only when the join padded the row.
Exercise
In the query below, why does the result include a row with a NULL name for order 102, even though order 102 belongs to Ada? How would you change the query so order 102 does not appear at all? SELECT c.name, o.orderid FROM customers c FULL OUTER JOIN orders o ON o.customerid = c.customer_id AND o.total > 30;
Show answer
Order 102 totals 20.00, so it fails the o.total > 30 condition in ON and cannot match Ada. A full join preserves every order, so 102 is returned as an unmatched order with NULL customer columns. To remove it, filter before the join, for example by joining against a CTE or subquery that selects only orders with total > 30, or add a WHERE clause that removes it after the join (accepting that WHERE also removes padded rows whose o.total is NULL).
Exercise
A query uses FULL OUTER JOIN, then GROUP BY c.name with COUNT(*). Cleo shows a count of 1 although she has no orders. What is wrong, and what is the fix?
Show answer
COUNT(*) counts the NULL-padded row that the join produces for Cleo. Count a non-nullable column from the orders table instead, such as COUNT(o.order_id), which ignores NULLs and returns 0 for Cleo.