How to reset sequence in postgres and fill id column with new data?

前端 未结 13 2203
星月不相逢
星月不相逢 2020-11-27 10:47

I have a table with over million rows. I need to reset sequence and reassign id column with new values (1, 2, 3, 4... etc...). Is any easy way to do that?

13条回答
  •  天命终不由人
    2020-11-27 11:09

    Just resetting the sequence and updating all rows may cause duplicate id errors. In many cases you have to update all rows twice. First with higher ids to avoid the duplicates, then with the ids you actually want.

    Please avoid to add a fixed amount to all ids (as recommended in other comments). What happens if you have more rows than this fixed amount? Assuming the next value of the sequence is higher than all the ids of the existing rows (you just want to fill the gaps), i would do it like:

    UPDATE table SET id = DEFAULT;
    ALTER SEQUENCE seq RESTART;
    UPDATE table SET id = DEFAULT;
    

提交回复
热议问题