Home  >  Article  >  Database  >  Why am I getting a \'Duplicate Entry for Primary Key\' Error (Code 1062) in MySQL?

Why am I getting a \'Duplicate Entry for Primary Key\' Error (Code 1062) in MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 12:42:01699browse

Why am I getting a

MySQL Error: Duplicate Entry for Primary Key

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

Problem:

When attempting to insert a new row into the UFFICIO-INFORMAZIONI table, you receive an error that a duplicate entry exists for the primary key value '1'.

Explanation:

The primary key is a unique constraint on a column or set of columns in a table. It ensures that each row has a unique identifier. In your case, the ID column is defined as the primary key, which means that no two rows can have the same value for the ID column.

Cause:

The error is raised because you are trying to insert a new row with an ID value that already exists in the table. This violates the primary key constraint, as there cannot be two rows with the same primary key value.

Solution:

There are two possible solutions to this issue:

  1. Use Auto-Increment: Change the ID column to an auto-incrementing column. This will allow the database to automatically generate unique ID values for each new row, eliminating the need to specify the ID value explicitly.
  2. Specify a Unique ID Value: If you do not want to use auto-incrementing, you will need to ensure that the ID value you specify for each new row is unique. You can generate your own unique ID values or use a UUID (Universally Unique Identifier) library.

Example:

To use auto-incrementing in MySQL, modify the table creation statement as follows:

<code class="sql">CREATE  TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `viale` VARCHAR(45) NULL ,
   .....</code>

This will create an ID column that automatically increments for each new row inserted into the table. You can then omit the ID value when inserting new rows.

<code class="sql">INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...)
VALUES ('Viale Cogel ', '120', ...)</code>

The above is the detailed content of Why am I getting a \'Duplicate Entry for Primary Key\' Error (Code 1062) 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