Sub topic 16
Join performance: indexes and execution plans
This chapter assumes you can write an INNER JOIN with an ON condition, chain several tables, and use WHERE and GROUP BY on joined rows. It also assumes you know what primary keys and foreign keys are. Here you will learn why a join can be fast or slow, how indexes help, and how to read an execution plan to check what the database actually does.
What the database does when it joins
The SQL you write describes the result you want. It does not say how to compute it. The database's query planner chooses a strategy, and for joins there are three common ones.
| Strategy | How it works | Typically chosen when |
|---|---|---|
| Nested loop | For each row in the outer table, look up matching rows in the inner table | One side is small, and the other side has an index on the join column |
| Hash join | Build an in-memory hash table from one input, then probe it with rows from the other | Both inputs are large, the condition is equality, and there is no useful index |
| Merge join | Walk two inputs that are both sorted on the join column, in step | Both inputs are already sorted, for example by an index |
The strategy names differ a little between products, and not every product has all three. The idea carries over, though. The planner estimates the cost of each option from table statistics, such as row counts and how many distinct values a column has, and picks the cheapest.
Without an index on orders.customer_id, the "look up" step becomes a scan of the whole orders table for every customer row. With 10,000 customers and 1,000,000 orders, that is about ten billion row comparisons. With an index, each lookup touches only a handful of index pages.
Which columns to index
A primary key is indexed automatically in every mainstream database. A foreign key is a different matter. PostgreSQL, Oracle, and SQL Server do not create an index on the referencing column. MySQL's InnoDB engine does create one, because it requires an index there.
So in the sample schema, customers.id is indexed, but in PostgreSQL orders.customer_id is not. Joining from customers to orders is exactly the case that benefits from an index on the foreign key.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);
CREATE INDEX idx_order_items_product_id ON order_items (product_id);order_items already has a composite primary key on (order_id, product_id). That index serves joins that look up by order_id, because order_id is the leading column. It does not serve joins that look up only by product_id, which is why the second index above is useful.
Guidelines for join indexes:
- Index the foreign key column on the many side of each relationship you join through.
- For composite indexes, put the column you filter or join by most often first.
- Do not index every column. Each index costs disk space and slows
INSERT,UPDATE, andDELETE. - On a tiny table, the planner may ignore an index and scan the table, because reading a few pages is cheaper than a lookup. That is correct behavior, not a problem.
Reading an execution plan
Every major database can show the plan it chose. The syntax varies:
- PostgreSQL and MySQL:
EXPLAIN, andEXPLAIN ANALYZEto run the query and report real timings. - SQL Server: "Display Estimated Execution Plan" in the client tools, or
SET SHOWPLAN_ALL ON. - Oracle:
EXPLAIN PLAN FOR ...followed by a query onDBMS_XPLAN.DISPLAY. - SQLite:
EXPLAIN QUERY PLAN.
The examples below use PostgreSQL. Try this query:
EXPLAIN
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
WHERE c.id = 1;On a large orders table with the index in place, the plan typically looks like this:
Nested Loop
-> Index Scan using customers_pkey on customers c
Index Cond: (id = 1)
-> Index Scan using idx_orders_customer_id on orders o
Index Cond: (customer_id = 1)Read a plan from the innermost, most indented nodes outward. Each node is one step, and its parent consumes the rows it produces. This plan says: find customer 1 through the primary key index, then find that customer's orders through the foreign key index, and combine them with a nested loop.
Now drop the index and run the same EXPLAIN. On a large table you would see a line like Seq Scan on orders o with a filter on customer_id. A Seq Scan (sequential scan, also called a full table scan) reads every row. That is the sign of a missing or unusable index.
Estimates versus actual numbers
EXPLAIN ANALYZE adds actual row counts and times next to the planner's estimates:
EXPLAIN ANALYZE
SELECT c.name, COUNT(*) AS order_count, SUM(o.total) AS revenue
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;Look for these things in the output:
- Estimated rows far from actual rows. If the planner expected 10 rows and got 500,000, it probably chose a poor strategy. Out-of-date statistics are a common cause. Run
ANALYZE(PostgreSQL) or the equivalent statistics update in your database. - Scans on large tables where you expected an index. Check that the join column is indexed and that its type matches the other side.
- A node that dominates the time. Tune the most expensive node first.
Why an index may not be used
An index on the join column is not always used, even when it exists. These are the usual causes.
- Mismatched types. Joining an
INTEGERcolumn to aVARCHARcolumn forces a conversion on each row, which can prevent index use. Keep join column types identical. - Functions on the join column.
ON LOWER(a.email) = b.emailcannot use a plain index ona.email. Either store normalized data or create an expression index onLOWER(email). - Low selectivity. If a join matches most of the table, scanning it is cheaper than millions of index lookups. The planner will choose a hash join with sequential scans, and that is the right choice.
- Stale statistics. The planner's estimates are wrong, so its choice is too.
- Non-equality conditions. Range joins like the discount tier example can use an index on one side in some databases, but a nested loop over a large table can be slow. Check the plan.
Reducing the work a join does
Indexes are not the only lever. These habits also help:
- Filter early. A selective
WHEREcondition on one table lets the planner reduce that table before it joins. For inner joins, the planner usually treatsWHEREandONfilters as equivalent, so write whichever is clearer. - Select only the columns you need. Avoid
SELECT *on wide joins. Narrow queries can sometimes be answered from an index alone, without reading the table. - Watch for row multiplication. A join that multiplies rows, as in the
order_itemsexample, feeds more rows into every later step. Aggregate before joining when you only need totals from the many side. - Join on keys. Joining on primary key and foreign key columns is the case databases are most heavily optimized for.
For example, summing item quantities per order before joining keeps the result at one row per order:
SELECT o.id, o.order_date, s.units
FROM orders AS o
INNER JOIN (
SELECT order_id, SUM(quantity) AS units
FROM order_items
GROUP BY order_id
) AS s ON s.order_id = o.id;A repeatable tuning routine
- Run the query on realistic data volumes. A plan on ten rows tells you little.
- Run
EXPLAIN ANALYZEand find the most expensive node. - Check for sequential scans on large tables and for estimates far from actual counts.
- Add an index on the join or filter column, or update statistics.
- Run
EXPLAIN ANALYZEagain and compare the times.
Exercise
Your PostgreSQL query joins orders to customers on o.customer_id = c.id. EXPLAIN shows a Seq Scan on orders that takes most of the time, and orders has 5 million rows. You only want orders for one customer. What do you check and what do you change?
Show answer
Check whether orders.customer_id has an index. PostgreSQL does not create one for a foreign key automatically. If it is missing, run CREATE INDEX idx_orders_customer_id ON orders (customer_id);, then run EXPLAIN ANALYZE again. The plan should change to an index scan on orders. If the index exists but is not used, check that the column types on both sides of the join match and that the table statistics are current (ANALYZE orders;).
Exercise
Why can ON LOWER(a.email) = b.email be slow even if a.email has an index, and how can you fix it?
Show answer
The index stores the original email values, not lowercased ones, so the database cannot use it to look up LOWER(a.email). It has to compute the function for every row. Fix it by creating an expression index, such as CREATE INDEX idx_a_email_lower ON a (LOWER(email));, or by storing emails already normalized so the join can compare the columns directly.