Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - How to drop all tables in a database except for 3

Tags:

postgresql

I know that to drop a table in a database is as follows, but if I have a database that has over a dozen tables and I only need to keep 3 of them, am I able to delete all but the 3 with only one command?

DROP TABLE IF EXISTS c_note RESTRICT;
like image 716
pete.si Avatar asked Dec 20 '22 10:12

pete.si


1 Answers

Yes, but you need to enumerate over all the tables you want to drop. There's no command to drop all but 3. So, if you had the following tables:

  1. foo
  2. bar
  3. baz
  4. narf
  5. poit
  6. troz

And you wanted to drop the first three and keep the last three, you would use the command:

 DROP TABLE foo, bar, baz;

If you know the tables all exist, there's no need for IF EXISTS, although it won't hurt. RESTRICT is also not needed -- that's the default (the opposite is CASCADE, where you also drop dependant objects).

SQL Doc

like image 109
khampson Avatar answered Jan 19 '23 01:01

khampson