Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Primary Key in MySQL

People also ask

Can we remove primary key in MySQL?

You can drop a primary key in MySQL using the ALTER TABLE statement.

How do I delete a key in MySQL?

To drop a non-primary key index, use the DROP INDEX command: DROP INDEX index_name ON table_name; The syntax requires the table name to be specified because MySQL allows index names to be reused on multiple tables.


Without an index, maintaining an autoincrement column becomes too expensive, that's why MySQL requires an autoincrement column to be a leftmost part of an index.

You should remove the autoincrement property before dropping the key:

ALTER TABLE user_customer_permission MODIFY id INT NOT NULL;
ALTER TABLE user_customer_permission DROP PRIMARY KEY;

Note that you have a composite PRIMARY KEY which covers all three columns and id is not guaranteed to be unique.

If it happens to be unique, you can make it to be a PRIMARY KEY and AUTO_INCREMENT again:

ALTER TABLE user_customer_permission MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT;

One Line:

ALTER TABLE  `user_customer_permission` DROP PRIMARY KEY , ADD PRIMARY KEY (  `id` )

You will also not lose the auto-increment and have to re-add it which could have side-effects.


I believe @Quassnoi has answered your direct question.

Just a side note, maybe this is just some awkward wording on your part, but you seem to be under the impression that you have three primary keys, one on each field.

This is not the case. By definition, you can only have one primary key. What you have here is a primary key that is a composite of three fields.

Thus, you cannot "drop the primary key on a column", you can drop the primary key, or not drop the primary key.

If you want a primary key that only includes one column, you can drop the existing primary key on 3 columns and create a new primary key on 1 column.


ALTER TABLE `user_customer_permission` MODIFY `id` INT;
ALTER TABLE `user_customer_permission` DROP PRIMARY KEY;

In case you have composite primary key, do like this- ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);


"if you restore the primary key, you sure may revert it back to AUTO_INCREMENT"

There should be no question of whether or not it is desirable to "restore the PK property" and "restore the autoincrement property" of the ID column.

Given that it WAS an autoincrement in the prior definition of the table, it is quite likely that there exists some program that inserts into this table without providing an ID value (because the ID column is autoincrement anyway).

Any such program's operation will break by not restoring the autoincrement property.


First modify the column to remove the auto_increment field like this: alter table user_customer_permission modify column id int;

Next, drop the primary key. alter table user_customer_permission drop primary key;