Nov 23, 20266 min read

Do Postgres Foreign Keys Need an Index?

Postgres indexes the referenced side of a foreign key but not the referencing column. What that costs on deletes, updates and joins, how to find unindexed foreign keys, and when you can skip the index.

Illustration for Do Postgres Foreign Keys Need an Index?

Postgres needs an index on the column a foreign key points to, and the primary key already gives it one, but it never creates an index on the column that holds the reference.

That gap stays invisible until a child table grows into the millions and deleting one customer, or one order with a cascade, takes seconds while holding locks.

At a glance

OperationWith an index on the FK columnWithout one
Delete or update a parent keyIndex lookup per parent rowSequential scan of the child table per parent row
ON DELETE CASCADEFast, finds children directlyScans the child table to find them
Join parent to childrenIndex or hash joinUsually a hash join over the whole child table
Insert into the child tableSlightly slower (one more index)Slightly faster
Disk useOne more indexNone

Why Postgres does not index the referencing column

The constraints documentation explains the asymmetry: the referenced columns must already be covered by a primary key or unique index, so checking a new child row is always cheap, while an index on the referencing columns is "often a good idea" but not always needed, and there are several ways to build it. Postgres leaves that choice to you, and most ORMs and migration generators follow its lead and leave it out as well.

What an unindexed foreign key costs

On a test table with 20,000 orders and 400,000 order items on a local Postgres 17 test, deleting one order with ON DELETE CASCADE took about 19 ms without an index on order_items.order_id and about 0.2 ms with one. EXPLAIN ANALYZE shows the cost in the line Trigger for constraint order_items_order_id_fkey, because the foreign key check runs as an internal trigger and does not appear as a scan node in the plan.

Nineteen milliseconds sounds harmless until a cleanup job deletes 10,000 parents in one transaction, which turns it into 10,000 sequential scans while the transaction holds row locks. Joins and lookups such as "all items for this order" pay the same price on every request.

Find every unindexed foreign key

This query lists foreign key constraints that have no index whose leading columns are the constraint's columns, in any order:

SELECT c.conrelid::regclass AS table_name, 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;

It reads pg_constraint, where conkey holds the constrained column numbers, and checks it against each index's indkey. A composite index on (order_id, sku) counts, while one on (sku, order_id) does not help lookups by order_id alone and is not counted.

Adding the index

On a new table, create the index in the same migration as the constraint. On a large table that is already serving traffic, build it without blocking writes:

CREATE INDEX CONCURRENTLY IF NOT EXISTS order_items_order_id_idx ON order_items (order_id);

CONCURRENTLY takes longer and, as the CREATE INDEX documentation notes, cannot run inside a transaction block, and a failed build leaves an invalid index behind that you drop before retrying.

When you can skip it

  • The parent is never deleted and its key never changes. Lookup tables such as countries or currencies are referenced from many rows and almost never deleted.
  • The child table stays small. A few thousand rows scan in well under a millisecond.
  • An existing composite index already starts with the column. A second single-column index would only add write cost.

Best fit: index every foreign key column on tables that grow with usage, and skip it only for small or append-only reference data where you have checked the write cost.

Foreign keys and their indexes in Encore

Encore

Encore is a backend framework with built-in infrastructure, and a service's schema lives in its own migrations directory next to the endpoints that use it, so the foreign key and its index can ship in one migration and be reviewed together. This orders service declares both and maps a missing parent to a clean error:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- orders/migrations/1_create_orders.up.sql CREATE TABLE orders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id text NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE order_items ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE, sku text NOT NULL, quantity int NOT NULL CHECK (quantity > 0) ); CREATE INDEX order_items_order_id_idx ON order_items (order_id);
// orders/orders.go package orders import ( "context" "encore.dev/beta/errs" "encore.dev/storage/sqldb" "encore.dev/storage/sqldb/sqlerr" ) var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{Migrations: "./migrations"}) type AddItemParams struct { SKU string `json:"sku"` Quantity int `json:"quantity"` } type Item struct { ID int64 `json:"id"` } //encore:api public method=POST path=/orders/:orderID/items func AddItem(ctx context.Context, orderID int64, p *AddItemParams) (*Item, error) { var id int64 err := db.QueryRow(ctx, ` INSERT INTO order_items (order_id, sku, quantity) VALUES ($1, $2, $3) RETURNING id `, orderID, p.SKU, p.Quantity).Scan(&id) switch sqldb.ErrCode(err) { case sqlerr.ForeignKeyViolation: return nil, &errs.Error{Code: errs.NotFound, Message: "order not found"} case sqlerr.CheckViolation: return nil, &errs.Error{Code: errs.InvalidArgument, Message: "quantity must be positive"} } if err != nil { return nil, err } return &Item{ID: id}, nil } // Cancel deletes the order; the cascade finds its items through the index. // //encore:api public method=DELETE path=/orders/:orderID func Cancel(ctx context.Context, orderID int64) error { _, err := db.Exec(ctx, `DELETE FROM orders WHERE id = $1`, orderID) return err }

encore run starts Postgres locally and applies the migration, and the local trace shows each query's duration, which is where a slow cascade usually shows up first. The databases docs cover migrations, API errors lists the error codes, and in production the same schema runs on RDS or Cloud SQL in your account, provisioned as described in the AWS infrastructure docs.

An AI coding agent that adds a new child table tends to copy the migration next to it, so having the foreign key and its index together in the first migration makes the indexed version the pattern it repeats. You can also run the unindexed-foreign-key query against the local database in a test and fail the build when it returns rows.

Best fit: services whose schema grows table by table and that want every foreign key indexed from the first migration.

Frequently asked questions

Does Postgres automatically index foreign keys?

No. Postgres requires an index on the referenced columns, which the primary key or unique constraint already provides, but it does not create one on the referencing column. You add that index yourself with CREATE INDEX on the foreign key column.

Why do unindexed foreign keys slow down deletes?

Deleting a parent row, or changing its key, makes Postgres look for child rows that reference it. Without an index on the child's foreign key column that check is a sequential scan of the child table, once for every parent row you delete.

How do I find foreign keys without an index in Postgres?

Query pg_constraint for constraints of type f and check pg_index for an index on the same table whose leading columns are the foreign key columns. The query in this article lists every constraint that has no such index.

How do I add a foreign key index in an Encore service?

Create the index in the same migration that adds the foreign key, in the service's migrations directory. encore run applies it to the local Postgres it starts, and each deploy applies it to the database in your AWS or GCP account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders