Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making MySQL IN Clause Case Sensitive

Does anyone know how I can make an IN clause behave in a case sensitive manner? I have seen that COLLATE can be used with LIKE for string searching but I don't know if or how it can be used with IN. For example I want to do something like

SELECT * FROM pages_table WHERE topic IN ('Food','NightLife','Drinks')

And I want it to return pages where the topic is 'Food' but not those where the topic is 'food' which is currently what happens on this query. Thanks.

like image 876
hackartist Avatar asked Nov 12 '12 23:11

hackartist


People also ask

Can MySQL be case-sensitive?

Table names are stored in lowercase on disk and name comparisons are not case-sensitive. MySQL converts all table names to lowercase on storage and lookup. This behavior also applies to database names and table aliases.

Is the IN clause for SQL case-sensitive?

Let's start there. Keywords in SQL are case-insensitive for the most popular DBMSs. The computer doesn't care whether you write SELECT , select, or sELeCt ; so, in theory, you can write however you like. Unfortunately, it is a little bit different in practice.

How would you make a case-insensitive query in MySQL?

The syntax is as follows: SELECT DISTINCT UPPER(yourColumnName) FROM yourTableName; Case 2: Using LOWER(). Here is the query to select case-insensitive distinct.

How do I make SQL queries case-sensitive?

SQL Server is, by default, case insensitive; however, it is possible to create a case-sensitive SQL Server database and even to make specific table columns case sensitive. The way to determine if a database or database object is to check its "COLLATION" property and look for "CI" or "CS" in the result.


2 Answers

You can actually use it as you have likely seen in other examples:

SELECT *
FROM pages_table
WHERE CAST(topic AS CHAR CHARACTER SET latin1)
        COLLATE latin1_general_cs IN ('Food','NightLife','Drinks')

This changes the character set into one that supports case sensitivity and then collates the column (you may not have to do this depending on your own character encoding).

like image 105
RocketDonkey Avatar answered Sep 28 '22 06:09

RocketDonkey


You can use the BINARY operator. Something like:

SELECT *
FROM pages_table
WHERE CAST(topic AS BINARY) IN ('Food','NightLife','Drinks');

SQL Fiddle Demo

like image 33
Mahmoud Gamal Avatar answered Sep 28 '22 06:09

Mahmoud Gamal