Like Case Sensitive in MySQL

Solution 1:

A much better solution in terms of performance:

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

String comparision is case-sensitive when any of the operands is a binary string.

Another alternative is to use COLLATE,

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

Solution 2:

Try this:

SELECT LOWER(CONCAT_WS(title,description)) AS concatenated 
WHERE concatenated LIKE '%searchterm%'

or (to let you see the difference)

SELECT LOWER(CONCAT_WS(title,description)) AS concatenated 
WHERE concatenated LIKE LOWER('%SearchTerm%')

Solution 3:

In this method, you do not have to select the searched field:

SELECT table.id 
FROM table
WHERE LOWER(table.aTextField) LIKE LOWER('%SearchAnything%')

Solution 4:

Check CHARSET mentioned in the table schema:

show create table xyz;

Based on CHARSET, you can try the following.

select name from xyz where name like '%Man%' COLLATE latin1_bin;
select name from xyz where name like '%Man%' COLLATE utf8_bin;

Following are the cases which worked for me, CHARSET=latin1, MySQL version = 5.6.

mysql> select installsrc from appuser where installsrc IS NOT NULL and installsrc like 'Promo%' collate latin1_bin limit 1;
+-----------------------+
| installsrc            |
+-----------------------+
| PromoBalance_SMS,null |
+-----------------------+
1 row in set (0.01 sec)

mysql>
mysql> select installsrc from appuser where installsrc IS NOT NULL and installsrc like 'PROMO%' collate latin1_bin limit 1;
+---------------------------+
| installsrc                |
+---------------------------+
| PROMO_SMS_MISSEDCALL,null |
+---------------------------+
1 row in set (0.00 sec)

mysql> select installsrc from appuser where installsrc IS NOT NULL and installsrc like 'PROMO%' limit 1;
+-----------------------+
| installsrc            |
+-----------------------+
| PromoBalance_SMS,null |
+-----------------------+
1 row in set (0.01 sec)

Solution 5:

Just for completion, in case it helps:

As stated on https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html, for default character sets, nonbinary string comparisons are case insensitive by default.

Therefore, an easy way to perform case-insensitive comparisons is to cast the field to CHAR, VARCHAR or TEXT type.

Here is an example with a check against a single field:

SELECT * FROM table1 WHERE CAST(`field1` AS CHAR) LIKE '%needle%';