// SQL snippet

Find foreign keys without a supporting index in PostgreSQL

PostgreSQL does not index foreign keys for you. Every unindexed FK means every parent delete or update scans the child table.

Main statement
PostgreSQL
También cubre
SQL Server

The task

When you delete a parent row, PostgreSQL must verify no child rows reference it. With an index on the child FK column this is a cheap index probe; without one it is a sequential scan of the entire child table, run inside your delete transaction while it holds locks. Small child tables hide the problem for months until the data grows.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

PostgreSQL
SELECT c.conrelid::regclass AS child_table,
       c.conname AS fk_name,
       (SELECT string_agg(quote_ident(a.attname), ', ' ORDER BY k.ord)
        FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)
        JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS fk_columns,
       pg_size_pretty(pg_total_relation_size(c.conrelid)) AS child_table_size
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[0] = c.conkey[1]
  )
ORDER BY pg_total_relation_size(c.conrelid) DESC;

Cómo funciona

pg_constraint holds every FK, and conkey is the array of referencing-column numbers in constraint order. The NOT EXISTS looks for any index on the child table whose first column (indkey[0]) is the FK's first column (conkey[1]); note that indkey counts from 0 and conkey, a normal array, from 1. An index that leads with the FK's first column lets the check seek. The subquery turns conkey back into a quoted column list, and sorting by child table size puts the potentially painful ones first.

Variations

Generate the missing CREATE INDEX statements

SELECT format('CREATE INDEX CONCURRENTLY ON %s (%s);',
              c.conrelid::regclass,
              (SELECT string_agg(quote_ident(a.attname), ', ' ORDER BY k.ord)
               FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)
               JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum)) AS create_statement
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[0] = c.conkey[1]
  )
ORDER BY 1;

SQL Server equivalent

SQL Server
SELECT OBJECT_NAME(fk.parent_object_id) AS child_table, fk.name AS fk_name
FROM sys.foreign_keys fk
JOIN sys.foreign_key_columns fkc
  ON fkc.constraint_object_id = fk.object_id AND fkc.constraint_column_id = 1
WHERE NOT EXISTS (
    SELECT 1 FROM sys.index_columns ic
    WHERE ic.object_id = fkc.parent_object_id AND ic.column_id = fkc.parent_column_id AND ic.key_ordinal = 1
)
ORDER BY child_table, fk_name;

Questions that come up

Multi-column foreign keys: does this catch them?

Yes. It tests whether some index leads with the FK's first column, which is what lets the check seek; for an FK on (order_id, line_no), an index starting with order_id passes. The generated CREATE INDEX lists every FK column in constraint order, so a flagged two-column FK gets a two-column index.

Why CREATE INDEX CONCURRENTLY?

A plain CREATE INDEX takes a SHARE lock that blocks inserts, updates and deletes on the child table until the build finishes. CONCURRENTLY lets writes continue, takes longer, and cannot run inside a transaction block. If it fails partway it leaves an INVALID index behind, which you drop and retry.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.