How to reset the sequence for IDs on PostgreSQL tables

django, postgresql

Solution

Run sqlsequencereset and it'll print all the reset commands you need.

Problem

I recently imported a lot of data from an old database into a new Postgresql database as the basis for models in a new Django site. I used the IDs from the old database (as rows in various tables refer to each other), but they aren't all sequential - there are often large gaps. I've noticed that when I add a new object via the Django app, then it has been using IDs starting from 1, which hasn't been a problem so far as there were no rows with very low IDs. But once it reaches the first row of legacy data, then postgres obviously complains: ``` ERROR: duplicate key value violates unique constraint "django_comments_pkey" DETAIL: Key (id)=(25) already exists. ``` Looking at the table descriptions I'm guessing I need to reset some kind of sequence on each table: ``` Table "public.django_comments" Column | Type | Modifiers -----------------+--------------------------+-------------------------------------------------------------- id | integer | not null default nextval('django_comments_id_seq'::regclass) ... ``` What do I need to do to reset that sequence, so that new rows are added with IDs higher than the current maximum ID?

Original source