Sequence does not reset after truncating the table

前端 未结 6 1827
礼貌的吻别
礼貌的吻别 2021-01-31 16:18

I use SELECT lastval() to get wrong serial id after truncated the table.

when I truncate the table, I use SELECT lastval(), I got the wrong ID/

相关标签:
6条回答
  • 2021-01-31 16:30

    Try this:

    TRUNCATE TABLE table_name RESTART IDENTITY CASCADE;

    0 讨论(0)
  • 2021-01-31 16:34

    Check the next

    ALTER SEQUENCE sequence_name RESTART WITH 1;
    
    0 讨论(0)
  • 2021-01-31 16:43

    Try

    TRUNCATE TABLE table_name 
    RESTART IDENTITY;
    

    It will

    Automatically restart sequences owned by columns of the truncated table(s).

    Details here: TRUNCATE

    0 讨论(0)
  • 2021-01-31 16:46

    Following is the standard way to reset sequence:

    truncate table table_name restart identity;
    

    but in some version & platform, it's syntax error,

    in that case, you can truncate without reset sequence, and alter the sequence with another sql, try this:

    truncate table table_name;
    alter sequence seq_name start 1;
    
    0 讨论(0)
  • 2021-01-31 16:48

    The best way to reset a sequence to start back with number 1 is to execute the following after you have successfully truncate it:

    ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1
    

    So, for example for the users table it would be:

    ALTER SEQUENCE users_id_seq RESTART WITH 1
    
    0 讨论(0)
  • 2021-01-31 16:51

    If you want to reset the sequence then:

    setval('sequence_name', 0)
    

    To list the existent sequence names issue a \ds at the psql prompt.

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