Home > Database > Mysql Tutorial > How do I add a primary key to a MySQL table and avoid common errors?

How do I add a primary key to a MySQL table and avoid common errors?

DDD
Release: 2024-10-27 09:15:30
Original
1071 people have browsed it

How do I add a primary key to a MySQL table and avoid common errors?

Adding a Primary Key to a MySQL Table

Adding a primary key to a MySQL table can be accomplished through specific syntax. However, some users may encounter errors when attempting this operation.

How to Add a Primary Key

To add a primary key to a table, use this syntax:

ALTER TABLE [table_name] ADD PRIMARY KEY ([column_name]);
Copy after login

For example, to add a primary key to the goods table with a column named id:

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

Troubleshooting Common Error

One common error that may occur is when attempting to create a primary key while adding the column. The following syntax will not work:

ALTER TABLE goods ADD COLUMN `id` INT(10) UNSIGNED PRIMARY AUTO_INCREMENT;
Copy after login

To resolve this issue, specify PRIMARY KEY instead of just PRIMARY. The correct syntax is:

ALTER TABLE goods ADD COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
Copy after login

The above is the detailed content of How do I add a primary key to a MySQL table and avoid common errors?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template