Home > Database > Mysql Tutorial > body text

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

Linda Hamilton
Release: 2024-10-30 15:40:26
Original
816 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!