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-constraints.md
1---2title: Add Constraints Safely in Migrations3impact: HIGH4impactDescription: Prevents migration failures and enables idempotent schema changes5tags: constraints, migrations, schema, alter-table6---78## Add Constraints Safely in Migrations910PostgreSQL does not support `ADD CONSTRAINT IF NOT EXISTS`. Migrations using this syntax will fail.1112**Incorrect (causes syntax error):**1314```sql15-- ERROR: syntax error at or near "not" (SQLSTATE 42601)16alter table public.profiles17add constraint if not exists profiles_birthchart_id_unique unique (birthchart_id);18```1920**Correct (idempotent constraint creation):**2122```sql23-- Use DO block to check before adding24do $$25begin26if not exists (27select 1 from pg_constraint28where conname = 'profiles_birthchart_id_unique'29and conrelid = 'public.profiles'::regclass30) then31alter table public.profiles32add constraint profiles_birthchart_id_unique unique (birthchart_id);33end if;34end $$;35```3637For all constraint types:3839```sql40-- Check constraints41do $$42begin43if not exists (44select 1 from pg_constraint45where conname = 'check_age_positive'46) then47alter table users add constraint check_age_positive check (age > 0);48end if;49end $$;5051-- Foreign keys52do $$53begin54if not exists (55select 1 from pg_constraint56where conname = 'profiles_birthchart_id_fkey'57) then58alter table profiles59add constraint profiles_birthchart_id_fkey60foreign key (birthchart_id) references birthcharts(id);61end if;62end $$;63```6465Check if constraint exists:6667```sql68-- Query to check constraint existence69select conname, contype, pg_get_constraintdef(oid)70from pg_constraint71where conrelid = 'public.profiles'::regclass;7273-- contype values:74-- 'p' = PRIMARY KEY75-- 'f' = FOREIGN KEY76-- 'u' = UNIQUE77-- 'c' = CHECK78```7980Reference: [Constraints](https://www.postgresql.org/docs/current/ddl-constraints.html)81