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, ev
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);
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
This just happened to me and my team. We are using Postgres 12 and were doing some processing using Apache NiFi. It got stuck.
We did a:
systemctl status postgresql-12
Then I noticed a lot of "TRUNCATED Waiting" I proceeded to try and reload Postgres without success and then just killed each of the stuck processes.
It worked after that and we were able to restart the jobs and only took less than a seccond.
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.