如何从postgresql中的所有表中删除所有行?

Thi*_*mal 9 postgresql

是否有任何 SQL 查询可以删除 postgresql 中所有表中的所有行?

小智 15

方法 1:创建一个包含一组 sql 语句的文件来截断每个表,然后从文件中执行这些语句。

testdb=# \t
Tuples only is on.
testdb=# \o truncate_all_tables.sql
testdb=# SELECT 'TRUNCATE ' || table_name || ';' FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';
testdb=# \o
testdb=# \t
Tuples only is off.
testdb=# \i truncate_all_tables.sql
TRUNCATE TABLE_NAME CASCADE
TRUNCATE TABLE_NAME CASCADE
TRUNCATE TABLE_NAME CASCADE
TRUNCATE TABLE_NAME CASCADE
TRUNCATE TABLE_NAME CASCADE
Run Code Online (Sandbox Code Playgroud)

方法 2:仅使用架构创建数据库转储,重新创建数据库并恢复转储。

# pg_dump -U postgres -v -Fc -s -f testdb.dump testdb
# dropdb -U postgres testdb
# createdb -U postgres testdb
# pg_restore -U postgres -v -d testdb testdb.dump
Run Code Online (Sandbox Code Playgroud)