Change the starting value of a serial - Postgresql

前端 未结 4 1843
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 22:28

I\'ve a little problem with serial : From a file, I filled my database in which I have a client ID (it is a serial and it is my primary key). I have 300 clients so 300 client ID

相关标签:
4条回答
  • 2021-02-03 22:58

    if your Postgresql version is higher than the upper answer, you could try getting serial key with select pg_get_serial_sequence('ingredients', 'id');

    and SELECT adsrc FROM pg_attrdef WHERE adrelid = (SELECT oid FROM pg_class WHERE relname = 'ingredients');

    0 讨论(0)
  • 2021-02-03 23:01

    You can alter a sequence using RESTART WITH to change the current sequence number;

    ALTER SEQUENCE test_seq RESTART WITH 300;
    

    To get the sequence name if you created it using the serial keyword, use

    SELECT adsrc FROM pg_attrdef WHERE adrelid = (SELECT oid FROM pg_class WHERE relname = 'table name goes here'); 
    

    An SQLfiddle to test with.

    0 讨论(0)
  • 2021-02-03 23:02

    PostgreSQL

    ALTER SEQUENCE tablename_columnname_seq RESTART WITH anynumber;
    

    Example:

    ALTER SEQUENCE test_table_rec_id_seq RESTART WITH 4615793;
    
    0 讨论(0)
  • 2021-02-03 23:02

    The solutions above did not work for what I needed.

    I needed a serial id to use as a primary key that started from 1000, rather than 1.

    In order to do this, I created a standard serial column:

    ALTER table my_table ADD COLUMN new_id SERIAL PRIMARY KEY;
    

    and then updated that column:

    UPDATE my_table set new_id = new_id + 1000;
    

    I then joined that table to the table with existing non-consecutive id numbers under 1000.

    0 讨论(0)
提交回复
热议问题