Ошибка mysql duplicate entry 1 for key primary

So my MySQL database is behaving a little bit wierd. This is my table:

Name shares id  price   indvprc
cat   2     4   81      0
goog  4     4   20      20
fb    4     9   20      20

I’m getting this #1062 error when I try to insert into the table. So I looked into it further and realized that when I try to insert values into the table, in which the name and shares values are the same, it will return the #1062 error. For example, If i inserted:

fb    4      6     20   20 

It would return an error. But if i changed the shares number to 6, it would run fine. Is it because of one of my columns that could be unique, or is it just something with mysql?

asked Jul 24, 2012 at 20:05

irosenb's user avatar

5

You need to remove shares as your PRIMARY KEY OR UNIQUE_KEY

answered Jul 24, 2012 at 20:12

mlishn's user avatar

mlishnmlishn

1,67914 silver badges19 bronze badges

1

Use SHOW CREATE TABLE your-table-name to see what column is your primary key.

answered Jul 24, 2012 at 20:10

Majid Fouladpour's user avatar

Majid FouladpourMajid Fouladpour

29.2k20 gold badges76 silver badges127 bronze badges

2

  1. Make sure PRIMARY KEY was selected AUTO_INCREMENT.
  2. Just enable Auto increment by :

    ALTER TABLE [table name] AUTO_INCREMENT = 1
  3. When you execute the insert command you have to skip this key.

chw21's user avatar

chw21

7,9151 gold badge16 silver badges31 bronze badges

answered Feb 4, 2016 at 2:34

Đoàn Nhật Duẩn's user avatar

I solved it by changing the «lock» property from «shared» to «exclusive»:

ALTER TABLE `table` 
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;

davejal's user avatar

davejal

6,00910 gold badges39 silver badges82 bronze badges

answered Dec 9, 2015 at 2:19

Hegle Leonardo Melgar's user avatar

What is the exact error message? #1062 means duplicate entry violating a primary key constraint for a column — which boils down to the point that you cannot have two of the same values in the column. The error message should tell you which of your columns is constrained, I’m guessing «shares».

answered Jul 24, 2012 at 20:11

Chris's user avatar

ChrisChris

3221 silver badge3 bronze badges

Probably this is not the best of solution but doing the following will solve the problem

Step 1: Take a database dump using the following command

mysqldump -u root -p databaseName > databaseName.db

find the line

ENGINE=InnoDB AUTO_INCREMENT="*****" DEFAULT CHARSET=utf8;

Step 2: Change ******* to max id of your mysql table id. Save this value.

Step 3: again use

mysql -u root -p databaseName < databaseName.db

In my case i got this error when i added a manual entry to use to enter data into some other table. some how we have to set the value AUTO_INCREMENT to max id using mysql command

FastFarm's user avatar

FastFarm

4091 gold badge6 silver badges21 bronze badges

answered Apr 15, 2013 at 10:15

Kshitiz's user avatar

KshitizKshitiz

2,6731 gold badge18 silver badges24 bronze badges

1

Repair the database by your domain provider cpanel.

Or see if you didnt merged something in the phpMyAdmin

answered Apr 14, 2017 at 20:03

Guy's user avatar

The DB I was importing had a conflict during the import due to the presence of a column both autoincrement and primary key.

The problem was that in the .sql file the table was chopped into multiple «INSERT INTO» and during the import these queries were executed all together.

MY SOLUTION was to deselect the «Run multiple queries in each execution» on Navicat and it worked perfectly

answered Oct 30, 2020 at 9:01

ivoroto's user avatar

ivorotoivoroto

90512 silver badges12 bronze badges

Do not mix SQLAlchemy commands with Python’s Try-Except. SQL will keep trying regardless, and the error will only show later in your program flow.

answered Mar 2 at 18:26

Al Martins's user avatar

Al MartinsAl Martins

4135 silver badges13 bronze badges

I had this error from mySQL using DataNucleus and a database created with UTF8 — the error was being caused by this annotation for a primary key:

@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDSTRING)
protected String id;

dropping the table and regenerating it with this fixed it.

@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDHEX)
protected String id;

answered Jun 3, 2017 at 19:50

bsautner's user avatar

bsautnerbsautner

4,3891 gold badge35 silver badges49 bronze badges

2

[Solved] How to solve MySQL error code: 1062 duplicate entry?

January 21, 2016 /

Error Message:

Error Code: 1062. Duplicate entry ‘%s’ for key %d

Example:

