Home  >  Article  >  Database  >  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
DDDOriginal
2024-10-27 09:15:301035browse

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]);

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

ALTER TABLE goods ADD PRIMARY KEY (id);

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;

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;

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!

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