Search code examples
sqlpostgresqldatabase-sequence

How to get all the sequences and columns to which sequence is applied using single query


I want to get all the sequences created, tables and columns to which that sequence is applied in a database using a single query in PostgreSQL. Any direct or indirect method is helpful.


Solution

  • SELECT t.relname as related_table, a.attname as related_column,s.relname as sequence_name 
    FROM pg_class s 
       JOIN pg_depend d ON d.objid = s.oid 
       JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid 
       JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum) 
       JOIN pg_namespace n ON n.oid = s.relnamespace 
    WHERE s.relkind     = 'S' 
    AND n.nspname = 'public'
    

    i found the above query which will return list of tables, columns and related sequences.

    source: http://www.dbforums.com/showthread.php?1667561-How-to-list-sequences-and-the-columns-by-SQL