Error Code: 1062. Duplicate entry ‘1’ for key ‘PRIMARY’

Possible Reason:

Case 1: Duplicate value.

The data you are trying to insert is already present in the column primary key. The primary key column is unique and it will not accept the duplicate entry.

Case 2: Unique data field.

You are trying to add a column to an existing table which contains data and set it as unique.

Case 3: Data type –upper limit.

The auto_increment field reached its maximum range.

MySQL NUMERICAL DATA TYPE — STORAGE & RANGE

Solution:

Case 1: Duplicate value.

Set the primary key column as AUTO_INCREMENT.

ALTER TABLE table_name ADD column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY;

Now, when you are trying to insert values, ignore the primary key column. Also you can insert NULL value to primary key column to generate sequence number. If no value specified MySQL will assign sequence number automatically.

Case 2: Unique data field.

Create the new column without the assigning it as unique field, then insert the data and now set it as unique field now. It will work now!!!

Case 3: Data type-upper limit.

When the data type reached its upper limit, for example, if you were assigned your primary key column as TINYINT, once the last record is with the id 127, when you insert a new record the id should be 128. But 128 is out of range for TINYINT so MySQL reduce it inside the valid range and tries to insert it with the id 127, therefore it produces the duplicate key error.

In order to solve this, you can alter the index field, setting it into signed / unsigned INT/ BIGINT depending on the requirement, so that the maximum range will increase. You can do that by using the following command:

ALTER TABLE table_name MODIFY column_name INT UNSIGNED NOT NULL AUTO_INCREMENT;

You can use the following function to retrieve the most recently automatically generated AUTO_INCREMENT value:

mysql> SELECT LAST_INSERT_ID();

Final workaround:

After applying all the above mentioned solutions and still if you are facing this error code: 1062 Duplicate entry error, you can try the following workaround.

Step 1: Backup database:

You can backup your database by using following command:
mysqldump database_name > database_name.sql

Step 2: Drop and recreate database: 

Drop the database using the following command:

DROP DATABASE database_name;

Create the database using the following command:

CREATE DATABASE database_name;

Step 3: Import database:


You can import your database by using following command:

mysql database_name < database_name.sql;

After applying this workaround, the duplicate entry error will be solved. I hope this post will help you to understand and solve the MySQL Error code: 1062. Duplicate entry error. If you still facing this issue, you can contact me through the contact me page. I can help you to solve this issue.

На днях я переносил один из своих сайтов на новый хостинг и столкнулся с проблемой. Подробно о том, как перенести сайт на другой хостинг я расскажу в одной из следующих статей, а пока расскажу о самой проблеме и ее решении.

Файлы сайта я скопировал быстро, сделал экспорт базы данных со старого хостинга, но при попытке импортировать таблицы в базу на новом хостинге возникла ошибка в My SQL вот такого вида:

Ошибка

SQL-запрос:

