简体   繁体   中英

Postgresql add primary key as serial using contraint

I have a table which has an Id column as int but not mentioned as a primary key. Now I want to add primary key constraint as serial. I've seen this question Postgresql 9.4, Make existing primary key as SERIAL however this is using alter table statement while my intention is doing that with constraint. Is there any way to do that like below?

constraint "PK_tablename" serial primary key ("Id")

You can add the constraint and the identity property in a single statement:

alter table the_table
    add constraint pk_the_table primary key (id),
    alter id add generated always as identity;

As you most probably have already data in your table, you need to adjust the sequence used by the identity clause:

select setval(pg_get_serial_sequence('the_table', 'id'), max(id))
from the_table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM