Mysql 5.5.54 Duplicate entry on unique key with multiple columns - mysql

We have table in production (locally I try to do same thing, everything works as expected, maybe I have newer db version).
Table contains many columns, two of them is number AND year. These columns are bound with unique constraint key.
When I do query such as
SELECT * FROM `order` WHERE number IS NULL AND YEAR = 2018
I get more than one row. And it's not important, it's correct. [I could have 100 rows with null, 2018 for example]
But when I try to insert new record with number = null and year = 2018. I get error such as
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2018' for key 'number_year_UNIQUE'
One thing which comes in mind is that null in mysql is hiddenly bound with random number, and when I try to insert it's somehow becomes duplicate for new record.
As extra info is: We use Yii1 and error appears through ActiveRecord.
EDIT
After suggeestion added profiling got bound params
They are as follow
:yp13='2018',
:yp14='',
Exactly same parameters are on local machine.
EDIT

did you tried to run the insert query from from sql console(PhpMyAdmin or similar)?
I doubt it's an issue in the php side like the way you pass null value.

The problem was in that I tried to insert empty string '' not null value, as stated above (seen on screenshot).
In code I had something like
$order = new Order();
//some other stuff
$order->number = null;
$order->save();
However, in rules (in newly added validation method, number became empty string)
Added scenario (Yii specific) and problem had gone.

Related

MySQL export/import empty/null multilinestring

Using phpMyadmin
I have exported a database which has a table with a spatial multilinestring field. Some of the records in this table have a null entry in this field.
When trying to import, the table fails the import with this message.
1416 - Cannot get geometry object from data you send to the GEOMETRY field
What do I need to replace the null value with for records where this field is not required?
I finally worked this out so posting back in case anyone else struggles with this.
It was not to do with null entries as I first thought. In phpMyAdmin, the insert scripts batch the inserts together. if you select the option 'include column names in every INSERT statement', each record will have it's own insert statement.
Then when you import, it will show you which record is failing. It was not failing on a null entry.
I then ran a query on the failing record like this to view the points in the multilinestring
SELECT ST_ASTEXT(Polylines) FROM myTable WHERE id = 100
This showed me that there was only 1 point in one of the Polylines. This was the issue. Importing a polyline with only 1 point into MySQL fails - which makes sense (but it did allow the record to be inserted in the first place). In my case, I set the single point polylines to null to fix this issue.
I was exporting and importing from the same versions of mySQL : 5.7.26

Error: Duplicate entry '' for key 'email'

I have seen this error with people running php scripts before but this is happending to me in phpmyadmin ??
Error
SQL query:
UPDATE `cl56-goldeng`.`users` SET `email` = '' WHERE `users`.`id` =118
MySQL said: Documentation
#1062 - Duplicate entry '' for key 'email'
It works fine if I give the field another value, but if I clear the field and press enter I get the above error.
The table itself looks like this :
On your table cl56-goldeng.users, the field email was specified on creation to not allow more than 1 of the same value to be allowed into it. This is done using the UNIQUE identifier on table creation in MySQL. You can see more on the UNIQUE identifier at this link.
You have 2 options that you could go about doing.
First would be to remove the unique constraint on the email field. This entirely depends on your logic in your code, but seeing as emails should almost always be unique, this is not suggested.
You can drop a unique key by running the command:
alter table [table-name] drop index [unique-key-index-name];
Second, would be to use NULL instead of an empty string. My assumption is that you are setting an empty string when the users email does not exist. In this scenario, it would be better to use NULL, and then check for that when retrieving data from the database.
You can insert a NULL value by using the NULL identifier in your MySQL statement, like such:
INSERT INTO users (firstName,lastName,email)
VALUES ('Bob','Ross',NULL);
And then check for a NULL value in whatever language you are accessing this data from.
You have a unique constraint on your email field. Either rethink your logic or drop the unique constraint.
Thats because you may have declare the email as unique key, and once you enter one row of empty email, it wont except another empty email

Why does MySQL think that I'm not using a WHERE statement?