— — Дамп данных таблицы `rich_blc_instances` — INSERT INTO `rich_blc_instances` (`instance_id`, `link_id`, `container_id`, `container_type`, `link_text`, `parser_type`, `container_field`, `link_context`, `raw_url`) VALUES (1, 1, 1, ‘blogroll’, ‘Документация’, ‘url_field’, ‘link_url’, », ‘http://codex.wordpress.org/Заглавная_страница’), (2, 2, 2, ‘blogroll’, ‘Блог WordPress’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/news/’), (3, 3, 3, ‘blogroll’, ‘Форумы поддержки’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/’), (4, 4, 4, ‘blogroll’, ‘Плагины’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/plugins/’), (5, 5, 5, ‘blogroll’, ‘Темы’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/themes/’), (6, 6, 6, ‘blogroll’, ‘Обратная связь’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/forum/20’), (7, 7, 7, ‘blogroll’, ‘Планета WordPr[…]

Ответ MySQL:

#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’

Так как в базах данных я полный чайник, пришлось копаться в интернете в поисках решения. На форумах довольно много записей от людей с подобной проблемой, но нигде нет четкого ответа – сделай вот так и так.

В общих чертах я проблему понял, но вот как ее решить было неясно. На всех форумах, где встречалось описание подобной ошибки, люди писали, что она возникает при попытке добавить записи из одной базы данных в уже существующую другую.

Но я импортировал базу данных в пустые таблицы, более того, таблицы создавались в процессе импорта.

Решил проблему с ошибкой «#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’» следующим образом:

Заменил в таблицах базы данных команду INSERT INTO на REPLACE INTO. В тексте ошибки, который я привел выше вы можете посмотреть в каком месте таблицы располагаются эти слова (выделил жирным).

По умолчанию, с помощью директивы insert база пыталась вставить значения в таблицу, но почему-то, находила дублированный key ‘PRIMARY’ и не могла вставить данные (как она их находила, я так и не разобрался). Директива replace заставила базу заменять данные при совпадении значений, не обращая внимания на прошлые записи.

Заменить эту директиву можно открыв сам файл базы данных с помощью текстового редактора – эта команда стоит перед блоком каждой таблицы. Открываете базу данных в текстовом редакторе, например, Akelpad и меняете все команды INSERT INTO на REPLACE INTO.

В моем же случае, получилось сделать проще – я по новой сделал экспорт таблицы на старом хостинге и в настройках экспорта установил этот самый REPLACE вместо INSERT.

Карта Tinkoff Black MySQL NUMERICAL DATA TYPE — STORAGE & RANGE

Solution:

Case 1: Duplicate value.

Set the primary key column as AUTO_INCREMENT.

ALTER TABLE table_name ADD column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY;

Now, when you are trying to insert values, ignore the primary key column. Also you can insert NULL value to primary key column to generate sequence number. If no value specified MySQL will assign sequence number automatically.

Case 2: Unique data field.

Create the new column without the assigning it as unique field, then insert the data and now set it as unique field now. It will work now!!!

Case 3: Data type-upper limit.

When the data type reached its upper limit, for example, if you were assigned your primary key column as TINYINT, once the last record is with the id 127, when you insert a new record the id should be 128. But 128 is out of range for TINYINT so MySQL reduce it inside the valid range and tries to insert it with the id 127, therefore it produces the duplicate key error.

In order to solve this, you can alter the index field, setting it into signed / unsigned INT/ BIGINT depending on the requirement, so that the maximum range will increase. You can do that by using the following command:

ALTER TABLE table_name MODIFY column_name INT UNSIGNED NOT NULL AUTO_INCREMENT;

You can use the following function to retrieve the most recently automatically generated AUTO_INCREMENT value:

mysql> SELECT LAST_INSERT_ID();

Final workaround:

After applying all the above mentioned solutions and still if you are facing this error code: 1062 Duplicate entry error, you can try the following workaround.

Step 1: Backup database:

You can backup your database by using following command:
mysqldump database_name > database_name.sql

Step 2: Drop and recreate database: 

Drop the database using the following command:

DROP DATABASE database_name;

Create the database using the following command:

CREATE DATABASE database_name;

Step 3: Import database:


You can import your database by using following command:

mysql database_name < database_name.sql;

After applying this workaround, the duplicate entry error will be solved. I hope this post will help you to understand and solve the MySQL Error code: 1062. Duplicate entry error. If you still facing this issue, you can contact me through the contact me page. I can help you to solve this issue.

На днях я переносил один из своих сайтов на новый хостинг и столкнулся с проблемой. Подробно о том, как перенести сайт на другой хостинг я расскажу в одной из следующих статей, а пока расскажу о самой проблеме и ее решении.

Файлы сайта я скопировал быстро, сделал экспорт базы данных со старого хостинга, но при попытке импортировать таблицы в базу на новом хостинге возникла ошибка в My SQL вот такого вида:

Ошибка

SQL-запрос:

— — Дамп данных таблицы `rich_blc_instances` — INSERT INTO `rich_blc_instances` (`instance_id`, `link_id`, `container_id`, `container_type`, `link_text`, `parser_type`, `container_field`, `link_context`, `raw_url`) VALUES (1, 1, 1, ‘blogroll’, ‘Документация’, ‘url_field’, ‘link_url’, », ‘http://codex.wordpress.org/Заглавная_страница’), (2, 2, 2, ‘blogroll’, ‘Блог WordPress’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/news/’), (3, 3, 3, ‘blogroll’, ‘Форумы поддержки’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/’), (4, 4, 4, ‘blogroll’, ‘Плагины’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/plugins/’), (5, 5, 5, ‘blogroll’, ‘Темы’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/themes/’), (6, 6, 6, ‘blogroll’, ‘Обратная связь’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/forum/20’), (7, 7, 7, ‘blogroll’, ‘Планета WordPr[…]

Ответ MySQL:

#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’

Так как в базах данных я полный чайник, пришлось копаться в интернете в поисках решения. На форумах довольно много записей от людей с подобной проблемой, но нигде нет четкого ответа – сделай вот так и так.

В общих чертах я проблему понял, но вот как ее решить было неясно. На всех форумах, где встречалось описание подобной ошибки, люди писали, что она возникает при попытке добавить записи из одной базы данных в уже существующую другую.

Но я импортировал базу данных в пустые таблицы, более того, таблицы создавались в процессе импорта.

Решил проблему с ошибкой «#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’» следующим образом:

Заменил в таблицах базы данных команду INSERT INTO на REPLACE INTO. В тексте ошибки, который я привел выше вы можете посмотреть в каком месте таблицы располагаются эти слова (выделил жирным).

По умолчанию, с помощью директивы insert база пыталась вставить значения в таблицу, но почему-то, находила дублированный key ‘PRIMARY’ и не могла вставить данные (как она их находила, я так и не разобрался). Директива replace заставила базу заменять данные при совпадении значений, не обращая внимания на прошлые записи.

Заменить эту директиву можно открыв сам файл базы данных с помощью текстового редактора – эта команда стоит перед блоком каждой таблицы. Открываете базу данных в текстовом редакторе, например, Akelpad и меняете все команды INSERT INTO на REPLACE INTO.

В моем же случае, получилось сделать проще – я по новой сделал экспорт таблицы на старом хостинге и в настройках экспорта установил этот самый REPLACE вместо INSERT.

Карта Tinkoff Black

Ошибка
SQL запрос:INSERT INTO `wp_commentmeta` (`meta_id`, `comment_id`, `meta_key`, `meta_value`) VALUES
(1, 2, ‘rating’, ‘5’),
(2, 2, ‘verified’, ‘0’),
(3, 1, ‘_wp_trash_meta_status’, ‘1’),
(4, 1, ‘_wp_trash_meta_time’, ‘1464693386’),
(5, 3, ‘rating’, ‘1’),
(6, 3, ‘verified’, ‘0’)
Ответ MySQL: Документация

#1062 — Дублирующаяся запись ‘1’ по ключу ‘PRIMARY’

при загрузке в базу таблицы пробовали в zip тоже самое

Похожие вопросы

Паркуется домен при установке вп

Добрый день, подскажите почему паркуется домен при установке вордпреса на сайт? Мои действия:

1) создание бд, выставление прав к бд

2) установка вп

