I need to drop tables in a PostgreSQL database that have foreign key constraints and require DROP TABLE ... CASCADE
.
I could execute raw SQL: engi
You need the data in pg_constraint
, which is a rather complicated table, that handles all constraints, including check constraints and foreign keys. Fortunately, what you want is fairly straightforward.
In order to get the list of all of the tables referencing table foo
, you can do something like:
SELECT conrelid
FROM pg_constraint
WHERE confrelid = ;
That gets you a list of table relids. But you probably don't want to deal with relids, so let's make it a bit more complicated:
SELECT r.schemaname || '.' || r.relname
FROM pg_stat_user_tables r, pg_constraint c, pg_stat_user_tables s
WHERE
s.relid = c.confrelid AND
c.conrelid = r.relid AND
s.relname = 'foo';
That returns a list which you can then loop through and issue individual DROP TABLE
statements.