1

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)

2 Answers 2

8

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 with setval(). Consider 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). But it fails for empty tables. To also cover that corner case:

SELECT setval('tablename_id_seq'
            , COALESCE(max(id) + 1, 1)
            , false)
FROM   tablename;

Or better yet, without providing the sequence name:

SELECT setval(pg_get_serial_sequence('tablename', 'id')
            , COALESCE(max(id) + 1, 1)
            , false)
FROM   tablename;

See:

2
1

In addition to the @Erwin Brandstetter's, I think the max id should be +1.

SELECT setval(pg_get_serial_sequence('tablename', 'id'), max(id) + 1) FROM tablename;
1
  • setval() has an optional 3rd parameter to set the is_called flag - defaulting to true. So the given number is incremented automatically, not need for + 1 in your call. Commented Mar 6, 2022 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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