SoFunction
Updated on 2025-03-03

Postgresql operation to reset the sequence start value

I won't say much nonsense, let's just read the code~

-- Sequence reset to1000
alter sequence sequence_name restart with 1000
-- verify
SELECT nextval('sequence_name');

Supplement: postgresql reset sequence and autoincrement primary key

1. Problem background

Several test data were inserted into the data table, and then manually deleted it, resulting in a primary key conflict when inserting data later:

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

Even if INSERT IGNORE or REPLACE INTO is used, it still reports an error, so I want to reset the self-increment sequence and primary key.

2. Solution

2.1 Method 1

(1) Reset the start value of the sequence to 1

alter sequence xxx_id_seq restart with 1

(2) View the current sequence

SELECT nextval('xxx_id_seq ');

(3) Reset the auto-increment key

TRUNCATE tableName RESTART IDENTITY;

2.2 Method 2

(1) Clear all records

TRUNCATE tablename questions CASCADE;

(2) Clear all records and the index number starts from 0

TRUNCATE tablename questions RESTART IDENTITY CASCADE;

2.3 Method Three

It may also be caused by the inconsistency between the primary key and the sequence, so you can change the sequence number to the maximum primary key without resetting the sequence starting value and primary key.

select setval('xxx_id_seq', max(id)) from tableName;

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.