Practical technical guides / Core IT: databases

Unindexed Foreign Keys Make PostgreSQL Parent Deletes Scan the Child Table

PostgreSQL does not index referencing columns. On 18.4, deleting 200 orders spent 17 to 20 s in the FK trigger without an index, under 25 ms with one.

By Sandeep Belgavi · Published 2026-12-04 · Prepared 2026-12-03

Deleting a parent scans every child row
Original explanatory diagram; synthetic values where shown.

PostgreSQL does not index referencing columns. On 18.4, deleting 200 orders spent 17 to 20 s in the FK trigger without an index, under 25 ms with one.

The index PostgreSQL does not create for you

Declare a primary key or a unique constraint in PostgreSQL and you get an index with it. Declare a foreign key and you do not. The referenced side already has one, because a foreign key must point at a primary key or unique constraint. The referencing side, the child table, gets nothing unless you create it.

The PostgreSQL documentation states the consequence directly in its section on constraints: since a delete of a row from the referenced table, or an update of a referenced column, will require a scan of the referencing table for rows matching the old value, it is often a good idea to index the referencing columns too. Because this is not always needed, and there are many choices on how to index, the declaration of a foreign key constraint does not automatically create an index on the referencing columns.

"Often a good idea" undersells it for tables that grow. Inserts into the child table are unaffected, because they look up the parent's index. Reads that join on the key may be slow but visibly so. Deletes of parents are where the missing index hides, because the cost appears inside a trigger, not in the plan of the statement that caused it.

Worked example: deleting 200 orders

The Belgavi's Book Store order database has an orders table and an order_lines table that references it with ON DELETE CASCADE. A nightly job removes cancelled test orders. On a synthetic copy with 20,000 orders and 400,000 lines, the job deletes 200 orders, each with 20 lines.

CREATE TABLE orders (order_id bigint PRIMARY KEY, customer text NOT NULL);
CREATE TABLE order_lines (
  line_id  bigint PRIMARY KEY,
  order_id bigint NOT NULL REFERENCES orders ON DELETE CASCADE,
  isbn     text NOT NULL
);
-- 20,000 orders, 400,000 lines, then:
EXPLAIN (ANALYZE, COSTS OFF) DELETE FROM orders WHERE order_id BETWEEN 1 AND 200;

The probe ran this on PostgreSQL 18.4 on a laptop, three times without an index on order_lines.order_id and three times with one, rolling back each delete. The interesting line of the plan is the last one, which reports time spent in the foreign key's trigger.

Child indexRunTrigger timeTrigger callsTotal execution
none120,334 ms20020,343 ms
none216,924 ms20016,925 ms
none316,906 ms20016,907 ms
on order_id124.7 ms20025.5 ms
on order_id221.4 ms20022.2 ms
on order_id311.8 ms20012.2 ms

The delete of the 200 parent rows themselves is fast in both cases; almost all of the time is the trigger. The trigger runs once per deleted parent, and each call has to find that parent's children. Without an index, the only way to find one order's lines is a sequential scan of all 400,000 rows, so the trigger reads the whole table 200 times. A standalone EXPLAIN of that lookup shows the sequential scan, and with the index it becomes a bitmap index scan; the cascaded delete inside the trigger runs without parallel workers, because PostgreSQL does not use parallel plans for data-modifying statements. These are single-machine timings on synthetic data and the ratio will differ on your hardware; the shape, one full scan per deleted parent, does not.

Two things make this easy to miss. First, the delete statement's own plan looks fine: an index scan on orders by primary key. The cost appears only as a "Trigger for constraint" line, and only when you run EXPLAIN ANALYZE, which most people do not do for a delete. Second, the delete holds row locks on the parents and, through the cascade, on the children for the whole duration. A 17-second delete in a nightly job becomes a 17-second lock on rows that the daytime application may also touch.

It is not only ON DELETE CASCADE. A foreign key with the default NO ACTION or with RESTRICT must also check whether any children exist before allowing the parent delete, and that check needs the same lookup. ON DELETE SET NULL has to find the children to update them. Updating a referenced key column triggers the same work.

