Published : 2016-09-10

Schema cleanup

In some cases, for instance in an integration environment, it can be interesting to clean up all entries in your PostgreSQL database. When the number of tables grows and especially when you have built a robust schema based on foreign keys, cleaning it up can be tedious. Fortunately, it is possible to clean up your database by asking PostgreSQL to generate the query that will list the tables of the schema and clean them up. The query below will generate the cleanup query for the tables in the current database under the public schema. It will not be executed; it is only a SQL result as a string.

select 'truncate ' || string_agg(nspname || '.' || relname, ',') || ';' from pg_class join pg_namespace on pg_class.relnamespace = pg_namespace.oid where pg_namespace.nspname = 'public' and relkind='r';

You then only need to run the generated query. Note: If you want to filter on the table names, just filter on the relname field.