Languages
[Edit]
EN

Postgres - drop all public tables in schema

7 points
Created by:
Root-ssh
103710

In this short article, we would like to show how to remove all public tables from the Postgres database.

The main idea of the solution in this article is to generate DROP TABLE ... queries for all public tables and call each query manually.

Steps:

1. Generate DROP TABLE ... queries calling database:

SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;' 
FROM pg_tables
WHERE schemaname='public';

Example result:

DROP TABLE IF EXISTS "tasks" CASCADE;
DROP TABLE IF EXISTS "users" CASCADE;

Example screenshot:

Dropping all tables query - Postgres.
Dropping all tables query - Postgres.

2. Execute generated drop queries:

DROP TABLE IF EXISTS "tasks" CASCADE;
DROP TABLE IF EXISTS "users" CASCADE;

Example output:

/* Affected rows: 0  Found rows: 0  Warnings: 0  Duration for 2 queries: 0.000 sec. (+ 0.010 sec. network) */
DONE: database is empty!
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join