Complete the code to check for deadlocks using PostgreSQL system views.
SELECT * FROM pg_locks WHERE [1] = true;The pg_locks view shows lock information. The granted column indicates if the lock is currently held. Checking for granted locks helps identify potential deadlocks.
Complete the query to find transactions waiting for locks in PostgreSQL.
SELECT pid, blocked_pid FROM pg_blocking_pids([1]);The function pg_blocking_pids(pid) returns the process IDs blocking the given process ID. So, you need to pass a pid to check who is blocking it.
Fix the error in the query to detect deadlocks by joining pg_locks and pg_stat_activity.
SELECT a.pid, a.query, l.locktype FROM pg_stat_activity a JOIN pg_locks l ON a.[1] = l.pid WHERE NOT l.[2];
The correct join is on pid columns from both views. The condition NOT l.granted filters locks that are waiting, which helps detect deadlocks.
Fill both blanks to write a query that detects deadlocks by checking waiting and granted locks.
SELECT blocked_locks.pid AS blocked_pid, blocking_locks.pid AS blocking_pid FROM pg_locks blocked_locks JOIN pg_locks blocking_locks ON blocked_locks.[1] = blocking_locks.[2] WHERE NOT blocked_locks.granted AND blocking_locks.granted;
Deadlocks often occur when transactions wait on the same transactionid. Joining on transactionid helps find blocking and blocked transactions.
Fill all three blanks to write a query that prevents deadlocks by ordering lock acquisition.
BEGIN; LOCK TABLE [1] IN [2] MODE; LOCK TABLE [3] IN SHARE MODE; COMMIT;
To prevent deadlocks, acquire locks in a consistent order. Here, table_a is locked first in EXCLUSIVE mode, then table_b in SHARE mode.