I'm trying to update a table called rep in a database called premier_products. The table's primary key is rep_num.
When I run the following statement:
update rep
set last_name = "Perry"
where rep_num = 85;
I get an error that says "You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column."
I Googled that error message and most of the responses were along the lines of "You have to use a where clause or turn off safe mode". But as you can see, I am using a where clause. Why is the error appearing if I have a where clause?
MySQL server version 5.6.20.
This image shows that rep_num is definitely my primary key:
This image shows the current rep table:
Although you save only numbers, your primary-key type is char(2) and not tinyint(2) and when you update the record you are giving numerical value instead char value in your where condition. I think thats where the indexing mechanism triggers the error and tells you, your where condition is unsafe or might yield wrong results.
in your case try
update rep
set last_name = "Perry"
where rep_num = '85';
PS: why don't you name your tables with a prefix? like tbl_rep? just a thought.

MySQL DUPLICATE KEY UPDATE fails to update due to a NOT NULL field which is already set

I have a MySQL DB which is using strict mode so I need to fill all NOT NULL values when I insert a row. The API Im creating is using just DUPLICATE KEY UPDATE functionality to do both inserts/updates.
The client application complains if any NOT NULL attributes are inserted which is expected.
Basic example (id is primary key and theare are two fields that are NOT NULL aaa and xxx)
INSERT INTO tablename (aaa, xxx, id ) VALUES ( "value", "value", 1)
ON DUPLICATE KEY UPDATE aaa=VALUES(aaa), xxx=VALUES(xxx)
All good so far. Once it is inserted, the system would allow doing updates. Nevertheless, I get the following error when updating only one of the fields.
INSERT INTO tablename (aaa, id ) VALUES ( "newValue", 1)
ON DUPLICATE KEY UPDATE aaa=VALUES(aaa)
java.sql.SQLException: Field 'xxx' doesn't have a default value
This Exception is a lie as the row is already inserted and xxx attribute has "value" as value. I would expect the following sentence to be equivalent to:
UPDATE tablename SET aaa="newValue" WHERE id=1
I would be glad if someone can shed some light about this issue.
Edit:
I can use the SQL query in PhpMyAdmin successfully to update just one field so I am afraid that this is not a SQL problem but a driver problem with JDBC. That may not have solution then.
#Marc B: Your insight is probably true and would indicate what I just described. That would mean that there is a bug in JDBC as it should not do that check when the insert is of ON DUPLICATE type as there may be a default value for the row after all. Can't provide real table data but I believe that all explained above is quite clear.
#ruakh: It does not fail to insert, neither I am expecting delayed validation. One requirement I have is to have both insert/updates done using the same query as the servlet does not know if the row exists or not. The JAVA API service only fails to update a row that has NOT NULL fields which were already filled when the insert was done. The exception is a lie because the field DOES have a default value as it was inserted before the update.
This is a typical case of DRY / SRP fail; in an attempt to not duplicate code you've created a function that violates the single responsibility principle.
The semantics of an INSERT statement is that you expect no conflicting rows; the ON DUPLICATE KEY UPDATE option is merely there to avoid handling the conflict inside your code, requiring another separate query. This is quite different from an UPDATE statement, where you would expect at least one matching row to be present.
Imagine that MySQL would only check the columns when an INSERT doesn't conflict and for some reason a row was just removed from the database and your code that expects to perform an update has to deal with an exception it doesn't expect. Given the difference in statement behaviour it's good practice to separate your insert and update logic.
Theory aside, MySQL puts together an execution plan when a query is run; in the case of an INSERT statement it has to assume that it might succeed when attempted, because that's the most optimal strategy. It prevents having to check indices etc. only to find out later that a column is missing.
This is per design and not a bug in JDBC.

Error with inserting into mysql database

I am using cfwheels (coldfusion orm framework).
I recently moved some data from my previous host to a new one. Now I am trying to insert into a table, but am getting an error message: "Error Executing Database Query.
Duplicate entry '13651' for key 'PRIMARY'"
I looked into the database and it appears a record with id 13651 already exists. So I think the problem is with mysql generating the right auto increment value.
It seems Auto_Increment value is damaged or not set to max value in that column. It's possible due to bulk insert.
So as per solution, set the maximum PK value + 1 as new AUTO_INCREMENT value. Now when you insert the records in this table, they will automatically pick the next incremented correctly.
ALTER.TABLE tablename AUTO_INCREMENT = value
Is the rest of the data for that record, and the one you are trying to insert, the same? If you you might just need to tell the ORM to replace that value?
If primary key has auto increment attribute turned on, do not insert it manually. remove that primary key part from your insert query (whatever the syntax according to the taste of your ORM framework).