Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/schema-foreign-key-indexes.md
1---2title: Index Foreign Key Columns3impact: HIGH4impactDescription: 10-100x faster JOINs and CASCADE operations5tags: foreign-key, indexes, joins, schema6---78## Index Foreign Key Columns910Postgres does not automatically index foreign key columns. Missing indexes cause slow JOINs and CASCADE operations.1112**Incorrect (unindexed foreign key):**1314```sql15create table orders (16id bigint generated always as identity primary key,17customer_id bigint references customers(id) on delete cascade,18total numeric(10,2)19);2021-- No index on customer_id!22-- JOINs and ON DELETE CASCADE both require full table scan23select * from orders where customer_id = 123; -- Seq Scan24delete from customers where id = 123; -- Locks table, scans all orders25```2627**Correct (indexed foreign key):**2829```sql30create table orders (31id bigint generated always as identity primary key,32customer_id bigint references customers(id) on delete cascade,33total numeric(10,2)34);3536-- Always index the FK column37create index orders_customer_id_idx on orders (customer_id);3839-- Now JOINs and cascades are fast40select * from orders where customer_id = 123; -- Index Scan41delete from customers where id = 123; -- Uses index, fast cascade42```4344Find missing FK indexes:4546```sql47select48conrelid::regclass as table_name,49a.attname as fk_column50from pg_constraint c51join pg_attribute a on a.attrelid = c.conrelid and a.attnum = any(c.conkey)52where c.contype = 'f'53and not exists (54select 1 from pg_index i55where i.indrelid = c.conrelid and a.attnum = any(i.indkey)56);57```5859Reference: [Foreign Keys](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-FK)60