Finding unindexed foreign keys

You can find candidates from the catalog. The query below lists foreign keys where no index on the child table starts with the foreign key's columns. It accepts an index whose leading columns are the foreign key columns in any order; an index that merely contains them somewhere does not help the lookup.

SELECT c.conrelid::regclass AS child_table,
       c.conname           AS constraint_name,
       pg_get_constraintdef(c.oid) AS definition
FROM pg_constraint c
WHERE c.contype = 'f'
  AND NOT EXISTS (
    SELECT 1 FROM pg_index i
    WHERE i.indrelid = c.conrelid
      AND (string_to_array(i.indkey::text, ' ')::int2[])[1:cardinality(c.conkey)] @> c.conkey
  )
ORDER BY 1, 2;

Tested on a scratch schema with two foreign keys: one with no index at all, and one whose only covering index was (reason, order_id). Both were reported, the second correctly, because an index led by reason cannot find rows by order_id. After adding an index on order_lines (order_id), only the second remained.

Treat the output as a list to review, not a list to fix blindly. Some foreign keys reference tables whose rows are never deleted or re-keyed, such as a currency or country table. An index there costs write throughput and storage for no benefit.

Adding the index on a live table

On a table in use, create the index without blocking writes:

CREATE INDEX CONCURRENTLY order_lines_order_id_idx ON order_lines (order_id);

CONCURRENTLY takes longer and cannot run inside a transaction block. If it fails partway, it leaves an invalid index behind, which you must drop and recreate; check pg_index.indisvalid after it finishes. Many migration tools wrap every migration in a transaction, so this statement often needs a migration that opts out of that.

If the child table already has a composite index whose leading column is the foreign key, you do not need another. If the composite index starts with a different column, it does not help, as the catalog query shows.

Composite keys and partitioned tables

A composite foreign key, such as (store_id, order_id), needs an index whose leading columns are both key columns. An index on order_id alone helps the lookup but still forces the database to filter the matching rows by store_id; an index on (store_id, created_at, order_id) does not help it at all, because created_at sits between the key columns. The catalog query reports both cases, because it accepts only an index whose leading columns are exactly the key columns, which is the conservative reading.

Partitioned child tables add a wrinkle. Creating an index on a partitioned table creates a matching index on each partition, but the PostgreSQL documentation notes that concurrent builds for indexes on partitioned tables are not supported. The documented workaround is to create the index on the parent only, which is cheap and marks it invalid, then build the index concurrently on each partition and attach each one to the parent index. When every partition's index is attached, the parent index becomes valid.

Tradeoffs

  • Write cost. Every insert and every update of the key column also maintains the new index. For append-heavy child tables with rare parent deletes, measure whether the deletes justify it.
  • Storage. A bigint index on 400,000 rows is small; on billions of rows it is not. Partial indexes can help when only some children are ever affected.
  • Alternative strategies. Some teams never delete parents and instead mark them inactive. That avoids the trigger entirely and may be the better design for audit-heavy data, but then the foreign key's delete behaviour no longer matters and should not be relied on.

Failure modes in practice

  • The batch job that slowly gets slower. The delete scans the child table once per parent, so its cost grows with both the number of parents deleted and the size of the child table. A job that took seconds in the first year takes minutes in the third.
  • Lock pile-ups. A long cascade holds locks while the application waits. The symptom is often blamed on the application.
  • Timeouts on admin actions. Deleting one customer with thousands of related rows across several unindexed child tables can exceed the statement timeout of an admin tool.

Verification

Add the catalog query to your schema checks, with an explicit allow-list of foreign keys that intentionally have no index. For a suspect table, run the delete inside a transaction with EXPLAIN (ANALYZE) on a production-sized copy and read the "Trigger for constraint" lines, then roll back. Compare the trigger time before and after the index. If the trigger time is a small fraction of the total, the index was not your problem; look elsewhere.

Primary references and authorship

Sources checked 2026-12-03. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/postgres_unindexed_fk. Views are my own and do not represent any employer, past or present.