MySQL case sensitive query

MysqlCase Sensitive

Mysql Problem Overview


This has been asked on this site before but I couldn't find a sufficient answer. If I'm doing a query like:

Select Seller from Table where Location = 'San Jose'

How can I make it return only Sellers with Location 'San Jose' instead of 'san jose' or something else?

Mysql Solutions


Solution 1 - Mysql

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

Solution 2 - Mysql

To improve James' excellent answer:

It's better to put BINARY in front of the constant instead:

SELECT * FROM `table` WHERE `column` = BINARY 'value'

Putting BINARY in front of column will prevent the use of any index on that column.

Solution 3 - Mysql

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael LiaoView Question on Stackoverflow
Solution 1 - MysqlJames masonView Answer on Stackoverflow
Solution 2 - MysqlShenxianView Answer on Stackoverflow
Solution 3 - MysqlThomas ClowesView Answer on Stackoverflow