I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(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-keyid(surrogate) column. The following command should be sufficient in recent versions of PostgreSQL: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:
Again, in recent versions of Postgres this is roughly equivalent to the single command above.