Sub topic 15
Indexing Foreign Key Columns
Prerequisites and the indexing question
Assume you know how to create tables, declare foreign keys, write joins, and create basic indexes. This chapter uses PostgreSQL-style SQL.
A foreign key protects a relationship, but declaring one does not usually create an index on the referencing column. The referenced primary key already has an index because primary keys require uniqueness. The child table often needs its own index for performance.
In this example, orders.customer_id references customers.customer_id:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES customers (customer_id),
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);The index stores orders.customer_id in an order that lets the database find matching orders without scanning every row.
Which operations benefit
An index on a foreign key is especially useful when the application frequently:
- Joins the child table to the parent table.
- Finds all child rows for one parent.
- Deletes a parent row while checking for referencing rows.
- Updates a referenced parent key.
- Applies an action such as
ON DELETE CASCADE.
For example, this join can use the foreign-key index to locate orders for each customer:
SELECT c.name, o.order_id, o.ordered_at
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id
WHERE c.customer_id = 42
ORDER BY o.ordered_at;The index does not guarantee that PostgreSQL will use it. For a very small table, reading the whole table can be cheaper. The query planner chooses an execution plan using table size, statistics, selectivity, and available indexes.
Choosing a useful index shape
For queries that filter by the foreign key and then sort by a second column, a composite index can help:
CREATE INDEX idx_orders_customer_date
ON orders (customer_id, ordered_at);Column order matters. An index beginning with customer_id can support searches by customer_id. An index beginning with ordered_at usually cannot efficiently support searches for one customer alone.
Do not add indexes automatically to every foreign key. Indexes consume storage and slow inserts, updates, and deletes because the index must also change. Check real queries and use EXPLAIN or EXPLAIN ANALYZE to verify that an index improves the workload.
Exercise
Which index better supports a query filtering only by customerid: (orderedat, customerid) or (customerid, ordered_at)?
Show answer
(customerid, orderedat), because the foreign-key column is the leading column.