dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/postgresql/#17
Script #17
postgresql
Performanceread-onlyMin Version: 10

Find Foreign Keys Without Supporting Indexes in PostgreSQL

Lists foreign keys with no index on the referencing side. A common cause of slow deletes, updates and lock contention.

#foreign-key#missing-index#locking
postgresql · sql
SELECT c.conrelid::regclass AS table_name,
       c.conname AS fk_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:array_length(c.conkey, 1)] @> c.conkey
  )
ORDER BY 1, 2;
Operational Notes & Remediation Guidance

Unindexed foreign keys cause full table scans on child tables during DELETE/UPDATE operations on parent tables.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 10).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.