Home > Database > Mysql Tutorial > Why are MySQL LIKE Queries Case-Sensitive with utf8_general_ci Encoding?

Why are MySQL LIKE Queries Case-Sensitive with utf8_general_ci Encoding?

Susan Sarandon
Release: 2024-11-09 18:05:02
Original
459 people have browsed it

Why are MySQL LIKE Queries Case-Sensitive with utf8_general_ci Encoding?

Case Sensitivity in MySQL LIKE Queries

Problem:

Consider the following MySQL query:

SELECT concat_ws(title, description) as concatenated
HAVING concatenated LIKE '%SearchTerm%';
Copy after login

Despite using the LIKE operator, searches appear to be case sensitive when the table encoding is utf8_general_ci with a MyISAM storage engine.

Explanation:

The MyISAM storage engine uses case-insensitive comparisons for strings stored in utf8_general_ci encoding. However, the LIKE operator performs case-sensitive comparisons by default.

Optimal Solution:

To perform case-insensitive comparisons, use the BINARY keyword as follows:

SELECT ....
FROM ....
WHERE `concatenated` LIKE BINARY '%SearchTerm%';
Copy after login

String comparisons become case-sensitive when one of the operands is a binary string.

Alternative Solution:

Alternatively, use the COLLATE statement to specify a locale-specific collation:

SELECT ....
FROM ....
WHERE `concatenated` like '%SearchTerm%' COLLATE utf8_bin;
Copy after login

This approach allows for case-insensitive comparisons while maintaining the original character encoding.

The above is the detailed content of Why are MySQL LIKE Queries Case-Sensitive with utf8_general_ci Encoding?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template