Home  >  Article  >  Database  >  How to Correctly Add a Primary Key to an Existing MySQL Table?

How to Correctly Add a Primary Key to an Existing MySQL Table?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 08:48:03514browse

How to Correctly Add a Primary Key to an Existing MySQL Table?

Adding a Primary Key to a MySQL Table

When attempting to add a primary key to an existing MySQL table using the command:

alter table goods add column `id` int(10) unsigned primary AUTO_INCREMENT;

one might encounter an error. To resolve this, it is necessary to add the PRIMARY KEY keyword explicitly:

alter table goods add column `id` int(10) unsigned PRIMARY KEY AUTO_INCREMENT;

Alternatively, you can add the primary key after adding the column:

ALTER TABLE goods ADD PRIMARY KEY(id)

This ensures that the id column becomes the primary key for the table. By explicitly specifying PRIMARY KEY, you can avoid the confusion that might arise from using the word PRIMARY alone.

The above is the detailed content of How to Correctly Add a Primary Key to an Existing MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn