Skip to content

Instantly share code, notes, and snippets.

@christopher-b
Created April 22, 2014 19:05
Show Gist options
  • Save christopher-b/11190658 to your computer and use it in GitHub Desktop.
Save christopher-b/11190658 to your computer and use it in GitHub Desktop.
Postgres - Drop / Recreate constraints
# These queries generate *other* queries that can be used to drop and recreate constraints on all tables in the database.
# Both must be run while the constrains still exist
# Drop constraints
SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" DROP CONSTRAINT "'||conname||'";'
FROM pg_constraint
INNER JOIN pg_class ON conrelid=pg_class.oid
INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace
ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END,contype,nspname,relname,conname
# Recreate constraints
SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" ADD CONSTRAINT "'||conname||'" '||
pg_get_constraintdef(pg_constraint.oid)||';'
FROM pg_constraint
INNER JOIN pg_class ON conrelid=pg_class.oid
INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace
ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END DESC,contype DESC,nspname DESC,relname DESC,conname DESC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment