Skip to main content

Distribute Foreign Keys

When it's time to distribute the foreign keys in postgres:
select 'alter table '||quote_ident(ns.nspname)||'.'||quote_ident(tb.relname)||
' drop constraint '||quote_ident(conname)||';'||chr(10)||
'alter table '||quote_ident(ns.nspname)||'.'||quote_ident(tb.relname)||
' add constraint '||quote_ident(conname)||' '||
pg_get_constraintdef(c.oid, true)||';' as ddl
from pg_constraint c
join pg_class tb on tb.oid = c.conrelid
join pg_namespace ns on ns.oid = tb.relnamespace
where ns.nspname in ('public') --<<< adjust the schema name(s) here
and c.contype = 'f'; (edited)

Pulled from: https://dba.stackexchange.com/questions/125578/recreate-all-foreign-keys-in-all-tables-as-deferrable-batch