I have a table with the following primary key:
PRIMARY KEY (`Id`,`InputOutputConfigurationServerAccountId`,`Identifier`)
I want to modify this so that the PK is only the Id
column. How do I do this?
To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key. Note You must be logged in to the database using a database name before you can add a primary key or conduct any other referential integrity (RI) operation.
You can modify the primary key of a table by changing the column order, index name, clustered option, or fill factor.
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.
The problem seems to be that you have Id
defined as auto_increment
. You need to first change it to just plain int, them make the changes, then turn it back to auto_increment.
Try this:
ALTER TABLE SO1 MODIFY COLUMN ID INT;
ALTER TABLE SO1 DROP PRIMARY KEY;
ALTER TABLE SO1 ADD PRIMARY KEY (id);
ALTER TABLE SO1 MODIFY COLUMN ID INT AUTO_INCREMENT;
Here's a test of the above (btw, I got the error you mentioned in your comment on other answer if I didn't first modify the column):
drop table if exists SO1;
create table SO1 (
id int auto_increment,
InputOutputConfigurationServerAccountId int,
Identifier int,
PRIMARY KEY (`Id`,`InputOutputConfigurationServerAccountId`,`Identifier`)
);
ALTER TABLE SO1 MODIFY COLUMN ID INT;
ALTER TABLE SO1 DROP PRIMARY KEY;
ALTER TABLE SO1 ADD PRIMARY KEY (id);
ALTER TABLE SO1 MODIFY COLUMN ID INT AUTO_INCREMENT;
show create table SO1;
All executed OK. Final Output:
CREATE TABLE `SO1` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`InputOutputConfigurationServerAccountId` int(11) NOT NULL DEFAULT '0',
`Identifier` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
)
ALTER TABLE table_name DROP PRIMARY KEY
ALTER TABLE table_name ADD PRIMARY KEY (Id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With