Home  >  Article  >  Database  >  How to Fix \"Error 1062 (23000): Duplicate entry\" When Adding a Primary Key in MySQL?

How to Fix \"Error 1062 (23000): Duplicate entry\" When Adding a Primary Key in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 15:40:26816browse

How to Fix

How to Append a Primary Key to a MySQL Table

When attempting to add a primary key to a MySQL table, you may encounter errors similar to the one described in the question. This error occurs if you use the PRIMARY keyword instead of PRIMARY KEY.

To correctly add a primary key to a table, follow these steps:

  1. Add the Column:

    • Add a new column to your table using the ALTER TABLE statement. Specify the column name, data type, and other attributes.
    <code class="sql">ALTER TABLE goods ADD COLUMN `id` INT(10) UNSIGNED;</code>
  2. Specify the Primary Key:

    • Once you have added the new column, you can specify it as the primary key using the ALTER TABLE statement again.
    <code class="sql">ALTER TABLE goods ADD PRIMARY KEY (id);</code>

As an example, the corrected query that the user was attempting to use would be:

<code class="sql">ALTER TABLE goods ADD COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;</code>

The above is the detailed content of How to Fix \"Error 1062 (23000): Duplicate entry\" When Adding a Primary Key in MySQL?. 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