Postgres manually alter sequence

前端 未结 5 1536
盖世英雄少女心
盖世英雄少女心 2020-11-28 18:56

I\'m trying to set a sequence to a specific value.

SELECT setval(\'payments_id_seq\'), 21, true

This gives an error:

5条回答
  •  抹茶落季
    2020-11-28 19:01

    Use select setval('payments_id_seq', 21, true);

    setval contains 3 parameters:

    • 1st parameter is sequence_name
    • 2nd parameter is Next nextval
    • 3rd parameter is optional.

    The use of true or false in 3rd parameter of setval is as follows:

    SELECT setval('payments_id_seq', 21);           // Next nextval will return 22
    SELECT setval('payments_id_seq', 21, true);     // Same as above 
    SELECT setval('payments_id_seq', 21, false);    // Next nextval will return 21
    

    The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:

    SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;
    

    where table_name is the name of the table, id is the primary key of the table

提交回复
热议问题