Sub topic 2
The Idea Behind Outer Joins: Preserving Rows
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query. It also assumes you know what primary and foreign keys are, how NULL behaves in comparisons, and how to write an INNER JOIN ... ON. Here you build the mental model that the next chapters use for LEFT, RIGHT and FULL joins. You will not memorize syntax yet. The goal is to be able to predict which rows survive a join before you run it.
What an inner join drops
The sample data used throughout this tutorial has one customer with no orders and one order with 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);An inner join keeps a row only when the ON condition is true for a pair of rows, one from each table.
SELECT c.name, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00Two rows are missing from the result:
- Cleo has no order, so no pair involving Cleo satisfies the condition.
- Order 104 has a
NULLcustomer. The comparisonNULL = 1evaluates to unknown, not true, so it never matches any customer. The same is true ofNULL = NULL.
An inner join silently discards both rows. That is correct when you only want matched data. It is wrong when the question is "show me every customer, and their orders if they have any." If you answer that question with an inner join, customers without orders vanish, and nothing in the output tells you they were there.
Preserved and unpreserved sides
An outer join adds one rule to the inner join: every row from a chosen table must appear in the result at least once, whether or not it found a match.
The table whose rows are guaranteed to appear is the preserved side. The other table is the unpreserved side (some books call it the null-supplying side). Rows on the unpreserved side appear only when they match.
| Join type | Preserved side | Unpreserved side |
|---|---|---|
| `INNER JOIN` | none | both tables |
| `LEFT OUTER JOIN` | the table written before `JOIN` | the table written after `JOIN` |
| `RIGHT OUTER JOIN` | the table written after `JOIN` | the table written before `JOIN` |
| `FULL OUTER JOIN` | both tables | none |
"Left" and "right" refer only to the position of the table in the query text. They say nothing about which table is bigger, which holds the foreign key, or which is the parent.
When you design an outer join, ask: which table's rows must never disappear? That table is the preserved side. Everything else follows from that choice.
How the engine thinks about it
You can describe any outer join in two steps. Real engines may execute it differently, but the result is the same.
- Compute the inner join: every pair of rows where
ONis true. - For each preserved-side row that appears in no pair, add one extra row. It carries the preserved row's values, with
NULLin every column from the unpreserved table.
You can write this out literally as SQL. The query below builds a left join by hand: the inner join, plus one padded row for each customer who has no orders.
SELECT c.name, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id
UNION ALL
SELECT c.name, NULL, NULL
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- Cleo NULL NULLThe LEFT JOIN keyword does the same thing in one clause:
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- Cleo NULL NULLThe next chapter covers LEFT JOIN syntax in detail. For now, notice what changed compared with the inner join: only Cleo's row was added.
What the ON clause does and does not do
In an inner join, ON decides which rows survive. In an outer join, ON decides only which rows match. It has no power to remove a preserved-side row.
Suppose you tighten the match condition so that only orders over 30 count:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 30;
-- Ada 101
-- Ben 103
-- Cleo NULLAda's order 102 (total 20.00) no longer matches, but Ada still appears because order 101 matches. Had Ada had only small orders, she would still appear, with NULL in order_id. The preserved side always wins over ON. A later chapter compares this behavior with a WHERE filter, which does remove rows. Keep this rule in mind: ON shapes matching, and the preserved side guarantees survival.
Matching is not the same as being related
An outer join cannot tell the difference between "no related row exists" and "a related row exists but my condition didn't match it." Both produce the same padded row. In the example above, Cleo has no orders at all. A customer whose only orders were under 30 would look identical in the output.
The same applies to NULL keys. Order 104 has no customer, so it can never match. If orders were the preserved side, order 104 would appear with NULL in the customer columns. The NULL there comes from the join's padding, but the missing key was already NULL in the data. Later chapters show how to tell these cases apart.
One-sided and two-sided preservation
A LEFT JOIN preserves one side. To keep unmatched rows from the other table instead, you can swap the table order or use RIGHT JOIN. If you need unmatched rows from both tables, use FULL OUTER JOIN. On the sample data, the full join keeps both Cleo and order 104:
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 104Row order is not guaranteed without an ORDER BY. Not every database supports FULL OUTER JOIN, and a later chapter covers a workaround.
The OUTER keyword is optional. LEFT JOIN and LEFT OUTER JOIN are the same operation. This tutorial uses the short forms in code and the long forms when naming the concept.
Common errors at this stage
- Choosing the wrong preserved side. If the question is "all customers, with orders if any," customers must be preserved. Writing
FROM orders LEFT JOIN customerspreserves orders instead and drops Cleo. - Expecting one row per preserved row. A preserved row is guaranteed to appear at least once. If it matches several rows, it appears several times. Ada appears twice in the examples above. Later chapters cover the effect this has on counts and sums.
- Using
INNER JOINand then wondering where rows went. If your result has fewer entities than the table you started from, check whether the join type discards unmatched rows. - Assuming
LEFTmeans "the bigger table." It only means the table written first.
Choosing a join type
Decide using the question you are answering:
- Do you need only the pairs that relate? Use
INNER JOIN. - Do you need every row of table A, plus related rows from B when they exist? Preserve A.
- Do you need every row of both, matched where possible? Use
FULL OUTER JOIN.
If you are unsure, count the entities you expect in the output. If "every customer" must be visible, the customers table must be on the preserved side.
Exercise
Using the sample data, you write SELECT c.name, o.order_id FROM orders o LEFT JOIN customers c ON o.customer_id = c.customer_id;. Which table is preserved, and which rows appear in the result? Is Cleo among them?
Show answer
The orders table is preserved because it is written before LEFT JOIN. All four orders appear: Ada with 101, Ada with 102, Ben with 103, and NULL with 104, because order 104 has a NULL customer_id and cannot match. Cleo does not appear. She is on the unpreserved side and matches no order, so there is no row for her.
Exercise
A query uses customers c LEFT JOIN orders o ON o.customer_id = c.customer_id AND o.total > 100. No order exceeds 100. How many rows does the query return, and what do the order columns contain?
Show answer
Three rows, one per customer (Ada, Ben, Cleo). Each has NULL in the order columns. The ON condition limits which orders match, but no order satisfies it. Every customer is on the preserved side, so each still appears once with NULL padding.