3) привязка домена

При переходе по ссылке, выдается страница парковки таймвеб

Подключение к базе данных через c#

Никто не сталкивался с проблемами подключения к базе данных msql на хостинге через c#?
Пробую, не получается!
буду очень рад любой вашей помощи!

Создать опрос на платформе timeweb

Подскажите, пожалуйста, можно ли создать опросник с вариантами ответов, чтобы данные были привязаны к нашему ящику на timeweb и сохранялись там же? Как в googleforms или survey monkey. Спасибо!

Duplicate Entry error is a very common error that has been experienced by users working with databases. Users have reported that the error has commonly occurred when using the SQL. The error appears when updating the tables. Furthermore, the error has occurred in several scenarios which include using Laravel, PHP, Atlassian, Joomla, and similar web development and databases. Now in this article, the objective is to give you important information regarding the error and to give you some methods by which you can fix the issue by yourself in no time. But before let’s go through its causes.

Duplicate Entry

Causes of Duplicate Entry Error Problem Issue

While researching about the error and its possible solution we come up with some very common users that have been reported by the users. The Duplicate Entry error appears because of multiple reasons depending like if you are working with SQL possible the error comes because of the duplicate key, unique data field, or data type -upper limit. Also if the table indexes are corrupted then also the error seems to appear. However, the error also occurs due to mistakes in the codes or the way the user is updating or modifying the table.

  • Duplicate key or entries
  • Unique data field
  • Data type -upper limit
  • Table indexes are corrupted
  • Mistakes in the codes

Similar Types of Duplicate Entry Error Problem Issue

  • MySQL error 1062 duplicate entry ‘0’ for key ‘primary’
  • MySQL for key ‘primary auto_increment
  • #1062 – duplicate entry ‘1’ for key ‘primary’ PHPMyAdmin
  • ‘0’ for key ‘primary Codeigniter
  • Duplicate entry 255 for key ‘primary
  • 82 for key primary
  • Duplicate entry ‘4294967295’ for key ‘primary
  • #1062 40 for key primary

In this section, we will try to cover some methods that you can try to resolve the Duplicate Entry Error. The following are the methods we will go through. Since we do not know the actual cause of the issue we will be giving you solutions according to the scenarios.

