Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: delete all tables or cascade a delete?

Tags:

postgresql

Is it possible either to delete all rows from all tables with a single command in postgres (without destroying the database), or to cascade a delete in postgres?

If not, then how can I reset my test database?

like image 312
AP257 Avatar asked Aug 19 '10 17:08

AP257


1 Answers

is it possible either to delete all rows from all tables with a single command in postgres

You are right, the answer is NO

You can define cascading foreign keys that will delete all referencing rows if the "parent" is deleted. But that is an attribute of the foreign key, nothing you can specify with the DELETE statement

if not - wow.

What's that supposed to mean?

On second thought: what are you trying to achieve?

I have the suspicion that you are trying to "reset" e.g. a test database. In that case the PostgreSQL approach would be:

  • Create a database that contains everything (tables, views, indexes etc) you need in a new database (call it e.g. my_template)
  • To reset your current test-DB, do a DROP DATABASE testdb and then re-create the test database using CREATE DATABASE testdb TEMPLATE my_template

The newly created testdb will have all tables defined in my_template. That is probably a lot faster than deleting all rows.

like image 162
a_horse_with_no_name Avatar answered Sep 30 '22 07:09

a_horse_with_no_name