Tablux

Tablux › Guides › Postgres foreign key indexes

Guide

PostgreSQL foreign key indexes: find the missing ones, and the unused ones

PostgreSQL indexes the referenced side of a foreign key (it must be a primary key or unique), but not the referencing columns. Without an index on, say, order_items.order_id, every delete from orders scans all of order_items, and so do lookups by order. Add one with CREATE INDEX CONCURRENTLY ON order_items (order_id); and use the catalog queries below to find every foreign key that needs one.

Why PostgreSQL does not index foreign keys for you

A foreign key has two sides. The referenced columns (orders.id) must be a primary key or have a unique constraint, so they always have an index. The referencing columns (order_items.order_id) get none. The PostgreSQL documentation explains why: not every foreign key needs one, and there are many ways to index it (on its own, as the first columns of a composite index, as a partial index), so the choice is left to you.

MySQL's InnoDB takes the other approach and creates an index on the referencing columns automatically if none exists. People who move from MySQL often assume PostgreSQL does the same.

When a missing index hurts

Deleting or updating the parent. For every parent row you delete (or whose key you change), PostgreSQL checks the child table for rows that still point at it. It does the same for ON DELETE CASCADE and SET NULL, which must find the child rows to change. Without an index, each check is a sequential scan of the child table. Delete 1,000 parents and you get 1,000 full scans, while the delete holds its locks.

EXPLAIN ANALYZE shows the cost on the line for the constraint's trigger. In a test on PostgreSQL 16 with 1.7 million rows in order_items, deleting 1,000 orders that had no items left, without the index:

EXPLAIN (ANALYZE, COSTS OFF) DELETE FROM orders WHERE id BETWEEN 2001 AND 3000;
...
 Trigger for constraint order_items_order_id_fkey: time=93460.278 calls=1000
 Execution Time: 93462.069 ms

With an index on order_items (order_id), the same kind of delete took 9 ms. (EXPLAIN ANALYZE really runs the delete; wrap it in BEGIN … ROLLBACK on real data.)

Joins and lookups from the parent. "All items for this order" is WHERE order_id = $1, and joining orders to order_items for a handful of orders wants an index on the same column.

When you can skip it. Small child tables, and parents that are never deleted and never used to look up children, such as a country_code column pointing at a countries table you only join the other way. Every index costs disk space and slows inserts and updates on the child table a little.

Find foreign keys without an index

This query lists every foreign key whose columns are not the leading columns of some index on the child table, biggest tables first:

SELECT c.conrelid::regclass AS table_name,
       c.conname AS foreign_key,
       string_agg(quote_ident(a.attname), ', ' ORDER BY k.n) AS columns,
       c.confrelid::regclass AS referenced_table,
       pg_size_pretty(pg_relation_size(c.conrelid)) AS table_size
FROM pg_constraint c
CROSS JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, n)
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
WHERE c.contype = 'f'
  AND c.conparentid = 0
  AND NOT EXISTS (
    SELECT 1
    FROM pg_index i
    WHERE i.indrelid = c.conrelid
      AND i.indpred IS NULL
      AND i.indnkeyatts >= cardinality(c.conkey)
      AND (i.indkey::int2[])[0:cardinality(c.conkey) - 1] @> c.conkey
  )
GROUP BY c.oid, c.conrelid, c.conname, c.confrelid
ORDER BY pg_relation_size(c.conrelid) DESC;

How it works. pg_constraint.conkey holds the foreign key's column numbers; pg_index.indkey holds an index's columns, as an array that starts at position 0. An index covers the key when its first n columns (for an n-column key) are exactly the key's columns, in any order. That handles multi-column foreign keys: an index on (region, code) or (code, region, id) covers FOREIGN KEY (region, code), but one on (region) alone, or on (created_at, region, code), does not.

  • Partial indexes are ignored (indpred IS NULL), since they may not cover the rows a check needs.
  • INCLUDE columns do not count (indnkeyatts counts only key columns).
  • conparentid = 0 lists a foreign key on a partitioned table once, instead of once per partition. Its table_size shows 0 bytes, because the data lives in the partitions.

A simpler check that only compares each key's first column with each index's first column (indkey[0] = conkey[1]) works for single-column keys and is a fair first pass, but it misses multi-column keys that are only partly covered.

Create the index without blocking writes

CREATE INDEX CONCURRENTLY order_items_order_id_idx
  ON order_items (order_id);

A plain CREATE INDEX blocks inserts, updates and deletes on the table until it finishes. CONCURRENTLY lets them carry on, at the cost of a slower build that waits for running transactions. It cannot run inside a transaction block, so turn off your migration tool's wrapping transaction for that step. For a multi-column key, put the key's columns first, in the same order as the foreign key.

