Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter table column for primary key and identity

I have table created and want to alter that table. I want to add a primary key and identity(1,1).

I can apply primary key but applying identity gives error. Is anything missing?

ALTER TABLE MyTable ADD PRIMARY KEY (Id)

How can I add identity as well with primary key?

like image 716
k-s Avatar asked Aug 10 '12 07:08

k-s


People also ask

Can we make identity column as primary key?

In many cases an identity column is used as a primary key; however, this is not always the case. It is a common misconception that an identity column will enforce uniqueness; however, this is not the case. If you want to enforce uniqueness on the column you must include the appropriate constraint too.

Can we modify an existing table column to add the identity property?

You can add and drop the generated or identity property of a column in a table using the ALTER COLUMN clause in the ALTER TABLE statement.

How do I change an existing column to an identity in Oracle?

Sadly you can't alter an existing column to become an identity. This assigns a value from the sequence to all existing rows. The method for this is non-deterministic.


1 Answers

You cannot alter the definition of an existing column in the database, to add the IDENTITY property (nor to remove it). You have to create a new column with the IDENTITY property:

ALTER TABLE MyTable ADD NewID int IDENTITY(1,1) not null

Unfortunately, you're not then able to assign the old ID values to this new column. If you want to assign the ID values, and then let IDENTITY take over, you'd be better off creating a new table with the structure you want, then importing data from the old table (you can use IDENTITY_INSERT to assign values to the IDENTITY column).

You would then drop the old table and rename the new table, if required.

like image 88
Damien_The_Unbeliever Avatar answered Feb 04 '23 06:02

Damien_The_Unbeliever