MySQL Insert Failing with Duplicate Entry on Index - mysql

I am trying to do an insert statement. I have an unique index setup that combines phone_number and niche.
INSERT INTO CV_YP.table (phone_number,website,niche) VALUES
(1231231234, 'website.com', 'fitness')
The return value says I have a duplicate entry but the phone number is different then the one I just tried to insert.
ERROR 1062 (23000) at line 1: Duplicate entry '2147483647-fitness' for
key 'idx_table_phone_number_niche'
I can't figure out why MySQL thinks my insert is related to the index duplication it returns.

i think if you run this query
SELECT * FROM CV_YP.table WHERE phone_number = '2147483647' AND niche = 'fitness';
you will find more than 1 row, so I think its a violation of the unique index, so when the engine tries to check for uniqueness on the new data this error fire
update
I think your phone number isn't 1231231234 right?
and it's a number greater than 2147483647 and you use phone_number data type as int
If that true I think you need to change the data type of the phone_number column because the max value of int is 2147483647 so when you insert the new number the engine sees it as the max value which is 2147483647 and try to insert it.

Related

MySQL Integer Column with Unique values in it, however default value is 2( not NULL) ? Is it Possible?

I want a table with an integer column, that must be filled with a default value 1111 when no input is received. But if we receive input it should be filled and I want it to be UNIQUE : there cannot be two entries of the same number(except default value 111). Ex :-
I know we can achieve the objective if our default value is NULL but here in my case I need to have a integer default value and unique check in all other integer added.
Please guide me if this can be achieved or not ?
A UNIQUE KEY can't hold the value 1111 multiple times.
So use NULL and replace it in the queries
CREATE TABLE tab1(col1 int,col2 int UNIQUe )
INSERT INTO tab1 VALUES (1,NULL),(2,1)
INSERT INTO tab1 VALUES (2,1)
Duplicate entry '1' for key 'tab1.col2'
SELECT col1,IFNULL(col2,1111) FROm tab1
col1 | IFNULL(col2,1111)
---: | ----------------:
1 | 1111
2 | 1
db<>fiddle here
Actually you could not use unique with default value. because the point of unique in MySql is preventing duplicates in column. Which making conflicts in that logic.
You must handle the duplication before sending the insert query to DB (in Backend) or you may use techniques other than unique like:
INSERT IGNORE: will insert rows in the same way as INSERT, but with the exception that it will ignore rows with duplicate values and continue execution without creating an error. Any row that contains a duplicate value will not be inserted.
INSERT ... ON DUPLICATE KEY UPDATE: will insert any non-duplicate rows as normal. However, when it encounters a duplicate row, it will perform an UPDATE on the original row.
REPLACE: works the same as INSERT, except that when it encounters a duplicate row, it deletes the original row and then continues with the insert. Any row with a duplicate unique index value will replace the row that originally contained the value.

Get the last primary key from table with no auto increment

