Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Primary Key

I have a table in Oracle which has following schema:

City_ID  Name  State  Country  BuildTime  Time 

When I declared the table my primary key was both City_ID and the BuildTime, but now I want to change the primary key to three columns:

City_ID  BuildTime  Time 

How can I change the primary key?

like image 629
Mohit BAnsal Avatar asked Feb 22 '10 11:02

Mohit BAnsal


People also ask

Can you edit primary key?

Short answer: yes you can.

How do I change the primary key in a column in SQL?

Alter table table_name add primary key (column_name); To change the Primary key column in the SQL Server, follow these steps: Drop already defined primary key. Add a new column as the primary key.


2 Answers

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city DROP CONSTRAINT pk_city;  ALTER TABLE city ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time); 

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

like image 106
Peter Lang Avatar answered Sep 19 '22 03:09

Peter Lang


You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk; alter table my_table add constraint my_pk primary key (city_id, buildtime, time); 

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key; 
like image 27
Tony Andrews Avatar answered Sep 22 '22 03:09

Tony Andrews