0

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")

4
  • Note that serial is discouraged when using a current Postgres version in favor of identity columns. Commented Aug 27, 2020 at 12:25
  • Oh, thanks for warning. What's the best approach to create auto incremented PKs? Commented Aug 27, 2020 at 12:27
  • Has your table already have a PK? Commented Aug 27, 2020 at 12:47
  • No, there is a column named Id but not PK yet. Commented Aug 27, 2020 at 12:58

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.