Home > Database > Mysql Tutorial > body text

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

Susan Sarandon
Release: 2024-10-27 08:48:03
Original
611 people have browsed it

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;
Copy after login

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;
Copy after login

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

ALTER TABLE goods ADD PRIMARY KEY(id)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template