Mysql - duplicate entry error for key with auto increment - mysql

Why do I get an error of the form:
Error in query: Duplicate entry '10' for key 1
...when doing an INSERT statement like:
INSERT INTO wp_abk_period (pricing_id, apartment_id) VALUES (13, 27)
...with 13 and 27 being valid id-s for existing pricing and apartment rows, and the table is defined as:
CREATE TABLE `wp_abk_period` (
`id` int(11) NOT NULL auto_increment,
`apartment_id` int(11) NOT NULL,
`pricing_id` int(11) NOT NULL,
`type` enum('available','booked','unavailable') collate utf8_unicode_ci default NULL,
`starts` datetime default NULL,
`ends` datetime default NULL,
`recur_type` enum('daily','weekly','monthly','yearly') collate utf8_unicode_ci default NULL,
`recur_every` char(3) collate utf8_unicode_ci default NULL,
`timedate_significance` char(4) collate utf8_unicode_ci default NULL,
`check_in_times` varchar(255) collate utf8_unicode_ci default NULL,
`check_out_times` varchar(255) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`),
KEY `fk_period_apartment1_idx` (`apartment_id`),
KEY `fk_period_pricing1_idx` (`pricing_id`),
CONSTRAINT `fk_period_apartment1` FOREIGN KEY (`apartment_id`) REFERENCES `wp_abk_apartment` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_period_pricing1` FOREIGN KEY (`pricing_id`) REFERENCES `wp_abk_pricing` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Isn't key 1 id in this case and having it on auto_increment sufficient for being able to not specify it?
Note: If I just provide an unused value for id, like INSERT INTO wp_abk_period (id, pricing_id, apartment_id) VALUES (3333333, 13, 27) it works fine, but then again, it is set as auto_increment so I shouldn't need to do this!
Note 2: OK, this is a complete "twilight zone" moment: so after running the query above with the huge number for id, things started working normally, no more duplicate entry errors. Can someone explain me WTF was MySQL doing to produce this weird behavior?

It could be that your AUTO_INCREMENT value for the table and the actual values in id column have got out of whack.
This might help:
Step 1 - Get Max id from table
select max(id) from wp_abk_period
Step 2 - Align the AUTO_INCREMENT counter on table
ALTER TABLE wp_abk_period AUTO_INCREMENT = <value from step 1 + 100>;
Step 3 - Retry the insert
As for why the AUTO_INCREMENT has got out of whack I don't know. Added auto_increment after data was in the table? Altered the auto_increment value after data was inserted into the table?
Hope it helps.

I had the same problem and here is my solution :
My ID column had a bad parameter. It was Tinyint, and MySql want to write a 128th line.
Sometimes, your problem you think the bigger you have is only a tiny parameter...

Late to the party, but I just ran into this tonight - duplicate key '472817' and the provided answers didn't help.
On a whim I ran:
repair table wp_abk_period
which output
Number of rows changed from 472816 to 472817
Seems like mysql had the row count wrong, and the issue went away.
My environment:
mysql Ver 14.14 Distrib 5.1.73, for Win64 (unknown)
Create table syntax:
CREATE TABLE `env_events` (
`tableId` int(11) NOT NULL AUTO_INCREMENT,
`deviceId` varchar(50) DEFAULT NULL,
`timestamp` int(11) DEFAULT NULL,
`temperature` float DEFAULT NULL,
`humidity` float DEFAULT NULL,
`pressure` float DEFAULT NULL,
`motion` int(11) DEFAULT NULL,
PRIMARY KEY (`tableId`)
) ENGINE=MyISAM AUTO_INCREMENT=528521 DEFAULT CHARSET=latin1

You can check the current value of the auto_increment with the following command:
show table status
Then check the max value of the id and see if it looks right. If not change the auto_increment value of your table.

When debugging this problem check the table name case sensitivity (especially if you run MySql not on Windows).
E.g. if one script uses upper case to 'CREATE TABLE my_table' and another script tries to 'INSERT INTO MY_TABLE'. These 2 tables might have different contents and different file system locations which might lead to the described problem.

Related

SQL forcing me to use default value and property

Strange trouble indeed!
I am experiencing this issue when (My)SQL add some properties to my table, that I don´t want to be there and that I can´t change, even if I run right command and get "SUCCESS" reply.
Here is code for creating such a table:
CREATE TABLE `KIIS_EVENT_APPLICATION`
(
`ID_USER` smallint(3) unsigned NOT NULL,
`ID_EVENT` smallint(5) unsigned NOT NULL,
`COMES` timestamp,
`LEAVES` timestamp,
`TRANSPORT_THERE` varchar(30) COLLATE cp1250_czech_cs,
`TRANSPORT_BACK` varchar(30) COLLATE cp1250_czech_cs,
`ROLE` varchar(30) COLLATE cp1250_czech_cs NOT NULL,
`RELEVANCE` tinyint(1) unsigned NOT NULL,
FOREIGN KEY (`ID_EVENT`) REFERENCES `KIIS_EVENTS`(`ID_EVENT`),
FOREIGN KEY (`ID_USER`) REFERENCES `KIIS_USERS`(`ID_USER`)
) ENGINE=InnoDB DEFAULT CHARSET=cp1250 COLLATE cp1250_czech_cs
Let´s see the result:
Yellow highlighted things I don´t asked for.
If I run query, such as
ALTER TABLE `KIIS_EVENT_APPLICATION` CHANGE `COMES` `COMES` TIMESTAMP NOT NULL;
page says, it is successfully done, but nothing changes.
How can i make COMES column to be same as LEAVES column ?
Could it be caused by missing primary key? Do I need one when I have 2 foreign there (is it good SQL design practice, or?) ?
Michael - sqlbot got it right in comment.
ALTER TABLE KIIS_EVENT_APPLICATION MODIFY COLUMN COMES TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00'; or more correctly, ... TIMESTAMP NULL DEFAULT NULL
The first timestamp column in a table gets magical behavior by default prior to MySQL Server 5.6.
I added
timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
properties to all columns with such a behaviour and it works just fine.
Great!

MySQL prcedures take too much time and the tables are very large

I have a large live database where around 1000 users are updating 2 or more updates every minute. at the same time there are 4 users are getting reports and adding new items. the main 2 tables contains around 2 Million and 4 Million rows till present.
Queries using these tables are taking too much time, even simple queries like:
"SELECT COUNT(*) FROM MyItemsTable" and "SELECT COUNT(*) FROM MyTransactionsTable"
are taking 10 seconds and 26 seconds
large reports now are taking 15mins !!! toooooo much time.
All the table that I'm using are innodb
is there any way to solve this problem before I read about reputation ??
Thank you in advance for any help
Edit
Here is the structure and indexes of MyItemsTable:
CREATE TABLE `pos_MyItemsTable` (
`itemid` bigint(15) NOT NULL,
`uploadid` bigint(15) NOT NULL,
`itemtypeid` bigint(15) NOT NULL,
`statusid` int(1) NOT NULL,
`uniqueid` varchar(10) DEFAULT NULL,
`referencenb` varchar(30) DEFAULT NULL,
`serialnb` varchar(25) DEFAULT NULL,
`code` varchar(50) DEFAULT NULL,
`user` varchar(16) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`pass` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`expirydate` date DEFAULT NULL,
`userid` bigint(15) DEFAULT NULL,
`insertdate` datetime DEFAULT NULL,
`updateuser` bigint(15) DEFAULT NULL,
`updatedate` datetime DEFAULT NULL,
`counternb` int(1) DEFAULT '0',
PRIMARY KEY (`itemid`),
UNIQUE KEY `referencenb_unique` (`referencenb`),
KEY `MyItemsTable_r04` (`itemtypeid`),
KEY `MyItemsTable_r05` (`uploadid`),
KEY `FK_MyItemsTable` (`statusid`),
KEY `ind_MyItemsTable_serialnb` (`serialnb`),
KEY `uniqueid_key` (`uniqueid`),
KEY `ind_MyItemsTable_insertdate` (`insertdate`),
KEY `ind_MyItemsTable_counternb` (`counternb`),
CONSTRAINT `FK_MyItemsTable` FOREIGN KEY (`statusid`) REFERENCES `MyItemsTable_statuses` (`statusid`),
CONSTRAINT `MyItemsTable_r04` FOREIGN KEY (`itemtypeid`) REFERENCES `itemstypes` (`itemtypeid`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `MyItemsTable_r05` FOREIGN KEY (`uploadid`) REFERENCES `uploads` (`uploadid`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Just having few indexes does not mean your tables and queries are optimized.
Try to identify the querties that run the slowest and add specific indexes there.
Selecting * from a huge table .. where you have columns that contain text / images / files
will be aways slow. Try to limit the selection of such fat columns when you don't need them.
future readings:
http://dev.mysql.com/doc/refman/5.0/en/innodb-index-types.html
http://www.xaprb.com/blog/2006/07/04/how-to-exploit-mysql-index-optimizations/
and some more advanced configurations:
http://www.mysqlperformanceblog.com/2006/09/29/what-to-tune-in-mysql-server-after-installation/
http://www.mysqlperformanceblog.com/2007/11/03/choosing-innodb_buffer_pool_size/
source
UPDATE:
try to use composite keys for some of the heaviest queries,
by placing the main fields that are compared in ONE index:
`MyItemsTable_r88` (`itemtypeid`,`statusid`, `serialnb`), ...
this will give you faster results for queries that complare only columns from the index :
SELECT * FROM my_table WHERE `itemtypeid` = 5 AND `statusid` = 0 AND `serialnb` > 500
and extreamlly fast if you search and select values from the index:
SELECT `serialnb` FROM my_table WHERE `statusid` = 0 `itemtypeid` IN(1,2,3);
This are really basic examples you will have to read a bit more and analyze the data for the best results.

Update table with MAX() and MIN() from another table + performance problems

I have a problem that i have tried to solve for the last 2 days, i have 2 tables, workspat and xtractor_wrk.
xtractor_wrk contains 250000 rows and workspat contains 67 million rows.
CREATE TABLE `xtractor_wrk` (
`db_time` datetime DEFAULT NULL,
`db_position` point NOT NULL,
`db_namn` char(50) CHARACTER SET utf8 COLLATE utf8_swedish_ci NOT NULL,
`db_sis` mediumint(8) unsigned DEFAULT NULL,
`db_om` smallint(5) unsigned DEFAULT NULL,
`db_seq` char(50) DEFAULT NULL,
`db_grarri` datetime DEFAULT NULL,
`db_grtime` datetime DEFAULT NULL,
KEY `db_time` (`db_time`),
KEY `db_sis` (`db_sis`),
KEY `db_om` (`db_om`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC
CREATE TABLE `workspat` (
`db_time` datetime NOT NULL,
`db_point` point NOT NULL,
`db_om` smallint(6) NOT NULL,
`db_sis` mediumint(8) NOT NULL,
`db_status` char(10) CHARACTER SET latin1 NOT NULL,
KEY `db_sis` (`db_sis`),
KEY `db_om` (`db_om`),
KEY `db_time` (`db_time`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci
I have 2 problems:
What i would like to do is to update my table xtractor_wrk with the MAX(workspat.db_time)
and the MIN(workspat.db_time) from the result i would get from the "ON" below .
I have tried a lot of things but the only think i got somewhat working was this:
UPDATE xtractor_wrk
JOIN workspat
ON date(xtractor_wrk.db_time) = date(workspat.db_time)
and xtractor_wrk.db_om = workspat.db_om
and xtractor_wrk.db_sis = workspat.db_sis
SET xtractor_wrk.db_grtime = workspat.db_time
and of course this does not give me the MAX and MIN update to xtractor_wrk its just that this
is the only thing that even remotely worked for me.
workspat.db_time can have any number of matches and i would like the highest and lowest and write them to xtractor_wrk.db_grtime and xtractor_wrk.db_grarri
I also have a problem with speed, i have tried indexing but its still very slow, is there a way to index across tables or is my problem all the updates? Can i write the result to a new table instead of updating or maybe delay the update since its 250000 rows to update? How would i do that?
Trying to suggest only
Add new column that indicates that is already updated or not like 1 if already updated and 0 if its not updated and also add where clause for more faster updating.
Example:
column 1 column 2 column 3 ... Updated
0
1
0
0
1

What does 'Execute failed: (1062) Duplicate entry 'X' for key 'Y'' mean?

I am trying to add X to some table in my DB, but I am getting this error. Even if X doesn't exist in the table, it say it's there. Although X is added to the DB, I want to get rid of this error. I don't know if it's relevant at all, but I'm using Mysqli's prepared statements and this error is printed using $statement->errno." ".$statement->error. Could someone explain this to me? Thanks.
UPDATE: this is the code: X = USER_USERNAME
$stmt = $mysqli->prepare("INSERT INTO USERS (USER_USERNAME, USER_EMAIL, USER_BIRTHDAY, USER_PASSWORD, USER_SALT, USER_IP, USER_ACTIVATION_CODE) VALUES (?,?,?,?,?,INET_ATON(?),?)");
$stmt->bind_param('sssssss',$username,$email,$date,$hashed_password,$salt,$IP,$activation_code);
$stmt->execute();
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else {
echo "ok";
}
SHOW CREATE TABLE USERS:
CREATE TABLE `USERS` (
`USER_ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_FIRSTNAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_LASTNAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_USERNAME` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_PASSWORD` varchar(128) CHARACTER SET utf8 DEFAULT NULL,
`LEVEL_ID` int(11) NOT NULL,
`USER_BIRTHDAY` date DEFAULT NULL,
`USER_EMAIL` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_GENDER` enum('M','W','U') CHARACTER SET utf8 DEFAULT NULL,
`USER_COUNTRY` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_LOCATION` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_ADDRESS` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`USER_HOUSENUMBER` varchar(8) CHARACTER SET utf8 DEFAULT NULL,
`USER_AVATAR` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`USER_REGISTRATION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`USER_ACTIVATION_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_STATUS` enum('REGISTERED','ACTIVE','BANNED','NONACTIVE') CHARACTER SET utf8 DEFAULT NULL,
`USER_BANNED_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_LATEST_LOGIN` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_EXP` bigint(20) DEFAULT NULL,
`USER_DESCRIPTION` text CHARACTER SET utf8,
`USER_ACTIVATION_CODE` varchar(32) CHARACTER SET utf8 NOT NULL DEFAULT '0',
`USER_SALT` varchar(15) CHARACTER SET utf8 NOT NULL,
`USER_IP` int(10) NOT NULL,
`USER_REMEMBER_KEY` varchar(32) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`USER_ID`),
UNIQUE KEY `USER_USERNAME` (`USER_USERNAME`),
UNIQUE KEY `USER_EMAIL` (`USER_EMAIL`),
KEY `LEVEL_ID` (`LEVEL_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=latin1
that's because you are trying to insert or update a value violating a constraint (like PK or UK), for example
if your Table have ID an it's a PK or a Unique Key, you can only have ONE UNIQUE VALUE... it's not possible no repeated....
with a Unique Key you can have Null... but never repeat values in the same column, because you will be breaking the constraint... for more information take a look to http://dev.mysql.com/doc/refman/5.0/es/constraints.html
You already defined a Primary or Unique Key, but again you tried to insert the same value. That time since already there exists a same value, it is not possible to have a redundant value for the primary key or unique key.
It is something like this. Consider you have a table with id and name, with id as primary key. You insert first row as:
INSERT INTO `users` (`id`, `name`) VALUES (1, 'Praveen');
INSERT INTO `users` (`id`, `name`) VALUES (1, 'Kumar');
The second query violates the id uniqueness.
Solution: Try to truncate the table and then run the query again, if it is possible.
Some steps to try
Check for other fields with unique constraints being violated too.
See what query is getting generated.
Put the same query in phpMyAdmin and check.
If you are getting that error then X does exist in the table. Apparently you have not noticed it, but it's there. (Check for things like trimmed spaces, and case sensitivity.)
If you don't get the error in phpMyAdmin then the query you think you are sending is not actually the query you are sending. Most likely you are sending blank for the field, and after you do it once, all further query are using the identical blank value.
Easiest way to check is delete everything from the table (copy it elsewhere first if you want). Then run the query and see what actually got inserted vs. what you expected to get inserted.
You are probably trying to insert a record with the ID (or some other field) 1 set, while such a record already exists in the table. The field that is the primary key must have a unique value for each record.
You could try a simple error check to avoid this error:
$rows = mysql_query("SELECT X from tablenme WHERE X = Y;");
if(mysql_num_rows($rows) > 0){
echo 'Error Messege';
}else{
insert...
}
where X is the primary key or foregin key column and Y is the value to be inserted in that column.
EDIT: Some of the problems that might have caused the problem may be that you have not specified certain columns that can't be null in you insert statement.
Like LEVEL_ID and USER_REMEMBER_KEY. They are set to NOT NULL but the values are not being inserted using the insert statement.
I also don't understand why you are inserting 'sssssss' when the first column is USER_USERNAME and its corresponding value is $username. Do check that too.
SQL Fiddle

MySQL Duplicate primary key on unexisting key

I've got a weird problem on a MySQL table. When trying to insert a new row, it says the primary key is duplicate. My primary key is auto incremental and is not set within my query (automatically set by MySQL).
The problem is I get a "Duplicate primary key" error on a key that doesn't even exists (I checked). I solved the problem increasing the current auto_increment value but I can't understand how it happened.
Any help would be great.
Edit
Table creation
CREATE TABLE `articles_mvt` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`ext_article_id` int(5) NOT NULL,
`date_mvt` date NOT NULL,
`qte` float(4,2) NOT NULL,
`in_out` enum('in','out') NOT NULL,
`ext_nateco_id` int(5) NOT NULL,
`ext_agent_id` int(5) NOT NULL COMMENT 'Demandeur',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1647 ;
Problematic query
INSERT INTO articles_mvt (
`ext_article_id`,
`date_mvt`,
`qte`,
`in_out`,
`ext_nateco_id`,
`ext_agent_id`
)
VALUES (
'".$_POST["numArticle"]."',
'".dateSql($_POST["date_mvt"])."',
".$_POST["qte_entier"].".".$_POST["qte_virgule"].",
'".$_POST["in_out"]."',
".$_POST["numNateco"].",
".$_POST["demandeur"]."
)
FYI variables are sanitized earlier in the code ;)
Well i think at that time you did not check auto Inc flag on primary key. So when you try to enter than value 0 is insert in the primary key and for second entry it gives error. like that
ID Value
0 A ok it not give error
0 ff it gives error..
Or you may try to insert a row whose ID is already exist like
ID Value
11 A ok it not give error
11 ff it gives error..