Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: alter the columns of my PRIMARY KEY

Tags:

database

mysql

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?

like image 735
StackOverflowNewbie Avatar asked Jul 19 '11 00:07

StackOverflowNewbie


People also ask

Can I update the primary key column in MySQL?

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.

Can you alter a primary key?

You can modify the primary key of a table by changing the column order, index name, clustered option, or fill factor.

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

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`)
)
like image 56
Bohemian Avatar answered Sep 25 '22 13:09

Bohemian


  1. Remove the old PK ALTER TABLE table_name DROP PRIMARY KEY
  2. Add the new PK ALTER TABLE table_name ADD PRIMARY KEY (Id)
like image 33
Mike Avatar answered Sep 25 '22 13:09

Mike