Pcornel
Databases · Database Troubleshooting

Blocking and Long-Running Queries

Cheat sheet · https://pcornel.dk/topic.php?topic=6195

Back to the Topic

Answer

Blocking happens when one session holds locks another needs; long-running queries hold resources and can block writes, vacuum or replication.

Remember

Find the head blocker, not the victims. Ask before killing — the blocker may be a migration or batch. Fix the root cause (long transaction, missing index, lock order).

First checks

  • SELECT pid,pg_blocking_pids(pid),state,query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid))>0; — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version

Verify in this order

session holds lock → others wait → chain → head blocker

Where it usually breaks

Killing waiters instead of the blocker changes nothing.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=6195

Confirmation

Confirm action

Continue?