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)
Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633
Lewis Menelaws
  • 111
  • 1
  • 1
  • 4

2 Answers2

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:

Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633
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;
empax
  • 11
  • 1