PostgreSQL将自动递增添加到空ID列中

问题描述 投票:0回答:2

我在PostgreSQL中创建表,但是我忘记添加auto increment

如何在Postgres中更改空的Id列以添加auto increment

postgresql identity auto-increment
2个回答
0
投票

您将需要创建该列所拥有的序列并将其设置为默认值。

例如

CREATE TABLE mytable (id int);

CREATE SEQUENCE mytable_id_seq OWNED BY mytable.id;

ALTER TABLE mytable ALTER COLUMN id SET DEFAULT nextval('mytable_id_seq');

0
投票

从Postgres 10开始,建议为此使用identity列。

您可以使用ALTER TABLE将现有的列转换为Identity列:

alter table the_table
  alter id add generated always as identity;

如果表中已经有数据,则需要同步序列:

select setval(pg_get_serial_sequence('the_table', 'id'), (select max(id) from the_table));
© www.soinside.com 2019 - 2024. All rights reserved.