Jun27

PostgreSQL: Quickly empty tables

If you have ever run into trouble while removing contents from large tables (because of foreign keys, relations, their huge size, or whatsoever), this is the ultimate solution: TRUNCATE.

truncate table audit cascade;

In my case, this resulted in truncation of all tables (since every table has a reference to the audit table). If you wish to perform the truncation only when there are no references at all, use the restrict keyword (or none at all, since it is the default):

truncate table audit restrict;

In case you are too lazy to read the documentation linked above, here is the most interesting part:

TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables.

The most amazing thing about this command is its’ speed. I have had to insert and remove data from a database quite often (database migration tests - migrate, see if correct, clean database, do it once again, and so on and so forth) and without truncate the only feasible solution was recreating the tables each time (the delete statement took ages). Now cleaning all tables works like a charm.


No Responses to “PostgreSQL: Quickly empty tables”

You can leave a response, or trackback from your own site.


Leave a Reply

About

Impessa LTD provides IT solutions tailored to business needs. Impessa specializes in providing web and software development services including solution integration and offshore IT outsourcing across the globe.