SoFunction
Updated on 2025-04-08

Postgresql modify self-increasing sequence operations

In mysql, the way to achieve id autoincrement is to add an auto_increment flag, while in pgsql, id autoincrement is through the sequence SEQUENCE.

When creating a table, set the self-increment sequence to:

CREATE TABLE "config" (
 "id" int4 NOT NULL DEFAULT nextval('config_id_seq'::regclass),
 ...
};

If you need to modify the sequence after creating the table, such as:

----Uninstall before deletion id Dependence on this sequence
ALTER TABLE tablename ALTER COLUMN id SET DEFAULT null;
DROP SEQUENCE IF EXISTS sequence_name;
---- id_max Right now id Current maximum,Can be written as1,Available “SELECT MAX(id) FROM tablename” get
CREATE SEQUENCE sequence_name START WITH id_max;
ALTER TABLE tablename ALTER COLUMN id SET DEFAULT nextval('sequence_name'::regclass);

Supplement: PostgreSQL sequence addition, deletion and modification

Create a sequence

CREATE SEQUENCE if not exists test_mergetable_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 999999999
START 1
CACHE 1;
//or:create sequence if not exists test_mergetable_id_seq increment by 1 minvalue 1 no maxvalue start with 1; 

Specify the sequence (specify the created sequence to the primary key of the table)

alter table test_mergetable alter column "i_id" set default nextval('test_mergetable_id_seq');

Set the sequence self-growth starts at the current maximum

SELECT setval('test_mergetable_id_seq', (SELECT MAX(i_id) FROM test_mergetable));

alter sequence test_mergetable_id_seq start with 12;

Delete the sequence

drop sequence IF EXISTS test_mergetable_id_seq

View the sequence

SELECT nextval('test_mergetable_id_seq')

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.