Sub topic 5
RIGHT OUTER JOIN and why it mirrors LEFT
This chapter assumes you can write a LEFT JOIN, you understand NULL padding, and you know the difference between a filter in ON and one in WHERE. Earlier chapters covered these. Here we show that RIGHT JOIN is the same operation with the tables swapped, and we cover the few cases where the difference matters.
The rule: RIGHT preserves the table written after JOIN
An outer join has a preserved side and an unpreserved side. The preserved side keeps every row, whether or not it matches. The unpreserved side contributes columns only when a match exists, and otherwise supplies NULLs.
LEFT JOINpreserves the table written before theJOINkeyword.RIGHT JOINpreserves the table written after it.
We use the same data as the rest of the tutorial. 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);Here is a RIGHT JOIN with orders as the preserved side:
SELECT c.name, o.order_id, o.total
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.customer_id
ORDER BY o.order_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- NULL 104 15.00Every order appears. Order 104 has no customer, so c.name is NULL. Cleo is missing because customers is the unpreserved side, and no order points to her.
The same data with a LEFT JOIN would keep Cleo and show no row for order 104, because the preserved side would be customers. Moving the keyword changes which table is protected.
RIGHT is LEFT with the tables swapped
Any RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the table order. The ON condition stays as it is, because equality is symmetric.
-- Same result as the RIGHT JOIN above
SELECT c.name, o.order_id, o.total
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
ORDER BY o.order_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- NULL 104 15.00Both queries return the same four rows. A query planner treats them identically, so you should not expect a performance difference between the two forms.
The following table shows the equivalence:
| You write | Preserved table | Unmatched rows appear for |
|---|---|---|
| `a LEFT JOIN b` | `a` | rows of `a` with no match in `b` |
| `a RIGHT JOIN b` | `b` | rows of `b` with no match in `a` |
| `b LEFT JOIN a` | `b` | rows of `b` with no match in `a` |
Rows 2 and 3 are the same query, written in two ways.
Why most teams write LEFT only
Because the two forms are interchangeable, many style guides ban RIGHT JOIN. The reasons are about reading, not about correctness.
- Queries are easier to read when the main subject is the first table in
FROM. WithLEFT JOIN, you read "start with this, then optionally attach that." - With
RIGHT JOIN, the preserved table sits at the end of the join. A reader has to keep the earlier tables in mind and then notice that they are the optional ones. - In a chain of joins, a single
RIGHT JOINchanges which rows survive in ways that are hard to see (covered below).
A RIGHT JOIN is still worth reading fluently, because you will meet it in existing code and generated SQL. It can also be reasonable when you are adding an outer join to a query whose FROM order you do not want to rearrange.
Finding unmatched rows from the right side
The anti-join pattern you saw with LEFT JOIN also works on a RIGHT JOIN. Filter on a NOT NULL column of the unpreserved table, which here is customers:
SELECT o.order_id, o.total
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL;
-- 104 15.00This returns orders that have no matching customer. Use the primary key of the unpreserved table in the test. A NULL there can only come from padding, since a primary key is never NULL. Testing a column like c.name also works here because it is declared NOT NULL, but the key is the safer habit.
The result contains order 104 because its customer_id is NULL, and NULL never equals anything in an ON condition. The foreign key does not prevent this. A foreign key only checks non-NULL values, so a NULL reference is allowed. If the column were declared NOT NULL, orphaned orders could not exist at all, and this query would return nothing.
ON versus WHERE, mirrored
The ON versus WHERE rule applies with the sides swapped. A WHERE condition on the unpreserved table removes the NULL-padded rows, so the join quietly becomes an inner join.
-- Filter in WHERE: order 104 and Ben's order are removed
SELECT c.name, o.order_id
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.customer_id
WHERE c.name = 'Ada'
ORDER BY o.order_id;
-- Ada 101
-- Ada 102Order 104 has c.name equal to NULL, and NULL = 'Ada' is not true, so WHERE discards it. Ben's order 103 is also discarded because his name is not 'Ada'. Putting the condition in ON limits which customers can match, but keeps every order:
-- Filter in ON: all orders are kept
SELECT c.name, o.order_id
FROM customers c
RIGHT JOIN orders o
ON o.customer_id = c.customer_id AND c.name = 'Ada'
ORDER BY o.order_id;
-- Ada 101
-- Ada 102
-- NULL 103
-- NULL 104Order 103 belongs to Ben, who fails the ON condition, so it is treated as unmatched and padded with NULL.
A filter on the preserved table behaves differently. A WHERE on o.total removes whole orders, which is usually what you intend. A WHERE on the preserved table does not undo the outer join, because those columns are never NULL-padded.
RIGHT JOIN inside a chain
A chain of joins is evaluated from left to right. Each join takes the result of everything written before it as its left input. This is where a RIGHT JOIN gets surprising.
Consider the shape customers JOIN orders RIGHT JOIN payments. The join preserves every payment. A customer with orders but no payments will not appear, because the RIGHT JOIN keeps only the rows connected to payments. If you expected customers to survive, you wanted a LEFT JOIN.
Two habits keep chains readable:
- Put the table you want to preserve first, and use
LEFT JOINfor every optional table after it. - If you need to mix join types, add parentheses or a subquery to make the evaluation order visible.
What each database supports
RIGHT JOIN is part of standard SQL, and PostgreSQL, MySQL, MariaDB, SQL Server and Oracle all support it. SQLite supports it from version 3.39. Older SQLite versions raise a syntax error, and the fix is to swap the tables and use LEFT JOIN.
The keyword OUTER is optional. RIGHT JOIN and RIGHT OUTER JOIN mean the same thing.
The row order of a join result is not guaranteed unless you use ORDER BY. The comments in this chapter's examples show the rows in sorted order for readability, so add an explicit ORDER BY in your own queries when order matters.
Common mistakes
- Preserving the wrong table. Check which table is after the
JOINkeyword before you trust aRIGHT JOIN. Running the query on a small dataset like this one and looking for the expected unmatched row catches this quickly. - Testing a nullable column for the anti-join. If you test
c.name IS NULLandnameis nullable, you cannot tell padding from real NULL data. Test the primary key. - Filtering the unpreserved table in WHERE. This turns the outer join into an inner join, as shown above.
- Mixing LEFT and RIGHT in one chain without checking each step. Work out the preserved side of each join in order.
Practice
Exercise
Using the tables from this chapter, write a query with RIGHT JOIN that lists every order together with its customer name, but where the customer name column shows 'unknown' for orders with no customer. Which table is preserved, and what does the query return for order 104?
Show answer
SELECT COALESCE(c.name, 'unknown') AS customer, o.orderid FROM customers c RIGHT JOIN orders o ON o.customerid = c.customerid ORDER BY o.orderid; The preserved table is orders, because it is written after RIGHT JOIN. Order 104 has a NULL customer_id, so it matches nothing in customers. Its name is NULL-padded, and COALESCE replaces the NULL with 'unknown', giving the row (unknown, 104). Cleo does not appear because customers is the unpreserved side.
Exercise
Rewrite SELECT c.name, o.orderid FROM customers c RIGHT JOIN orders o ON o.customerid = c.customer_id WHERE c.name <> 'Ada' as a LEFT JOIN, and say whether order 104 appears in the result.
Show answer
SELECT c.name, o.orderid FROM orders o LEFT JOIN customers c ON o.customerid = c.customer_id WHERE c.name <> 'Ada'; Swap the table order and keep the ON condition and the WHERE clause. Order 104 does not appear. Its c.name is NULL, and NULL <> 'Ada' evaluates to unknown, not true, so WHERE removes the row. Only Ben's order 103 is returned. To keep order 104, test for NULL explicitly with OR c.name IS NULL, or move the condition into ON.