I have a user table as follow:
CREATE TABLE `user` (
`Id` bigint NOT NULL AUTO_INCREMENT,
`FirstName` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci NOT NULL
-- more column
);
Now when I run the following procedure:
CREATE PROCEDURE myProc ()
BEGIN
SET @searchTerm = '%';
SELECT * FROM user WHERE FirstName like @searchTerm;
END
I get the exception:
Illegal mix of collations (utf8mb4_unicode_520_ci,IMPLICIT) and
(utf8mb4_0900_ai_ci,IMPLICIT) for operation ‘like’ 0.000 sec
I have set the character CHARACTER and COLLATE for the entire DB as follow:
ALTER DATABASE mydb CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_520_ci;
Not sure why my variable @searchTerm has utf8mb4_0900_ai_ci
for COLLATE
?
Update
Originally, when I asked the question, I did not mention that I was running the following script inside the stored procedure:
SET @searchTerm = '%';
SELECT * FROM user WHERE FirstName like @searchTerm;
I had to update the question, as it turned out that this was the issue.
2
Answers
The issue was that I had to drop and recreate the stored procedure after changing the CHARACTER SET and COLLATE, i.e. running the following script:
Thanks to @Paul Maxwell comment, about restarting the DB, which was a good hint to find the issue.
The issue is the collation mismatch between the
FirstName
column and the@searchTerm
variable is due to MySQL’s collation handling rules.In your query the
FirstName
column is using theutf8mb4_unicode_520_ci
collation, but the@searchTerm
variable is using theutf8mb4_0900_ai_ci
collation. When you perform aLIKE
comparison between these two with different collations, you get theIllegal mix of collations
error.You have to ensure that the variable
@searchTerm
uses the same collation as theFirstName
column.