Question

I know I can list all sequences with this:

SELECT * FROM information_schema.sequences;

But I need to know by which table this sequence is used.

The reason I want to do this is to find out which sequences of PRIMARY KEYs are not in the default format of table_name_id_seq

Is this possible?

Note: My PostgreSQL version is 11.5.

Was it helpful?

Solution

The information is stored in pg_depend:

SELECT t.oid::regclass AS table_name,
       a.attname AS column_name,
       s.relname AS sequence_name
FROM pg_class AS t
   JOIN pg_attribute AS a
      ON a.attrelid = t.oid
   JOIN pg_depend AS d
      ON d.refobjid = t.oid
         AND d.refobjsubid = a.attnum
   JOIN pg_class AS s
      ON s.oid = d.objid
WHERE d.classid = 'pg_catalog.pg_class'::regclass
  AND d.refclassid = 'pg_catalog.pg_class'::regclass
  AND d.deptype = 'i'
  AND t.relkind IN ('r', 'P')
  AND s.relkind = 'S';
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top