问题
In postgres 9.2 (CentOS), TRUNCATE TABLE command occasionally took a really long time to run. One time, it took more than 1.5 hours to truncate a table with 100K records, even longer in other cases. This problem also happened when I used pgAdmin to truncate table. What is the possible cause? and how to improve the truncation performance?
There is 16GB of memory on the server and shared_buffers = 1536MB
回答1:
TRUNCATE
has to flush shared_buffers
for the table being truncated, and it has to unlink the old file, which can be slow on file systems with slow deletion like ext3
.
1.5 hours is pretty extreme though, as we're usually talking seconds at most. It is highly likely that you have other sessions holding locks on the table that prevent the TRUNCATE
from proceeding. See pg_catalog.pg_locks
and pg_catalog.pg_stat_activity
.
The PostgreSQL wiki article on lock monitoring should be useful.
See also: Postgresql Truncation speed
回答2:
Check if the truncate
was blocked by any query
SELECT
activity.pid,
activity.usename,
activity.query,
blocking.pid AS blocking_id,
blocking.query AS blocking_query
FROM pg_stat_activity AS activity
JOIN pg_stat_activity AS blocking ON blocking.pid = ANY(pg_blocking_pids(activity.pid));
If necessary terminate it
SELECT pg_terminate_backend(PID);
回答3:
Try to disconnect all other connections to the database. It took me forever to truncate 58000 records.
After I disconnected my postgres database from PyCharm DB Navigator, dev server etc took 118 msec total.
来源:https://stackoverflow.com/questions/19936204/postgres-truncate-is-slow