Video in progress

Does PostgreSQL automatically create an index on a foreign key column, and what does that affect?

No. PostgreSQL requires an index only on the primary key or unique column in the parent table; it doesn't create an index on the FK column in the child table. Without an index, JOINs are slow, and deleting a parent row or changing its key makes a full scan of the child table.

📖 Answer

MySQL InnoDB adds the index on an FK by itself, so people coming from there often don't know this.

CREATE TABLE order_item (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    ...
);
-- you have to add this yourself
CREATE INDEX idx_order_item_order_id ON order_item (order_id);

What happens without the index:

  • SELECT ... FROM order_item WHERE order_id = ? does a Seq Scan every time;
  • DELETE FROM orders WHERE id = ? makes the database check the child rows (or delete them with CASCADE), and for every deleted parent it scans the whole order_item. Deleting 10,000 orders means 10,000 full scans. Locks are held that whole time.

It's easy to find a query on the internet that compares pg_constraint and pg_index to find FKs without an index; I run it once when I join a new project.

There is an exception too: for small reference tables whose parent rows are never deleted and which aren't searched by the FK column in the child table, the index may just be an extra write cost. But the default decision is to add the index.