Re: alter existing table column with primary key to auto-increment

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Rounak Jain <rounakjainis(at)gmail(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: alter existing table column with primary key to auto-increment
Date: 2017-02-05 17:40:35
Message-ID: 13322.1486316435@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Rounak Jain <rounakjainis(at)gmail(dot)com> writes:
> I am just starting with psql.
> I have created surrogate id keys in some tables.
> They are primary keys.
> I want to add auto-increment to them.

You want to read the definition of serial types here:

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

If you already have the column, you can make the sequence object, add the
default expression (ALTER TABLE ... ALTER COLUMN ... SET DEFAULT ...
I think is the right syntax) and do the ALTER OWNED BY if you'd like the
sequence to go away if the column is dropped.

If there's data in the column already, you probably also need to tweak the
current value of the sequence.

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Kranenburg, Roger 2017-02-06 18:52:17 pgAdmin4 1.1 Import Dialog does nothing
Previous Message Rounak Jain 2017-02-05 10:57:44 Re: alter existing table column with primary key to auto-increment