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?
With PostgreSQL 8.4 or newer there is no need to specify the WITH 1
anymore. The start value that was recorded by CREATE SEQUENCE
or last set by ALTER SEQUENCE START WITH
will be used (most probably this will be 1).
Reset the sequence:
ALTER SEQUENCE seq RESTART;
Then update the table's ID column:
UPDATE foo SET id = DEFAULT;
Source: PostgreSQL Docs
The best way to reset a sequence to start back with number 1 is to execute the following:
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
If you are using pgAdmin3, expand 'Sequences,' right click on a sequence, go to 'Properties,' and in the 'Definition' tab change 'Current value' to whatever value you want. There is no need for a query.
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;
Just for simplifying and clarifying the proper usage of ALTER SEQUENCE and SELECT setval for resetting the sequence:
ALTER SEQUENCE sequence_name RESTART WITH 1;
is equivalent to
SELECT setval('sequence_name', 1, FALSE);
Either of the statements may be used to reset the sequence and you can get the next value by nextval('sequence_name') as stated here also:
nextval('sequence_name')
To retain order of the rows:
UPDATE thetable SET rowid=col_serial FROM
(SELECT rowid, row_number() OVER ( ORDER BY lngid) AS col_serial FROM thetable ORDER BY lngid) AS t1
WHERE thetable.rowid=t1.rowid;