Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

Blocking and Long-Running Queries

Direct answer

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

When to use this

Use it when queries hang or the database seems frozen.

First 30 seconds

1. PG: SELECT pid,pg_blocking_pids(pid),state,query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid))>0;.

2. MySQL: sys.innodb_lock_waits.

3. SQL Server: sys.dm_exec_requests blocking_session_id.

4. Identify the head blocker's query and age.

5. Cancel/kill after confirmation; fix cause.

Operational verification

session holds lock → others wait → chain → head blocker

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
Scope / prerequisiteUse it when queries hang or the database seems frozen.
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 How to verify Verify boundary

Identify the application code that left the transaction open. Set statement or idle-in-transaction timeouts to limit damage.

Step 2 Finding blockers Verify boundary
-- PostgreSQL
SELECT pid, pg_blocking_pids(pid) AS blocked_by, state, now()-query_start AS age, query
FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
-- MySQL
SELECT * FROM sys.innodb_lock_waits\G
-- SQL Server
SELECT session_id, blocking_session_id, wait_type, wait_time FROM sys.dm_exec_requests WHERE blocking_session_id <> 0;

Find the head blocker (often an idle-in-transaction session), fix the application, and only then terminate (pg_terminate_backend, KILL). Set idle_in_transaction_session_timeout in PostgreSQL.

Step 3 Common failures Narrow the fault

Killing waiters instead of the blocker changes nothing. Terminating a large write causes a long rollback. Schema changes wait behind long queries and block everyone behind them.

Key points

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).

Key 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
ReferenceWhat it is1 section · depth on demand

How it works

Lock waits form chains: one blocker can stall many sessions. Missing indexes make updates lock more rows. Long reports on the primary hold snapshots that block cleanup.

ReferenceImportant terms & boundaries2 sections · depth on demand

In depth

Find the head of the blocking chain

-- PostgreSQL: who blocks whom
SELECT a.pid, pg_blocking_pids(a.pid) AS blocked_by, a.state,
       now() - a.xact_start AS xact_age, left(a.query, 70) AS query
FROM pg_stat_activity a
WHERE a.pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)
   OR cardinality(pg_blocking_pids(a.pid)) > 0
ORDER BY xact_age DESC;

The session that appears as a blocker but is not blocked itself is the head. Often it is idle in transaction: an application started a transaction, did a write and never committed.

-- MySQL 8: sys schema view
SELECT waiting_pid, waiting_query, blocking_pid, blocking_query, wait_age
FROM sys.innodb_lock_waits;
-- SQL Server
SELECT session_id, blocking_session_id, wait_type, wait_time, command
FROM sys.dm_exec_requests WHERE blocking_session_id <> 0;

Ending it safely

ActionPostgreSQLMySQLSQL Server
Cancel the current querypg_cancel_backend(pid)KILL QUERY id—
End the session (rolls back)pg_terminate_backend(pid)KILL idKILL spid

Terminating a session that has written a lot starts a rollback that can take about as long as the work done; check before killing a large batch.

Guardrails

ALTER ROLE shop_app SET idle_in_transaction_session_timeout = '60s';
ALTER ROLE shop_app SET statement_timeout = '30s';
ALTER ROLE reporting SET statement_timeout = '10min';
SET lock_timeout = '5s';           -- in migrations, so DDL does not stall everyone

Long reports belong on a replica; on the primary they hold snapshots that block vacuum (PostgreSQL) or purge (InnoDB history list).

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Common mistakes

  • Killing sessions without finding the blocker.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
blocking and long-running queriesdatabase blocking sessionidle in transaction
Confirmation

Confirm action

Continue?