pg_stat_database Counts Deadlocks
deadlocks in pg_stat_database is a per-database cumulative counter since the last stats reset; pair it with pg_blocking_pids for the live picture.
Code
-- deadlocks 是按库累计的计数器:自上次统计重置后一直累加
SELECT
datname,
xact_commit,
xact_rollback,
deadlocks,
stats_reset
FROM pg_stat_database
WHERE datname = current_database();
-- 它记录历史;正在等谁要用 pg_stat_activity 的 wait_event_type='Lock'
SELECT count(*) AS blocking_now
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
-- 死锁报错带 SQLSTATE 40P01;deadlock_timeout 控制检测前的等待时长
SELECT current_setting('deadlock_timeout') AS detection_wait;
-- 压测窗口需要归零重测时按库重置(需要相应权限):重置当前库全部统计
SELECT pg_stat_reset();
-- 重置后 deadlocks 从 0 重新累计,stats_reset 记录重置时刻
SELECT datname, deadlocks, stats_reset
FROM pg_stat_database
WHERE datname = current_database();What the code does
What runs here is SELECT — pg_stat_database and pg_stat_activity are the objects involved.
Mechanically, the statements are built from: a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation.
Applying it
Point it at the pg_stat_database table.
Statements that matter
SELECT
datname,
xact_commit,
xact_rollback,
deadlocks,
stats_reset
FROM pg_stat_database
WHERE datname = current_database();
SELECT datname, deadlocks, stats_reset
FROM pg_stat_database
WHERE datname = current_database();
SELECT count(*) AS blocking_now
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
Interactive Tools for This Topic
SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- What are the relations in play here?
- `pg_stat_database`, `pg_stat_activity`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.