Most developers assume a foreign key comes with an index. In PostgreSQL it doesn't: Postgres automatically indexes primary keys and unique constraints, but not the referencing column of a foreign key.

I measured what that costs on PostgreSQL 17.7 with 100,000 users and 2,000,000 orders. The short version: deleting 1,000 users took 46.4 seconds without the index and 22 milliseconds with it.

Prefer video? Here’s the 3-minute version:

The setup

A completely normal schema:

CREATE TABLE users ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL ); CREATE TABLE orders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, user_id bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE, total numeric(10,2) NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); INSERT INTO users (email) SELECT 'user' || g || '@example.com' FROM generate_series(1, 100000) g; INSERT INTO orders (user_id, total, created_at) SELECT 1 + (random() * 99999)::int, round((random() * 200)::numeric, 2), now() - random() * interval '365 days' FROM generate_series(1, 2000000); VACUUM ANALYZE users; VACUUM ANALYZE orders; 

Now look at what Postgres actually created:

=# \d orders Indexes: "orders_pkey" PRIMARY KEY, btree (id) Foreign-key constraints: "orders_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE 

An index on id, a constraint on user_id, and no index on user_id.

This surprises people coming from MySQL, where InnoDB requires an index on foreign key columns and creates one automatically if you don't. (SQLite doesn't create one either.)

Cost 1: every lookup scans the table

Fetching one user's orders is probably the most common query in the app:

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE user_id = 42; 
Gather (cost=1000.00..26124.67 rows=20 width=30) (actual time=2.059..21.719 rows=30 loops=1) Workers Planned: 2 Workers Launched: 2 Buffers: shared hit=14706 -> Parallel Seq Scan on orders (cost=0.00..25122.67 rows=8 width=30) (actual time=1.343..19.440 rows=10 loops=3) Filter: (user_id = 42) Rows Removed by Filter: 666657 Execution Time: 21.724 ms 

Postgres read all 2 million rows (the leader plus two parallel workers, each discarding ~666k) to find 30. Around 22 ms per call, on every page that lists a user's orders. A join from users to orders for one user took 27 ms.

Cost 2: deletes scan it once per deleted row

This is the one that really hurts. When you delete a user, Postgres has to find that user's orders to cascade the delete (or, with the default NO ACTION, to check none exist). That check runs as an internal trigger, and EXPLAIN ANALYZE shows exactly where the time goes:

BEGIN; EXPLAIN ANALYZE DELETE FROM users WHERE id = 42; ROLLBACK; 
Delete on users (cost=0.29..8.31 rows=0 width=0) (actual time=0.011..0.012 rows=0 loops=1) -> Index Scan using users_pkey on users (cost=0.29..8.31 rows=1 width=6) (actual time=0.005..0.005 rows=1 loops=1) Index Cond: (id = 42) Trigger for constraint orders_user_id_fkey: time=41.308 calls=1 Execution Time: 41.325 ms 

Finding the user: 0.005 ms. The foreign-key trigger: 41 ms, because it scans all of orders. And it does that once per deleted user:

Delete Time
1 user 42 ms
100 users 4.5 s
1,000 users 46.4 s

Imagine a nightly job that removes inactive accounts, holding locks the whole time.

The fix: one line

CREATE INDEX CONCURRENTLY orders_user_id_idx ON orders (user_id); 

On 2 million rows it took 0.7 seconds to build and uses 15 MB. CONCURRENTLY builds it without blocking inserts and updates, which is what you want on a live database. (It can't run inside a transaction block, so run it on its own, outside your migration's transaction.)

Results

Same queries, same data:

Query No index With index
SELECT one user's orders 22 ms 0.1 ms
JOIN users → orders (one user) 27 ms 0.5 ms
DELETE 1 user 42 ms 0.2 ms
DELETE 1,000 users 46.4 s 22 ms

The delete trigger went from time=41.308 to time=0.063. Bulk deletes got about 2,000× faster.

Find every unindexed foreign key in your database

This query lists foreign keys whose column isn't the leading column of any index on that table:

SELECT c.conrelid::regclass AS table_name, a.attname AS fk_column FROM pg_constraint c JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1] 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] ); 

Before the fix:

 table_name | fk_column ------------+----------- orders | user_id (1 row) 

After the fix it returns (0 rows).

It checks the first column of each foreign key, which covers the usual single-column case. For multi-column foreign keys, check that some index starts with the same columns.

When can you skip the index?

Only when the child table is tiny, or you never query by that column and never delete or update the parent key. That's rare. For a typical user_id, post_id or order_id, add the index.

Recap

  • Postgres does not create indexes for foreign keys
  • Without one, lookups and joins on that column scan the whole table
  • Every delete of a parent row scans the child table again: 1,000 deletes took 46 seconds
  • Fix: CREATE INDEX CONCURRENTLY ... ON child (fk_column);
  • Use the pg_constraint + pg_index query to find the rest

Run the query on your own database. How many did it find? Tell me in the comments.

I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.