// SQL snippet

Generate DDL for missing foreign-key indexes in SQL Server

SQL Server does not index foreign-key columns for you. This walks the catalog views and prints a CREATE INDEX for every foreign key that no index leads with.

Main statement
SQL Server
同時涵蓋
PostgreSQL

The task

Deleting a parent row (or changing its key) makes SQL Server check every child table that references it. With an index on the child's FK column that check is a seek; without one it is a scan of the child table, run inside the delete and holding locks while it runs. Joins on the FK column pay the same price. Creating a FOREIGN KEY constraint does not create an index, so after a few years of migrations nobody knows which FK columns have one.

The snippet

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

SQL Server
SELECT 'CREATE INDEX ' + QUOTENAME('ix_' + tb.name + '_' + COL_NAME(lead_col.parent_object_id, lead_col.parent_column_id)) + ' ON '
       + QUOTENAME(SCHEMA_NAME(tb.schema_id)) + '.' + QUOTENAME(tb.name)
       + ' (' + cols.list + ');' AS create_statement,
       tb.name AS child_table,
       fk.name AS fk_name,
       cols.list AS fk_columns,
       OBJECT_NAME(fk.referenced_object_id) AS parent_table
FROM sys.foreign_keys fk
JOIN sys.tables tb ON tb.object_id = fk.parent_object_id
JOIN sys.foreign_key_columns lead_col
  ON lead_col.constraint_object_id = fk.object_id AND lead_col.constraint_column_id = 1
CROSS APPLY (
    SELECT STRING_AGG(QUOTENAME(c.name), ', ') WITHIN GROUP (ORDER BY fkc.constraint_column_id) AS list
    FROM sys.foreign_key_columns fkc
    JOIN sys.columns c ON c.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id
    WHERE fkc.constraint_object_id = fk.object_id
) cols
WHERE NOT EXISTS (
    SELECT 1
    FROM sys.index_columns ic
    WHERE ic.object_id = fk.parent_object_id
      AND ic.column_id = lead_col.parent_column_id
      AND ic.key_ordinal = 1
)
ORDER BY child_table, fk_name;

它的運作方式

In sys.foreign_keys the referencing (child) table is parent_object_id and the referenced table is referenced_object_id, which reads backwards but is how the catalog names them. sys.foreign_key_columns lists each FK's child columns in order, and constraint_column_id = 1 picks the leading one. The NOT EXISTS looks for any index whose first key column (key_ordinal = 1) is that column: an index on (other_col, fk_col) cannot seek on fk_col. Included columns have key_ordinal 0, so they correctly do not count. STRING_AGG (SQL Server 2017 and later) builds the full column list so a two-column FK gets a two-column index, and QUOTENAME keeps the statements valid for names with spaces or brackets. Review the list before running it; every new index adds write cost.

Variations

PostgreSQL equivalent

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;

Questions that come up

Why is the first key column the only one that matters?

The check that runs when you delete a parent row looks up child rows by the FK columns. An index whose first key column is one of them can seek; an index that starts with some other column can only be scanned for that lookup. key_ordinal = 1 in sys.index_columns is the leading-column test. For a multi-column FK an index leading with the first FK column is usually enough, and the generated statement covers all of them.

Should I index every FK the query flags?

No. Index the FK when parent rows get deleted or re-keyed, or when queries join or filter on the column. If the parent table is append-only and nothing joins through that column, the index costs writes and buys nothing. MySQL is different: InnoDB requires an index on foreign-key columns and creates one automatically if none exists, so this check is not needed there.

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.