Sub topic 1
Starting point: what an inner join drops
An inner join answers the question "which rows have a partner on the other side?" Rows without a partner are removed from the result. This chapter shows exactly which rows disappear, why they disappear, and how to notice when the loss matters. Every later chapter in this tutorial builds on that gap.
Prerequisites
This chapter assumes you can already do the following:
- Write a basic
SELECT ... FROM ... WHEREquery. - Explain what a primary key and a foreign key are, and read a
CREATE TABLEstatement that declares them. - State what
NULLmeans in SQL: an unknown or missing value, not zero and not an empty string. - Write an
INNER JOINwith anONcondition that matches a foreign key to a primary key.
You do not need any knowledge of outer joins. You can run the examples on PostgreSQL, MySQL, SQLite or SQL Server. Nothing in this chapter depends on vendor-specific syntax.
The sample data
The whole tutorial uses two small tables. The data is chosen so that each kind of join gives a different answer.
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);Two rows are special:
- Cleo (customer 3) exists in
customers, but no row inorderspoints to her. - Order 104 exists in
orders, but itscustomer_idisNULL, so it points to no customer. The foreign key allows this becausecustomer_idinordersis nullable. A foreign key only checks non-NULL values.
Here are the two tables side by side.
| customer_id | name |
|---|---|
| 1 | Ada |
| 2 | Ben |
| 3 | Cleo |
| order_id | customer_id | total |
|---|---|---|
| 101 | 1 | 50.00 |
| 102 | 1 | 20.00 |
| 103 | 2 | 35.00 |
| 104 | NULL | 15.00 |
The inner join result
Join the tables on the key and list every pair that matches.
SELECT c.name, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;The result has three rows:
| name | order_id | total |
|---|---|---|
| Ada | 101 | 50.00 |
| Ada | 102 | 20.00 |
| Ben | 103 | 35.00 |
Four orders and three customers went in. Neither Cleo nor order 104 appears in the output. The database did not raise an error or a warning. The query succeeded and returned fewer rows than a reader might expect.
How the join decides what to keep
Conceptually, an inner join considers every pairing of one row from the left table with one row from the right table. It keeps a pair only when the ON condition is true. A row that never forms a true pair has no representation in the output.
For Cleo, the condition o.customer_id = c.customer_id becomes 1 = 3, 1 = 3, 2 = 3 and NULL = 3 against the four orders. None of these is true, so she contributes nothing.
For order 104, the condition compares NULL with 1, 2 and 3. Any comparison with NULL evaluates to unknown, not true. Only true passes the ON condition, so unknown is treated like false. You can check this directly:
SELECT CASE WHEN NULL = NULL THEN 'true' ELSE 'not true' END AS result;
-- not trueEven two NULL values do not match each other. That is why a NULL foreign key never joins to anything, whatever is in the other table.
Real database engines do not build every pairing. They use indexes, hash tables or sorted merges to find matches efficiently. The result is the same as the pairing description, and that is what you should reason with.
Two kinds of loss
The example shows two separate ways rows are dropped. They look similar in the output but have different causes in the data.
- A parent without children. Cleo is a customer with zero orders. This is normal data. Many customers sign up and never buy anything.
- A child without a parent. Order 104 has no customer. This happens when the foreign key column is nullable, for example for guest checkouts, or when a link was cleared after the fact. If the column were declared
NOT NULLwith a foreign key, this state could not exist.
Whether you care about each loss depends on the question being asked. If you are asked to "list each order with its customer's name", dropping order 104 might hide a data problem. If you are asked to "list customers who have bought something", dropping Cleo is exactly right.
Why this matters in practice
An inner join is a filter as well as a way to combine columns. The filter effect is easy to miss because it is implicit. Three situations show where it causes trouble.
Reports that are supposed to list everything. A report of "all customers and their spending" built on an inner join silently omits customers who have not spent anything. The report looks complete and has no errors.
Totals that do not reconcile. Suppose the finance team sums total across all orders and gets 120.00. You sum it through the inner join and get 105.00. The difference is order 104.
SELECT SUM(total) AS all_orders FROM orders;
-- 120.00
SELECT SUM(o.total) AS joined_orders
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;
-- 105.00Counts that are too low. Counting customers through the join gives 2, not 3.
SELECT COUNT(DISTINCT c.customer_id) AS customers_with_orders
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;
-- 2The query is correct for "customers with orders". It is wrong for "how many customers do we have". The SQL gives no hint of which question you meant to ask.
A quick check for dropped rows
A simple habit catches most problems. Count the rows on each side, then count the distinct keys that survive the join.
SELECT
(SELECT COUNT(*) FROM customers) AS customer_rows,
(SELECT COUNT(*) FROM orders) AS order_rows,
(SELECT COUNT(*)
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id) AS joined_rows;
-- customer_rows: 3, order_rows: 4, joined_rows: 3Here joined_rows equals customer_rows by coincidence, since Ada's two orders and Cleo's missing orders balance out. That is the second trap: the join row count tells you little by itself. A row count that matches the left table does not prove every left row survived. To find out which rows are missing, look at the keys, not just the totals.
You can list the unmatched parent rows without outer joins by using a subquery:
SELECT c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id FROM orders o WHERE o.customer_id IS NOT NULL
);
-- CleoThe IS NOT NULL filter inside the subquery is required. Without it, the NULL from order 104 makes NOT IN return no rows at all, because x NOT IN (..., NULL) is never true. A later chapter returns to this problem and compares it with other ways to find unmatched rows. For now, treat it as a sign that NULL behaves differently from ordinary values everywhere in SQL, and joins are no exception.
What outer joins add
Outer joins let you say, "keep the rows from this side even when no partner exists." The next chapters build that idea in steps:
| Join type | Keeps unmatched rows from |
|---|---|
| INNER JOIN | Neither table |
| LEFT OUTER JOIN | The left table |
| RIGHT OUTER JOIN | The right table |
| FULL OUTER JOIN | Both tables |
For the sample data, the four join types give different answers because of Cleo and order 104. Inner join omits both. A left join from customers to orders keeps Cleo. A right join keeps order 104. A full join keeps both.
The rows that outer joins preserve have no partner, so the columns that would have come from the other table must be filled with something. SQL fills them with NULL. Reading those NULL values correctly is the subject of a later chapter, and it is also the source of many bugs.
Common mistakes with inner joins
- Treating the join as a pure lookup. Joining to add a column is fine only when every row has a match, or when dropping unmatched rows is intended.
- Forgetting nullable foreign keys. A foreign key constraint does not stop the column from holding
NULL. Check whether the column isNOT NULLbefore you assume every child row has a parent. - Comparing counts without thinking about row multiplication. A customer with several orders appears several times in the joined result, so
COUNT(*)counts orders, not customers. UseCOUNT(DISTINCT ...)when you want the number of distinct entities. - Using
INNER JOINby default. It is the usual join in examples, but the choice should follow the question you are answering.
Exercise
Using the sample data, an analyst runs an inner join from customers to orders and reports "2 customers placed orders, so we have 2 customers." Name the two rows that the join dropped from the full data and give a reason for each.
Show answer
Cleo (customer 3) was dropped because no order has customerid 3, so the ON condition is never true for her. Order 104 was dropped because its customerid is NULL, and NULL = 1, NULL = 2 and NULL = 3 are all unknown, not true. The analyst's conclusion is also wrong: there are 3 customers, and only 2 of them have orders.
Exercise
The query SELECT SUM(o.total) FROM customers c INNER JOIN orders o ON o.customerid = c.customerid returns 105.00, but SELECT SUM(total) FROM orders returns 120.00. Which order explains the 15.00 difference, and why is it missing from the first result?
Show answer
Order 104. Its customer_id is NULL, so it never satisfies the join condition and is dropped. The second query reads the orders table directly and has no join, so it includes order 104.
Exercise
Can two NULL values in the join columns match each other in an ON condition such as a.x = b.x? Explain what happens to those rows in an inner join.
Show answer
No. NULL = NULL evaluates to unknown, and the ON condition only keeps pairs for which it is true. Rows with NULL in the join column are dropped from an inner join, even if the other table also has NULL in its column.