209

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?

2
  • 1
    Use COLLATE Commented Oct 22, 2011 at 6:03
  • 1
    The top answer is better than COLLATE, imo, because it is simpler. Commented Oct 13, 2015 at 20:37

3 Answers 3

476

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'
Sign up to request clarification or add additional context in comments.

1 Comment

1) using binary for this purpose is risky because it is literally going to compare the bytes of the two strings. If your default server/session charset does not match the charset of the column then accent characters will be considered not equal (i.e. ü in latin1 is 0xFC where as in utf8mb4 it is 0xC3Bc). 2) As Shenxian points out below, you should apply your conversion to the parameter rather than the column. It will have to same functional effect but it will allow the query to use an index if one is present on your column.
126

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.

2 Comments

How to add it in "LIKE"?
@Purushotamrawat just replace = with LIKE ... SELECT * FROM table WHERE column LIKE BINARY '%value%'
33

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.

2 Comments

I've edited to fix what I'm pretty sure was a silly typo that was precisely the opposite of what you wanted to say. I feel like I ought to notify you, though (and since it's a two-character change the site won't notify you automatically). Assuming you're happy with the change, feel free to just flag my comment as obsolete and let it be nuked. (And if I've screwed up, shout at me.)
For more recent versions of MySql you should replace the deprecated utf8 with utf8mb4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.