Skip to content

Instantly share code, notes, and snippets.

@akheron
Last active September 8, 2015 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akheron/368ed409dea96706d2a3 to your computer and use it in GitHub Desktop.
Save akheron/368ed409dea96706d2a3 to your computer and use it in GitHub Desktop.
Change foreign key constraints to point to a different table
-- PostgreSQL
SELECT
'ALTER TABLE ' || source_tbl.relname || ' ' ||
'DROP CONSTRAINT '|| constr.conname ||'; ' ||
'ALTER TABLE ' || source_tbl.relname || ' ' ||
'ADD CONSTRAINT ' || constr.conname || ' ' ||
'FOREIGN KEY (' || source_col.attname || ') ' ||
'REFERENCES new_table_name (primary_key_name);'
FROM pg_constraint constr
INNER JOIN pg_class target_tbl ON constr.confrelid = target_tbl.oid
INNER JOIN pg_attribute target_col ON target_tbl.oid = target_col.attrelid
INNER JOIN pg_class source_tbl ON constr.conrelid = source_tbl.oid
INNER JOIN pg_attribute source_col ON source_tbl.oid = source_col.attrelid
WHERE target_tbl.relname = 'target_table_name'
AND target_col.attname = 'primary_key_name'
AND source_col.attnum = constr.conkey[1];
-- Outputs the following statements for all foreign key constraints that refer
-- target_table_name (primary_key_name):
-- ALTER TABLE source_table_name DROP CONSTRAINT old_constraint_name;
-- ALTER TABLE source_table_name
-- ADD CONSTRAINT old_constraint_name
-- FOREIGN KEY (referencing_column_name) REFERENCES new_table_name (primary_key_name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment