views:

283

answers:

2

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 and Time

Can you guide me as to how to change the primary Key

+3  A: 

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.

Peter Lang
+3  A: 

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;
Tony Andrews
my primary key is a combination of city_id and buildtimeso what should write in place of my_pk
Mohit BAnsal
I was using "my_pk" as the name of the primary key constraint. You should know what the name of the constraint is, but if you don't you can use "alter table my_table drop primary key;" instead.
Tony Andrews
One does not need to drop dependent foreign keys that reference my_table.my_pk if one drops it using the CASCADE clause. Also, just dropping the constraint may keep an index around you may or may not want; use the KEEP | DROP INDEX clause to as appropriate.Oddly enough, all of this is documented in the Oracle Database SQL Reference. http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_3001.htm#i2103845
Adam Musch