If a concurrent build fails (a deadlock, a cancelled statement), it leaves an INVALID index that is not used for queries but still slows writes. Find and remove it, then try again:

SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY order_items_order_id_idx;

Partitioned tables do not support CREATE INDEX CONCURRENTLY on the parent. Create the parent index with ON ONLY (it starts invalid), build each partition's index concurrently, then attach them; the parent becomes valid once every partition has one:

CREATE INDEX events_customer_id_idx ON ONLY events (customer_id);
CREATE INDEX CONCURRENTLY events_2026_customer_id_idx ON events_2026 (customer_id);
ALTER INDEX events_customer_id_idx ATTACH PARTITION events_2026_customer_id_idx;
-- repeat for each partition

Find unused indexes

The other half of index hygiene: indexes that cost writes and disk but are never read. pg_stat_user_indexes.idx_scan counts how many times each index has been scanned:

SELECT s.schemaname,
       s.relname AS table_name,
       s.indexrelname AS index_name,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size,
       s.idx_scan,
       s.last_idx_scan            -- PostgreSQL 16+; remove on older servers
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
  AND NOT i.indisunique
  AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = s.indexrelid)
ORDER BY pg_relation_size(s.indexrelid) DESC;

The query skips unique indexes and any index that backs a constraint (primary key, unique or exclusion constraint). Those enforce rules even when no query reads them, so they must stay whatever idx_scan says.

Check how long the counters have been running:

SELECT stats_reset FROM pg_stat_database WHERE datname = current_database();

An empty stats_reset means nobody has reset them by hand, but see the caveats below.

Before you drop an index with idx_scan = 0

  • The counters may be younger than you think. They survive a clean restart but are reset after a crash or immediate shutdown, a restore from a base backup, point-in-time recovery and any pg_stat_reset(). Zero scans in a week says little about a month-end report.
  • Replicas count their own scans. Each server keeps its own statistics. An index that is idle on the primary may serve all the read traffic on a replica, so run the query on every replica too.
  • Foreign key indexes can sit idle for weeks. An index on order_items.order_id only gets scanned when someone deletes an order. Cross-check against the foreign key query before dropping.
  • Expression indexes feed the planner. ANALYZE gathers statistics on an expression index's expression, and the planner uses them for estimates even when it never scans the index.
  • Partitioned tables report statistics per partition index, not for the parent index, and you cannot drop one partition's attached index on its own (cannot drop index … because index … requires it). Drop the parent index if it is unused on every partition.

When you are sure, save the definition and drop it without blocking writes:

SELECT pg_get_indexdef('public.orders_status_idx'::regclass);
DROP INDEX CONCURRENTLY public.orders_status_idx;

Resetting statistics, and when not to

To measure from a known starting point you can reset the counters, but think first. pg_stat_reset() zeroes every counter in the current database, including the ones autovacuum uses to decide when to vacuum and analyze; the docs recommend a database-wide ANALYZE afterwards. It is superuser-only unless EXECUTE has been granted.

Two gentler options. Reset a single index with SELECT pg_stat_reset_single_table_counters('public.orders_status_idx'::regclass);. Or do not reset at all: save today's idx_scan values into a table and compare them in a month, which leaves autovacuum's numbers alone. Reset, if you must, just after a deploy rather than before a reporting cycle, so the window covers a full month of real traffic.

Running these checks automatically

Tablux's Insights runs catalog checks like these when it opens on a PostgreSQL connection, over a separate read-only session: foreign keys without an index, unused indexes and tables without a primary key. A suggested CREATE INDEX goes into the editor for you to review; nothing runs by itself. Try it on the demo database, where order_items.product_id is left without an index on purpose.

Questions

Does PostgreSQL automatically create an index on a foreign key?

No. It indexes the referenced primary key or unique columns, but not the referencing columns. Create that index yourself where deletes on the parent or joins need it.

Does a primary key create an index in PostgreSQL?

Yes. A primary key or unique constraint always creates a unique B-tree index, which is why the referenced side of a foreign key is already indexed.

Does MySQL index foreign keys automatically?

Yes. InnoDB requires an index on the referencing columns and creates one if none exists, so MySQL has no equivalent of this problem.

Is it safe to drop an index with idx_scan = 0?

Not on that number alone. Check how long the statistics have been collecting, check every replica, and keep indexes that back constraints or foreign keys.

Does CREATE INDEX CONCURRENTLY lock the table?

It takes a lock that allows reads and writes to continue but blocks other schema changes and VACUUM on that table while it runs. Before it finishes it also waits for transactions that were already running.

Updated 2026-11-25