List all sequences in a Postgres db 8.1 with SQL

后端 未结 19 1708
旧时难觅i
旧时难觅i 2020-12-12 11:30

I\'m converting a db from postgres to mysql.

Since i cannot find a tool that does the trick itself, i\'m going to convert all postgres sequences to autoincrement id

相关标签:
19条回答
  • 2020-12-12 11:46

    The following query gives names of all sequences.

    SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';
    

    Typically a sequence is named as ${table}_id_seq. Simple regex pattern matching will give you the table name.

    To get last value of a sequence use the following query:

    SELECT last_value FROM test_id_seq;
    
    0 讨论(0)
  • 2020-12-12 11:46

    Kind of a hack, but try this:

    select 'select ''' || relname || ''' as sequence, last_value from ' || relname || ' union' FROM pg_catalog.pg_class c WHERE c.relkind IN ('S','');

    Remove the last UNION and execute the result

    0 讨论(0)
  • 2020-12-12 11:47

    Run: psql -E, and then \ds

    0 讨论(0)
  • 2020-12-12 11:47

    after a little bit of pain, i got it.

    the best way to achieve this is to list all tables

    select * from pg_tables where schemaname = '<schema_name>'
    

    and then, for each table, list all columns with attributes

    select * from information_schema.columns where table_name = '<table_name>'
    

    then, for each column, test if it has a sequence

    select pg_get_serial_sequence('<table_name>', '<column_name>')
    

    and then, get the information about this sequence

    select * from <sequence_name>
    
    0 讨论(0)
  • 2020-12-12 11:49

    Note, that starting from PostgreSQL 8.4 you can get all information about sequences used in the database via:

    SELECT * FROM information_schema.sequences;
    

    Since I'm using a higher version of PostgreSQL (9.1), and was searching for same answer high and low, I added this answer for posterity's sake and for future searchers.

    0 讨论(0)
  • 2020-12-12 11:49

    Improvement of the previous answer:

    select string_agg('select sequence_name, last_value from ' || relname, chr(13) || 'union' || chr(13) order by relname) 
    from pg_class where relkind ='S'
    
    0 讨论(0)
提交回复
热议问题