I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?
相关问题
- Django distinct is not working
- PostgreSQL: left outer join syntax
- Connecting Python to a Heroku PostgreSQL DB?
- PostgreSQL - Deleting data that are older than an
- Does PLV8 support making http calls to other serve
相关文章
- postgresql 关于使用between and 中是字符串的问题
- postgresql 月份差计算问题
- Using boolean expression in order by clause
- Table valued Parameter Equivalent in Postgresql
- in redshift postgresql can I skip columns with the
- Oracle equivalent of PostgreSQL INSERT…RETURNING *
- Max Size of SQL Server Auto-Identity Field
- how to set H2 primary key id to auto_increment?
To use an identity column in v10,
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/.
(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.
This is all you need to:
id
columnCredit is given to @resnyanskiy who gave this answer in a comment.
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.