FK Performance

Difficulty: Intermediate

Question

Should you always create an index on foreign key columns? What happens if you do not?

Answer

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.

What the database does and does not create for you

DatabaseIndex on referenced (parent) keyIndex on referencing (child) column
PostgreSQLRequired (PK or unique)Not created automatically
MySQL InnoDBRequiredCreated automatically if none exists
SQL ServerRequired (PK or unique)Not created automatically
OracleRequired (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.

Where a missing FK index hurts

  • Joins and lookups: 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.
  • Deleting a parent: to check for (or cascade to) child rows, the database must find children with that key. Deleting one customer can scan a 100 million row orders table. Bulk deleting 10,000 parents can mean 10,000 such scans.
  • Updating a parent key: same check, same scan.
  • Locking: in Oracle, an unindexed foreign key makes parent deletes or key updates take a table-level lock on the child, a well-known cause of blocking. Other engines hold row locks longer because the check is slow.

When you might skip it

"Always" is a good default, but there are honest exceptions:

  • Small lookup parents that never change: 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.
  • A composite index already leads with the FK column: an index on (order_id, product_id) already serves lookups by order_id, so a separate single-column index is redundant.
  • Very write-heavy, rarely read child tables, such as logs, where every extra index slows inserts.

Checking an existing schema

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.

Common mistakes

  • Assuming the foreign key constraint itself creates an index.
  • Indexing (product_id, order_id) and expecting it to help lookups by order_id; the FK column must be the leading column.
  • Deleting old parent rows in bulk during peak hours and blaming "slow deletes" instead of the missing child index.
Deleting a parent row with ON DELETE CASCADE. The child lookup step is where a missing index turns one delete into a full table scan.
  1. DELETE FROM orders WHERE id = 9: Parent row located via primary key.
  2. FK trigger fires: Database must find dependent child rows.
  3. Search order_items.order_id: Index seek if indexed, full scan if not.
  4. Delete matching children: Cascade removes or blocks on found rows.
  5. Commit: Locks released once the work finishes.

Code examples

Add the missing FK index in PostgreSQL

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.

Find foreign keys whose first column is not indexed (PostgreSQL)

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.

Key points

  • The parent key is always indexed; the child FK column usually is not, except in MySQL InnoDB.
  • Missing FK indexes slow joins, parent deletes, cascades and parent key updates.
  • In Oracle, unindexed FKs cause child table locks during parent deletes.
  • A composite index that starts with the FK column already covers it.
  • Skip the index only for tiny, static lookup parents that are never filtered on.

Common follow-up questions

  • Why does deleting one row from a parent table take minutes?
  • Does an index on (a, b) help a query that filters only on b?
  • What is the cost of having too many indexes on a write-heavy table?
  • How would you detect unindexed foreign keys in an existing database?

Interview tips

  • Point out that PostgreSQL does not auto-index FK columns while MySQL InnoDB does; it shows hands-on knowledge.
  • Explain the delete and cascade path, not just joins; that is the part most candidates miss.
  • Give one sensible exception so the answer sounds like judgment rather than a rule recited.

Concepts covered

Foreign Key Index, ON DELETE CASCADE, Join Performance, Lock Contention, Referential Integrity

More Database Design questions