How to reset Postgres SERIAL number

By

Published · Updated

Tagged: Database

Reset a PostgreSQL identity or SERIAL sequence after truncating a test table, and avoid creating duplicate IDs when rows still exist.

When testing a table with a SERIAL field, this number will grow even if you remove all items in the table (like you’d do during testing), so you might insert a value and its id is 15 for example.

This happens because a SERIAL column gets its values from a sequence, a separate counter object. DELETE removes rows but doesn’t touch the sequence:

CREATE TABLE users (id SERIAL PRIMARY KEY, name text);

INSERT INTO users (name) VALUES ('a'), ('b'), ('c');
DELETE FROM users;

INSERT INTO users (name) VALUES ('d') RETURNING id;
-- id = 4

The same is true for identity columns (GENERATED ... AS IDENTITY), which are the SQL-standard way to make an auto-increment column. I explain both in how to define an auto increment primary key in PostgreSQL.

Empty the table and reset the counter

If you want to remove every row from a test table and reset its owned sequence in one operation, use:

TRUNCATE TABLE users RESTART IDENTITY;

The next insert gets id = 1 again. Without RESTART IDENTITY, TRUNCATE keeps the sequence as it is (that’s the default, CONTINUE IDENTITY).

TRUNCATE is destructive and cannot be used when foreign-key references block it unless you deliberately handle those tables too.

If another table points to users, you get this error:

ERROR:  cannot truncate a table referenced in a foreign key constraint
DETAIL:  Table "posts" references "users".
HINT:  Truncate table "posts" at the same time, or use TRUNCATE ... CASCADE.

List both tables in the same command:

TRUNCATE TABLE users, posts RESTART IDENTITY;

TRUNCATE users RESTART IDENTITY CASCADE also works, but it empties every table that references users, and the tables that reference those. Use it only when you know which tables that includes.

TRUNCATE is transaction-safe. If you run it inside a transaction and roll back, both the rows and the sequence go back to where they were.

Find the name of the sequence

A SERIAL column on users.id creates a sequence named users_id_seq by default. If you’re not sure, ask Postgres:

SELECT pg_get_serial_sequence('users', 'id');
-- public.users_id_seq

This works for identity columns too. In psql, \d users also shows the sequence in the column default.

Reset the sequence directly

To reset one known sequence directly:

ALTER SEQUENCE users_id_seq RESTART WITH 1;

RESTART with no value goes back to the sequence’s start value, which is 1 unless you changed it.

For an identity column you can do the same through the table, without knowing the sequence name:

-- posts.id is defined as GENERATED ALWAYS AS IDENTITY
ALTER TABLE posts ALTER COLUMN id RESTART WITH 1;

This form only works on identity columns. On a SERIAL column Postgres answers column "id" of relation "users" is not an identity column, so use ALTER SEQUENCE there.

Do this only when the table is empty. If rows still contain existing IDs, the next insert can collide with one of them.

This is what happens when rows with IDs 1, 2 and 3 are still there:

ERROR:  duplicate key value violates unique constraint "users_pkey"
DETAIL:  Key (id)=(1) already exists.

Continue after the highest ID

When you need the sequence to continue after the current highest ID, use setval():

SELECT setval(
  pg_get_serial_sequence('users', 'id'),
  COALESCE((SELECT MAX(id) FROM users), 1),
  EXISTS (SELECT 1 FROM users)
);

The third argument tells Postgres whether the value was already used:

This is also the fix for the most common sequence problem: you import rows with explicit IDs (from a dump, a CSV or a seed script), and the next normal insert fails with duplicate key value violates unique constraint. The import wrote the IDs but never moved the sequence. Run the setval() query above and inserts work again.

One difference from TRUNCATE: setval() is not undone by a ROLLBACK. The new value is visible to other sessions right away.

Gaps in the IDs are normal

Don’t try to keep the IDs without holes. A sequence never gives the same number twice, even when the insert that took it fails or is rolled back:

BEGIN;
INSERT INTO users (name) VALUES ('k');  -- takes id 5
ROLLBACK;

INSERT INTO users (name) VALUES ('l') RETURNING id;
-- id = 6, 5 is gone

An ID is only an identifier. If you need a gapless counter, like invoice numbers, keep it in a separate table and update it yourself.

Using a GUI

Using TablePlus, you can choose to restart identities when truncating a table. Review the generated SQL before confirming it.

Want me to talk about your product? You can sponsor this site.

Related posts about database: