10

I'm trying to take a look at locks that are happening on specific tables in my PostgreSQL database.

I see there's a table called pg_locks

select * from pg_locks;

Which seems to give me a bunch of columns but is it possible to find the relation because I see one of the columns is the relation oid.

What table must I link that to to get the relation name?

TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106

5 Answers5

17

This is Remy's query, adjusted for Postgres 10:

select nspname, relname, l.* 
from pg_locks l 
    join pg_class c on (relation = c.oid) 
    join pg_namespace nsp on (c.relnamespace = nsp.oid)
where pid in (select pid 
              from pg_stat_activity
              where datname = current_database() 
                and query != current_query());
HrkBrkkl
  • 613
  • 5
  • 22
Phil Horder
  • 402
  • 6
  • 13
12

If you just want the contents of pg_locks but with a human-friendly relation name,

select relation::regclass, * from pg_locks;
Chris Chudzicki
  • 630
  • 13
  • 16
8

Try this :

select nspname,relname,l.* from pg_locks l join pg_class c on 
 (relation=c.oid) join pg_namespace nsp on (c.relnamespace=nsp.oid) where 
  pid in (select procpid from pg_stat_activity where 
  datname=current_database() and current_query!=current_query())
Rémy Baron
  • 1,379
  • 8
  • 15
4

Remy Baron's answer is correct I just wanted to post one I came up with as well only because it's more specific to what I need in this case

select pg_class.relname,
       pg_locks.mode
from pg_class,
     pg_locks
where pg_class.oid = pg_locks.relation
and pg_class.relnamespace >= 2200
;
TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106
  • 3
    `pg_class.relnamespace >= 2200` it seems here that `2200` is the "magic" number I was looking for to exclude non-interesting postgres internal locks from the list and return only locks on user-defined tables. I wonder if there's some way to introspect this number from postgres itself? – Anentropic Sep 12 '18 at 20:53
4

The below command will give the list of locks:

select t.relname,l.locktype,page,virtualtransaction,pid,mode,granted 
from pg_locks l, pg_stat_all_tables t where l.relation=t.relid
order by relation asc;
anothernode
  • 5,100
  • 13
  • 43
  • 62
chiru
  • 789
  • 6
  • 5