Menu
mediumGrab · indexing

Index a foreign key column Postgres never indexed for you

orders.customer_id references customers.id — the foreign key is already in place and enforced. What surprises a lot of people: Postgres does not automatically create an index on the referencing column of a foreign key (only on the referenced side, because a primary key already implies one). Every lookup of "this customer's orders" is currently a full scan of orders.

Create an index on orders.customer_id.

Schema

customers
idINT
nameTEXT
orders
idINT
customer_idINT
amountNUMERIC

Example input

customers
orders
↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.