Difficulty: Intermediate
Should you always create an index on foreign key columns? What happens if you do not?
Almost always, yes. A foreign key constraint is enforced against the parent's primary key index, but the child-side column (for example order_items.order_id) is not automatically indexed in PostgreSQL, SQL Server or Oracle. Without that index, joins from parent to child, ON DELETE CASCADE, and every delete or key update on the parent must scan the whole child table.
| Database | Index on referenced (parent) key | Index on referencing (child) column |
|---|---|---|
| PostgreSQL | Required (PK or unique) | Not created automatically |
| MySQL InnoDB | Required | Created automatically if none exists |
| SQL Server | Required (PK or unique) | Not created automatically |
| Oracle | Required (PK or unique) | Not created automatically |
So the classic surprise is PostgreSQL: you declare REFERENCES orders(id) and assume it is indexed, but it is not.
SELECT * FROM order_items WHERE order_id = 123 is the most common query on a child table. Without an index it is a sequential scan."Always" is a good default, but there are honest exceptions:
orders.status_id referencing a five-row order_status table that is never deleted from, and nobody queries "all orders with status X" without other filters. The index costs write time and space for no read benefit.(order_id, product_id) already serves lookups by order_id, so a separate single-column index is redundant.Many teams run a query in CI that lists foreign key columns without a matching leading index column. Tools like pg_stat_user_tables (high seq_scan counts on child tables) and slow delete logs are also strong hints.
(product_id, order_id) and expecting it to help lookups by order_id; the FK column must be the leading column.CREATE TABLE order_items (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products(id),
qty INTEGER NOT NULL
);
-- PostgreSQL does NOT create these automatically
CREATE INDEX CONCURRENTLY order_items_order_id_idx ON order_items (order_id);
CREATE INDEX CONCURRENTLY order_items_product_id_idx ON order_items (product_id);
CONCURRENTLY builds the index without blocking writes, which matters when fixing this on a live table.
SELECT c.conrelid::regclass AS child_table,
a.attname AS fk_column,
c.conname AS constraint_name
FROM pg_constraint c
JOIN pg_attribute a
ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid
AND i.indkey[0] = c.conkey[1] -- FK column leads the index
);
This simplified check flags FKs whose first column does not lead any index; run it in CI to catch new omissions.
Foreign Key Index, ON DELETE CASCADE, Join Performance, Lock Contention, Referential Integrity