Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop multiple tables having foreign keys in PostgreSQL?

I know syntax for deleting multiple tables is:

DROP TABLE foo, bar, baz;

But in my case 3 tables having foreign keys in between them and with other tables which are not to be deleted.

  • Table1: Foreign keys From Table2, Table3, 3 more tables in database.
  • Table2: Forign keys From Table3, 2 more tables in database.
  • Table3: Forign keys From 3 more tables in database.

So how can I drop these 3 tables? They are having data in tables. Will above syntax work ignoring foreign keys? There should not be any data inconsistency in other tables in database.

like image 767
Somnath Muluk Avatar asked Mar 14 '13 07:03

Somnath Muluk


People also ask

Can we DROP TABLE with foreign key?

To drop a foreign key from a table, use the ALTER TABLE clause with the name of the table (in our example, student ) followed by the clause DROP CONSTRAINT with the name of the foreign key constraint.

Does DROP TABLE remove foreign keys?

In SQL Server, you cannot drop a table if it is referenced by a FOREIGN KEY constraint. You have to either drop the child tables before removing the parent table, or remove foreign key constraints.

How do you drop a table that contains referential constraints?

To drop foreign key (referential) constraints, use the DROP CONSTRAINT clause of the ALTER TABLE statement. When a foreign key constraint is dropped, packages or cached dynamic statements containing the following might be marked as invalid: Statements that insert or update the table containing the foreign key.

How do I drop all tables in PostgreSQL?

How to drop all tables in PostgreSQL? 2 From TablePlus GUI: You can select all the available tables from the right sidebar, right click and choose Delete.. , or press Delete key to drop all. Don't forget to commit changes to the server (Cmd + S) after doing so.


1 Answers

You can tell Postgres to automatically drop all foreign keys referencing those tables by using the cascade keyword:

DROP TABLE foo, bar, baz CASCADE;
like image 96
a_horse_with_no_name Avatar answered Oct 13 '22 22:10

a_horse_with_no_name