Sub topic 12
Row growth, indexes, and checking your results
This chapter assumes you can write INNER JOIN and LEFT JOIN with an ON condition, and that you know primary keys, foreign keys, NULL handling, and GROUP BY with SUM. It builds on the employees table and the sizes, colors, stores, products, and sales tables from earlier chapters. Self joins and cross joins are easy to write and easy to get wrong without noticing. You will learn to predict how many rows a join returns, which indexes help, and how to confirm that the result matches what you expected.
Predicting row counts before you run the query
A join's output size follows from its inputs. If you can state the expected number first, a wrong result stands out.
| Join shape | Expected rows | Sample data |
|---|---|---|
| `CROSS JOIN` of A and B | rows(A) × rows(B) | 3 sizes × 2 colors = 6 |
| Cross join of a table with itself | n² | 4 employees → 16 |
| Self join with `a.id < b.id` and no other condition | n × (n − 1) / 2 | 4 employees → 6 |
| `LEFT JOIN` to a parent by a unique key | rows of the left table, exactly | 4 employees → 4 |
| `INNER JOIN` to a parent by a unique key | rows of the left table that have a parent | 4 employees → 3 |
The last two rows work because employees.id is a primary key. Each employee row matches at most one manager row, so the join cannot add rows. If the join column on the right side is not unique, each left row matches several right rows and the result grows. This is called fan-out.
How fast the numbers grow
The cost of a cross join grows with the product of its inputs, not their sum. A small increase in either table produces a large increase in output.
| Left rows | Right rows | Cross join rows |
|---|---|---|
| 3 | 2 | 6 |
| 100 | 100 | 10,000 |
| 10,000 | 10,000 | 100,000,000 |
| 1,000,000 | 1,000 | 1,000,000,000 |
Pair comparison within a single table grows quadratically as well. A self join with a.id < b.id and no other condition returns n × (n − 1) / 2 rows.
| Table rows (n) | Pairs returned |
|---|---|
| 4 | 6 |
| 1,000 | 499,500 |
| 100,000 | 4,999,950,000 |
A query that runs instantly on your 4-row test table can run for hours on a production table. Test data hides this problem, so do the arithmetic before you run the query against real data.
What each pair condition does to the count
The pair query from earlier in the chapter joined employees who share a manager. These variants show how each condition changes the result on the sample data.
| Condition added to `a.manager_id = b.manager_id` | Rows | What you get |
|---|---|---|
| none | 5 | Self-pairs such as (Ben, Ben), and both (Ben, Chen) and (Chen, Ben) |
| `a.id <> b.id` | 2 | No self-pairs, but both orderings of the same pair |
| `a.id < b.id` | 1 | Each pair once |
Ava has a NULL manager_id. The comparison NULL = NULL is not true in SQL, so she never matches anyone, not even herself. Dana is the only employee managed by Ben, so she matches only herself, and the < condition removes that pair.
Indexes: what helps and what does not
An index is a separate, sorted structure that lets the database find matching rows without reading the whole table. For a join, the database needs a fast way to find the rows on one side that match each row on the other.
Self joins on a parent key
In e.manager_id = m.id, the lookup on m uses id, which is the primary key and already indexed. The reverse direction is different. Finding everyone who reports to a given manager searches manager_id, which has no index by default. Most databases do not create an index for a foreign key automatically. PostgreSQL and SQL Server do not, while MySQL's InnoDB engine does.
CREATE INDEX idx_employees_manager_id ON employees (manager_id);With this index, queries such as WHERE manager_id = 1, and joins that start from the manager and look for reports, avoid scanning the whole table.
Gap-filling reports
In the store and product report, the LEFT JOIN to sales matches on two columns. A composite index on both columns serves that lookup.
CREATE INDEX idx_sales_store_product ON sales (store_id, product_id);The cross join part of that query gets no help from an index. A cross join has no condition to look up, so the database must produce every combination. An index only reduces the cost of the LEFT JOIN that follows.
Inequality conditions
A condition such as a.id < b.id is a range, not an equality. Databases handle range joins less efficiently than equality joins, and many fall back to comparing rows pair by pair. When the equality part is present, as in a.manager_id = b.manager_id, the database can use it to narrow candidates first and apply the < check afterward. Put an equality condition in the pair join whenever your question allows one.
Reading the query plan
Most databases show how they intend to run a query. In PostgreSQL and MySQL the command is EXPLAIN.
EXPLAIN
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;Plan output differs between systems, so read it for these signs rather than exact wording:
- A full table scan on a large table that should be looked up by key means a missing or unusable index.
- A nested loop whose inner side is scanned repeatedly means the work is multiplied by the outer row count. That is expected for a cross join and a warning sign for anything else.
- An estimated row count far larger than your prediction means the join condition is missing or too loose.
On a 4-row table the planner will usually choose a full scan even when an index exists, because scanning four rows is cheaper than using an index. Compare plans on realistic data volumes.
Checking your results
Treat every join query as a claim: "this returns one row per X". Verify the claim with a few cheap checks.
Compare counts
For a LEFT self join, the result must have exactly as many rows as the employees table. If it has more, some manager key is duplicated.
SELECT
(SELECT COUNT(*) FROM employees) AS employee_rows,
(SELECT COUNT(*)
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id) AS joined_rows;On the sample data both columns show 4. In a real table, joined_rows larger than employee_rows means fan-out.
Check the cross join total
For the gap-filling report, the result should contain exactly one row per store and product pair, including pairs with zero sales.
SELECT
(SELECT COUNT(*) FROM stores) * (SELECT COUNT(*) FROM products) AS expected_rows,
COUNT(*) AS actual_rows
FROM (
SELECT st.store_name, p.product_name,
COALESCE(SUM(s.quantity), 0) AS total_quantity
FROM stores st
CROSS JOIN products p
LEFT JOIN sales s
ON s.store_id = st.id
AND s.product_id = p.id
GROUP BY st.id, st.store_name, p.id, p.product_name
) AS report;If the two numbers differ, check the GROUP BY. It must include the id of each side so that each pair becomes one group.
Look at a small slice first
When you write a join against a large table, filter each side before joining, or limit the result while you develop.
SELECT a.name AS first_employee, b.name AS second_employee
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id
AND a.id < b.id
ORDER BY a.id, b.id
LIMIT 20;LIMIT protects you only when the database can stop early. If the query sorts or aggregates the whole result first, as ORDER BY on an unindexed column or GROUP BY does, the full join still runs before the limit applies. For a real safeguard, put the filter in a WHERE clause on each input so that the joined sets are small.
Count before you select
When you are unsure about a join, replace the select list with COUNT(*) and compare the count to your prediction. Counting is cheap compared with returning and displaying millions of rows.
Common mistakes
- Trusting a small test table. The sample
employeestable has 4 rows, so even a broken self join finishes instantly. Estimate the size on production data. - Forgetting that NULL never matches. An INNER self join silently drops the top of the hierarchy. If your count is lower than expected, look for NULL keys.
- Indexing the wrong column. An index on
employees.namedoes nothing for a join onmanager_id. Index the columns that appear inON. - Expecting an index to speed up a cross join. The cost is the number of output rows. Reduce the inputs with filters instead.
- Aggregating after fan-out. Joining a table to a non-unique key and then using
SUMcounts the same value several times. Compare counts before and after each join.
Exercise
A table employees has 2,000 rows. You run a self join with ON a.id < b.id and no other condition. How many rows do you expect, and what do you expect if you remove the < condition entirely and use CROSS JOIN?
Show answer
With a.id < b.id you expect 2,000 × 1,999 / 2 = 1,999,000 rows. A plain cross join of the table with itself returns 2,000 × 2,000 = 4,000,000 rows, which includes self-pairs and both orderings of every pair.
Exercise
You run a LEFT self join on employees e LEFT JOIN employees m ON e.manager_id = m.id. The table has 500 rows but the result has 530. What does that tell you, and which query would you run to find the cause?
Show answer
A LEFT join on a parent key should return exactly one row per left row, so the extra rows mean some m.id values match more than once. Either id is not unique in this table (for example, the primary key constraint is missing) or the join has another condition that fans out. Run SELECT id, COUNT(*) FROM employees GROUP BY id HAVING COUNT(*) > 1; to find the duplicated ids.
Exercise
Why does an index on sales (store_id, product_id) speed up the gap-filling report, even though the report starts with a CROSS JOIN?
Show answer
The index serves the LEFT JOIN, not the cross join. For each store and product pair produced by the cross join, the database looks up matching sales rows by both columns, and the composite index finds them without scanning the whole sales table. The cross join itself still produces every pair, so the number of lookups equals the number of stores times the number of products.