How to detect query which holds the lock in Postgres?

前端 未结 5 2055
醉话见心
醉话见心 2020-12-07 08:51

I want to track mutual locks in postgres constantly.

I came across Locks Monitoring article and tried to run the following query:

SELECT bl.pid     A         


        
5条回答
  •  猫巷女王i
    2020-12-07 09:17

    Postgres has a very rich system catalog exposed via SQL tables. PG's statistics collector is a subsystem that supports collection and reporting of information about server activity.

    Now to figure out the blocking PIDs you can simply query pg_stat_activity.

    select pg_blocking_pids(pid) as blocked_by
    from pg_stat_activity
    where cardinality(pg_blocking_pids(pid)) > 0;
    

    To, get the query corresponding to the blocking PID, you can self-join or use it as a where clause in a subquery.

    SELECT query
    FROM pg_stat_activity
    WHERE pid IN (select unnest(pg_blocking_pids(pid)) as blocked_by from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0);
    

    Note: Since pg_blocking_pids(pid) returns an Integer[], so you need to unnest it before you use it in a WHERE pid IN clause.

    Hunting for slow queries can be tedious sometimes, so have patience. Happy hunting.

提交回复
热议问题