1. The Value Already Exist (Duplicate Value)

Now the #1062 – duplicate entry ‘1’ for key ‘primary’ Error may occur when the data or value which you are trying to insert already exists in the Primary key. Furthermore, it is important to know that the Primary key does not accept duplicate entries. To resolve this you can do the below steps.

  • STEP 1. Put the Primary Key Colum as to be auto increment
  • STEP 2. Use the below syntax
ALTER TABLE table_name ADD column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
**NOTE: You can ignore the Primary key column while inserting values.
Alternatively,
you can put NULL vale to Primary Key which in turn automatically generates sequence numbers.

2. Unique Data Filed

The error also appears when an existing table has been set to unique. So when you try to add any column the error appears. So the simple fix to this duplicate entry for key ‘primary’ issue is to create a new column but don’t set it to the Unique field. Insert whatever data you wish to insert and the set is as unique if you want to.

3. Data Limit Out Of Range

The error also appears when if you have been using the auto_increment function and the data exceeds the limit of auto_increment function the #1062 – duplicate entry ‘0’ for key ‘primary’ error appears. Suppose you have assigned the primary key column as something. And the limit of the auto_increment is set to a max of 127. Now when you enter a new record whose id is more than 127 the error will emerge. To fix this follow the steps.

  • STEP 1. We can resolve the issue by modifying the index field. You may use any of the following signed/unsigned INT/ BIGINT
  • STEP 2. Use the below command to increase the maximum range
ALTER TABLE table_name MODIFY column_name INT UNSIGNED NOT NULL AUTO_INCREMENT;
  • STEP 3. Also if you want to retrieve the recently incremented value, the below command
mysql> SELECT LAST_INSERT_ID();

4. Creating a New Database & Importing

If you have tried the above methods and the duplicate entry 0 for key primary error still persists, try the below step to fix the issue.

  • STEP 1. Firstly backup your database using the below command
mysqldump database_name > database_name.sql
  • STEP 2. Once the backup is done, drop the database
DROP DATABASE database_name;
  • STEP 3. Now recreate the database, by using the below command
CREATE DATABASE database_name;
  • STEP 4. Now that you have created the database import using the below command
mysql database_name < database_name.sql;
  • STEP 5. Now check if the duplicate entry ‘1’ for key ‘primary’ error still occurs

5. When Importing Table from Database in PHPmyadmin

The error has been seen when the user tries to import the exported tables in PHPMyAdmin the duplicate entry for key primary error seems to appear. Follow the steps to do it the right way.

  • STEP 1. When you are exporting your SQL database in PHPMyAdmin, use the custom export method
  • STEP 2. In the export, method choose Custom- display all possible options

phpmyadmin

  • STEP 3. In the options instead of selecting any of the insert options, choose update

phpmyadmin

  • STEP 4. Using this way will prevent any kind of duplicated inserts to get rid of remove duplicate entry in excel error.

6. Duplicate Username

One of the users has been facing the issue because the database does not allow duplicate usernames. So kindly make sure that the username is unique. To fix this how to remove the duplicate entry in excel issue follow the steps.

  • STEP 1. In order to resolve the issue, you have to find find the duplicate usernames, which can  be done using the following command
SELECT username FROM #__users GROUP BY username HAVING COUNT(*) > 1
**NOTE: Instead of #_ use the prefix for your tables.
  • STEP 2. Fix the 1062 duplicate entry 1 for key primary issue

7. Other Troubleshooting Points

  • Error in WordPress Database: So one the cause why this duplicate entry 1 for key primary error occurs is because of adswsc_DbInstall. It is comparing the unequal table names.
  • Update the Program: Make sure that if you are using any database application it is updated to the latest version.
  • Crosscheck the code: Make sure that the code is accurate and without errors
Conclusion:

In this troubleshooting, we have seen various methods that are the solution to fix Duplicate Entry Error. The error may appear due to multiple reasons and we have tried to cover most of them. Furthermore, we have also talked about the possible causes that lead to this error.

We hope this Duplicate Entry troubleshooting guide fixed your issue. For articles on troubleshooting and tips follow us. Thank You!

Понравилась статья? Поделить с друзьями:
  • Ошибка mysql 1114 что делать
  • Ошибка mysql 1046 no database selected
  • Ошибка my text is missing
  • Ошибка mx lookup failed for gmail ru
  • Ошибка multiple statements found while compiling a single statement