SQLNirvana by Pyro

Blog › postgresql · indexes

PostgreSQL foreign keys without indexes slow down deletes and joins

PostgreSQL indexes the referenced side of a foreign key, but not the referencing side. Why that matters, how to find the gaps, and how to fix them without locking.

When you declare a foreign key, PostgreSQL requires a unique index on the column being referenced: usually the parent's primary key. It does not create an index on the referencing column in the child table. MySQL's InnoDB does create one automatically, which is why people moving from MySQL are often surprised.

Why it matters

Take enrolments.course_id REFERENCES courses(id):

On a small table nobody notices. On a child table with 50 million rows, deleting a hundred parents can take minutes and block other writers.

Find foreign keys without a supporting index

This finds foreign keys where no index starts with the same columns:

SELECT c.conrelid::regclass AS table_name, c.conname AS fk_name,
       array_to_string(ARRAY(SELECT a.attname FROM unnest(c.conkey) k
                             JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k), ', ') AS columns
FROM pg_constraint c
WHERE c.contype = 'f'
  AND NOT EXISTS (
    SELECT 1 FROM pg_index i
    WHERE i.indrelid = c.conrelid
      AND (i.indkey::int2[])[0:cardinality(c.conkey) - 1] @> c.conkey
      AND (i.indkey::int2[])[0:cardinality(c.conkey) - 1] <@ c.conkey);

Fix it without blocking writes

CREATE INDEX CONCURRENTLY idx_enrolments_course_id ON enrolments (course_id);

CONCURRENTLY builds the index without blocking inserts and updates. It takes longer, can't run inside a transaction block, and if it fails it leaves an invalid index behind that you should drop and retry. Check with \d enrolments in psql.

Do you always need one?

Mostly yes. The exceptions are small lookup tables, and parents that are never deleted or updated and never joined from. If in doubt, add it: the cost is some disk and slightly slower inserts on the child table.

SQLNirvana's Schema tab lists every foreign key without an index on each database, with the CREATE INDEX CONCURRENTLY statement ready to run. The free PostgreSQL check finds them too.

Let SQLNirvana watch it for you

Health, tuning, security and upgrade checks every minute. Free for one server.

Start free