Add Primary Key Column to PostgreSQL Table
1 min read

Add Primary Key Column to PostgreSQL Table

Add Primary Key Column to PostgreSQL Table

The other day I got a question:

How to add a numeric PK column to an already existent table?

A quick look on the net showed that it is indeed possible to add an auto-incrementing PK to an already existing table (if you don't have already a PK that is!). The code is quite simple too!

The statement:

ALTER TABLE my_schema.table_without_pk ADD COLUMN id BIGSERIAL PRIMARY KEY;

will add an autoincrementing column named id to my table_without_pk.

HTH,

PS: Thanks to a couple of colleagues of mine for asking the question and working together to finding the answer :)