Sub topic 15
Indexing foreign key columns
This chapter assumes you can write CREATE TABLE with primary and foreign key constraints, and that you know what a join does. It uses the customers and orders tables from earlier chapters, with PostgreSQL syntax.
What the database indexes for you
Declaring a primary key or a unique constraint creates a unique index automatically. That index is how the database checks uniqueness quickly.
A foreign key is different. The constraint sits on the child table (the one holding the REFERENCES clause) and points at a key in the parent table. The parent side is already indexed, because it must be a primary key or unique column. The child side gets no index in PostgreSQL, so orders.customer_id has none until you create one.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);Why the child column needs an index
Three common operations search the child table by the foreign key value.
- Joins from parent to child. A query such as "all orders for customer 42" filters
ordersoncustomer_id. Without an index, the database reads every row oforders. - Parent deletes. Before deleting a customer, the database must check whether any order still references it. Without an index, that check scans all of
ordersfor each deleted customer. - Parent key updates and cascades.
ON DELETE CASCADEandON DELETE SET NULLmust first find the matching child rows. Without an index, a cascade from one parent row scans the whole child table.
The cost of a missing index grows with the child table. The problem is easy to miss because the constraint still works. It only gets slow once the table is large.
Checking whether the index is used
Use EXPLAIN to see the plan for a lookup by foreign key.
EXPLAIN
SELECT order_id, ordered_at
FROM orders
WHERE customer_id = 42;Without the index, the plan shows Seq Scan on orders. With it, you can see Index Scan or Bitmap Heap Scan using idx_orders_customer_id. On a table with only a few hundred rows, PostgreSQL may keep choosing a sequential scan even when the index exists, because reading a few pages is cheaper than an index lookup. Test with realistic row counts before you decide an index is not working.
Composite primary keys already cover one column
A composite primary key creates one index over its columns in the declared order. That index can serve searches on the leading column, but not efficiently on a later column alone. Look at the junction table from the many-to-many chapter:
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id) ON DELETE RESTRICT
);The primary key index on (order_id, product_id) serves lookups by order_id, so that foreign key is covered. Lookups by product_id alone, such as "which orders contain product 7", cannot use that index well. The ON DELETE RESTRICT check on products also searches by product_id. The second foreign key needs its own index:
CREATE INDEX idx_order_items_product_id ON order_items (product_id);Column order in the primary key matters here. Put the column you search by most often first, or add a separate index for the other column.
Finding unindexed foreign keys
On an existing database, you can ask the catalog which single-column foreign keys have no index starting with that column.
SELECT c.conrelid::regclass AS child_table,
c.conname AS constraint_name
FROM pg_constraint AS c
WHERE c.contype = 'f'
AND array_length(c.conkey, 1) = 1
AND NOT EXISTS (
SELECT 1
FROM pg_index AS i
WHERE i.indrelid = c.conrelid
AND i.indpred IS NULL
AND i.indkey[0] = c.conkey[1]
);The query skips multi-column foreign keys and partial indexes. Treat the output as a list of candidates, not a list of mistakes.
When not to add the index
Each index costs disk space and slows every INSERT, DELETE, and any UPDATE that changes the indexed column. Skip the index, or delay it, in these cases:
- Small child tables. A table that will stay at a few hundred rows is fast to scan.
- Parent rows that are never deleted or re-keyed, and no queries filter by the column. Surrogate parent keys are rarely updated, and many lookup tables are never deleted from. The index then only serves joins.
- Very low-selectivity columns. If a foreign key has a handful of distinct values spread across millions of rows, the planner may ignore the index for most lookups.
- Another index already covers it. A composite index such as
(customer_id, ordered_at)serves lookups bycustomer_idalone, so a separate single-column index is redundant.
A useful composite index for the orders table could replace the single-column one:
CREATE INDEX idx_orders_customer_ordered_at ON orders (customer_id, ordered_at);This serves "orders for customer 42, newest first" and also the foreign key checks.
How other databases differ
| Database | Index on the child foreign key column |
|---|---|
| PostgreSQL | Not created automatically. You add it. |
| MySQL (InnoDB) | Created automatically if no suitable index exists. |
| SQL Server | Not created automatically. You add it. |
| Oracle | Not created automatically. Missing indexes can cause extra locking on the child table when parent keys change. |
Because MySQL creates the index for you, a schema ported from MySQL to PostgreSQL loses those indexes unless you add them explicitly.
Common mistakes
- Assuming the foreign key declaration creates an index, then finding slow parent deletes in production.
- Indexing only the first column of a composite foreign key when queries need the whole key. For a multi-column foreign key, index all its columns, in the same order as the key.
- Adding a single-column index that duplicates the leading column of an existing composite index.
- Judging index usefulness from a nearly empty development table.
Exercise
The table orderitems has PRIMARY KEY (orderid, product_id) and foreign keys on both columns. Which foreign key column needs a separate index in PostgreSQL, and why?
Show answer
productid. The primary key index starts with orderid, so it already serves lookups and constraint checks on orderid. It cannot efficiently find rows by productid alone, so queries by product and ON DELETE RESTRICT checks on products would scan the table. Create it with CREATE INDEX idxorderitemsproductid ON orderitems (productid);
Exercise
You delete one row from customers, and the delete takes several seconds even though orders is large and the customer has no orders. What is the likely cause, and what is the fix?
Show answer
Nothing indexes orders.customerid, so the foreign key check scans the whole orders table to confirm no child rows exist. Create an index on orders (customerid).