I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?
5 Answers
(Updated - Thanks to the people who commented)
Modern Versions of PostgreSQL
Suppose you have a table named test1
, to which you want to add an auto-incrementing, primary-key id
(surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
Older Versions of PostgreSQL
In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:
ALTER TABLE test1 ADD COLUMN id INTEGER;
CREATE SEQUENCE test_id_seq OWNED BY test1.id;
ALTER TABLE test1 ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
UPDATE test1 SET id = nextval('test_id_seq');
Again, in recent versions of Postgres this is roughly equivalent to the single command above.
-
4I am using ORACLE, so sharing it might be useful for ORACLE guys In ORACLE : ALTER TABLE TEST1 ADD ID NUMBER; UPDATE TEST1 SET ID = TEST1_SEQ.NEXTVAL; ALTER TABLE TEST1 ADD PRIMARY KEY(ID); create a Sequence TEST1_SEQ before executing UPDATE statement– msbyuvaJun 22, 2011 at 20:19
-
1Further to @resnyanskiy's comment, this will work even when there's data in the table. IDs are populated and not null constraint is set. The entire answer can be replaced by the line in that comment.– SynessoMay 4, 2015 at 0:32
-
1@EricWang Thanks, Eric, you're right - I believe that this didn't work some versions (years) ago, but I'm not sure. Turned the answer into community-wiki.– leonbloyMay 16, 2016 at 14:10
-
3When using the
ALTER TABLE <table> ADD COLUMN id SERIAL PRIMARY KEY
, how can you specify theid
to bebigint
? Jun 4, 2020 at 7:49 -
3
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
- Add the
id
column - Populate it with a sequence from 1 to count(*).
- Set it as primary key / not null.
Credit is given to @resnyanskiy who gave this answer in a comment.
-
3This should be marked as answer, and the answer should belong to @resnyanskiy– EricMay 16, 2016 at 9:50
-
2I had to first drop the pkey and then run this.
ALTER TABLE <table> DROP CONSTRAINT <pkey_name>;
Dec 16, 2019 at 23:29
To use an identity column in v10,
ALTER TABLE test
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;
For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.
For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.
For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.
-
The problem with this solution is that if the table already contains rows then you get an error:
SQL Error [23502]: ERROR: column "id" contains null values
– isapirMar 7, 2018 at 16:30 -
3@isapir: There was a bug in early versions (pg 10 and 10.1) producing this error. It was fixed with pg 10.2. Details here: dba.stackexchange.com/q/200143/3684 May 22, 2018 at 1:04
I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.
ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;
ALTER TABLE test1 ADD id int8 NOT NULL GENERATED ALWAYS AS IDENTITY;
-
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.– Community BotOct 18, 2021 at 6:39
-
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review Oct 18, 2021 at 7:10