Databases
sql
Advanced
Deadlock Detection and Prevention
Query Postgres lock waiters and identify deadlock candidates before they occur.
sql
-- Active lock waits
SELECT
blocked.pid,
blocked.query AS blocked_query,
blocking.pid AS blocking_pid,
blocking.query AS blocking_query
FROM pg_stat_activity AS blocked
JOIN pg_stat_activity AS blocking
ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;
-- Kill a blocking query
SELECT pg_terminate_backend(42);
Prerequisites
- PostgreSQL >= 9.6
Pro Tips
- → Always acquire locks in the same order across transactions to prevent deadlocks.
Commercial Licensing
Acquire a production access token or template license for enterprise deployment.
Module Info
- Language
- sql
- Level
- Advanced
- Read time
- 4 min
- Published
- Jul 2026
- License
- Commercial License
Newsletter
New modules every week, directly to your inbox.
Similar Modules
MySQL Replication Status Check
Script to check MySQL/MariaDB replication lag and alert if it exceeds threshold.
sql
·
Intermediate
DB Connection Pool Monitor
Query to check active connections, idle connections and pool usage in PostgreSQL.
sql
·
Intermediate
Cursor-based Pagination Query
Implement cursor-based (keyset) pagination in SQL — faster than OFFSET for large tables.
sql
·
Intermediate