I have a Postgres database that I created with a Django application. When I transferred it over, it never reindexed anything and it gives me errors trying to do this. It seems as if there are lots of tables that have this issue. Is there a way I can use this code that I found on another question and use it for all sequences and tables?

SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1)

The code you display is not related to "reindexing". (Compare: REINDEX). It gets a sequence behind a serial column (or IDENTITY column in Postgres 10 or later) back in sync - by setting it to the maximum existing ID. Consider this query instead:

SELECT setval('tablename_id_seq', max(id)) FROM tablename;

No subselect needed, no off-by-one error to fix (the next value returned from the sequence is incremented by default).
Or, better yet, you don't have to provide the name of the sequence:

SELECT setval(pg_get_serial_sequence('tablename', 'id'), max(id)) FROM tablename;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.