postgresqldatabase-design

Get table and column "owning" a sequence


I can run the following line:

ALTER SEQUENCE seqName OWNED BY table.id;

How can I get the 'owner' set by OWNED BY for a sequence (in this case: table.id)?


Solution

  • Get the "owning" table and column

    ALTER SEQUENCE seqName OWNED BY table.id;
    

    Your ALTER SEQUENCE statement causes an entry in the system catalog pg_depend with the dependency type (deptype) 'a' and a refobjsubid greater than 0, pointing to the attribute number (attnum) in pg_attribute. With that knowledge you can devise a simple query:

    SELECT d.refobjid::regclass, a.attname
    FROM   pg_depend    d
    JOIN   pg_attribute a ON a.attrelid = d.refobjid
                         AND a.attnum   = d.refobjsubid
    WHERE  d.objid = 'public."seqName"'::regclass  -- your sequence here
    AND    d.refobjsubid > 0
    AND    d.classid = 'pg_class'::regclass;
    

    Get the actual "owner" (the role)

    To get the role owning a specific sequence, as requested:

    SELECT c.relname, u.usename 
    FROM   pg_class c
    JOIN   pg_user  u ON u.usesysid  = c.relowner
    WHERE  c.oid = '"seqName"'::regclass;  -- your sequence here