I have a table that has a primary key and for some reason i was advised not to use the AUTO_INCREMENT flag.
So every time i have to insert a new entry i search for the last value inserted (highest value) of the primary key.
Then i increment it by 1 to get a new ID.
Now the problem i face is, when inserting the first entry, there is no data in the table.
Can anyone suggest the optimal way to check
if data exists in table,
if not set id as 1 and insert new row,
else get the last id from table, increment it by 1 and then insert new row.
PS: New to mysql so having difficulty with its syntax.
Based on your statement 'i search for the last value inserted (highest value) of the primary key', I presume that you're currently doing something like this to get the maximum existing ID:
SELECT MAX(id_column) + 1 FROM my_table
If you have an empty table, this will of course return NULL. In that case, just handle the NULL using IFNULL to return 0 if there is no maximum value:
SELECT IFNULL(MAX(id_column), 0) + 1 FROM my_table
This will output 1 as the next identifier if the table has no rows.
I've given this more thought, and it turns out there is a way to generate a unique primary key without using Auto Increment or worrying about race conditions, so long as you are willing and able to use a 36 byte primary key (or, alternatively, a 128 bit binary).
The solution (at least as of MySQL 5.5) is the UUID, which stands for Universal Unique Identifier.
You would use it thus:
CREATE TABLE uu_table (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(50),
{other interesting columns}
)
Then insert new rows thus:
INSERT INTO uu_table VALUES (UUID(), 'Name of this Row', {other interesting values});
The UUID() function is guaranteed to generate a unique key 99.99{bunch more 9's}% of the time, even if generated on independent systems. That's its whole purpose, to be as unique as snowflake patterns, no matter where it is created.
There are pros and cons to this method. Best to read up on it here: https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_uuid
It is basically a 128 bit number, which you can save as a binary value after conversion from the 36 characters. I believe some versions of MySQL come with functions for that purpose. That would use less space in your database than 36 bytes, but I'll leave that as an exercise for the reader.

MySQL Duplicate Entry Error on non-primary key

I have a table defined with a single primary/auto-increment key.
When I call the following query I receive an error.
INSERT INTO device_sensor_reading (`we_id`, `UNIX_time`, `temp_we_id`, `reading_format_id`,`log_id`, `msg_type`, `device_position`) VALUES
(79995, 1550896918, 0, 3, 1, 0,1);
Error: 08:43:39 call sits_db.Insert Simulated Data() Error Code: 1062. Duplicate entry '79995-1550896918' for key 'we_id_UNIX_time' 0.063 sec
Neither we_id or UNIX_time are specified as UNIQUE in my table so why does MySQL give me this error?
There is a combined UNIQUE KEY. MySQL allows you to combine two columns, which results that only the combination of both values is unique.
In your table you specified w_id, temp_w_id , in your query are we_id and temp_we_id, now, check if you have any value with this entry in two fields. Now is the same with log_id... Maybe unique field is repeating

MySQL Error: Duplicate entry 'xxx' for Primary Key

I have table MySQL with Primary Key Composed of 2 fields, as below
Already existing records in the table are:
The INSERT query I am issuing is:
When I run the query:
INSERT INTO `case_data`
VALUES ('WCD/2016/1000017', 2, '2016-09-29', 'WCD',***********************
The error message displayed is:
[Err] 1062 - Duplicate entry 'WCD/2016/1000017' for key 'PRIMARY'
Am I violating the Primary Key constraint?
Thanks in advance.
You could check if the primary key values of a row you are trying to insert already exist in a table:
SELECT COUNT(*)
FROM case_data
WHERE caseno = 'WCD/2016/1000017' AND iteration = 2;
If it returns 0 then you will not violate the PK constraint and are safe to insert the row you wish (assuming there are no additional checks, triggers, constraints). Otherwise it will return 1 which means that you already have a row with values in those columns, thus you would violate uniqueness of the row which is not allowed.
When it returns 0 just issue an INSERT command. Also, remember to specify your column tables within the statement to make sure every value from your VALUES is being put within the right column of your destination table:
INSERT INTO case_data (caseno, iteration, casedate, casetype)
VALUES ('WCD/2016/1000017', 2, '2016-09-29', 'WCD');
Avoid using backticks around your column and table names if they don't contain alternative characters like commas or spaces. This will make your code more readable and definitely speed up your writing time.

MySQL: Increment value if exists, create if not (multiple criteria)

I have a table with three columns ('xCoord', 'yCoord' and 'Total'). I want to increment the Total value if the x,y coordinate pair already exists, else I want to create a new row with the new x and y values with Total = 1.
Below is my best attempt so far - running the query for the first time adds a new line (as expected), running it a second time adds a new line instead of incrementing the previously created line though? Is there a way to perform this with action with a single query?
INSERT
INTO tbl_DATA_HeatmapValues (xCoord, yCoord, Total)
VALUES (11, 22, 1)
ON DUPLICATE KEY
UPDATE Total = Total + 1
Your query should work, but you need to have a unique index. The check, if a row already exists is based on the index, not the actual data in the row. No index, no checking if it exists, therefore inserting no matter what.
INSERT ... ON DUPLICATE KEY UPDATE performs an update only where the insert would cause a duplicate value(s) in a UNIQUE index or PRIMARY KEY, see this link for details: http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Consider creating an unique index on xCoord, yCoord columns:
CREATE UNIQUE INDEX ON tbl_DATA_HeatmapValues (xCoord, yCoord)