Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT DISTINCT should be case sensitive?

How do I make MySQL's SELECT DISTINCT case sensitive?

create temporary table X (name varchar(50) NULL);
insert into X values ('this'), ('This');

Now this query:

select distinct(name) from X;

Results in:

this

What's going on here? I'd like SELECT DISTINCT to be case sensitive. Shouldn't that be the default?

like image 583
ishmael Avatar asked Oct 19 '13 05:10

ishmael


People also ask

Is distinct in SQL case-sensitive?

DISTINCT and Collations My SQL Server installation uses the SQL_Latin1_General_CP1_CI_AS collation, which is case-insensitive.

Is MySQL select case-sensitive?

By default, it depends on the operating system and its case sensitivity. This means MySQL is case-insensitive in Windows and macOS, while it is case-sensitive in most Linux systems. However, you can change the behavior by changing collation.

Can we use distinct in case?

You can only apply distinct to the column expression, not to the THEN clause within the CASE.

Would you make a case-insensitive query in MySQL?

If you want case-insensitive distinct, you need to use UPPER() or LOWER(). Case 1: Using UPPER().


2 Answers

Use BINARY operator for that:

SELECT DISTINCT(BINARY name) AS Name FROM X;

You can also CAST it while selecting:

SELECT DISTINCT 
(CAST(name AS CHAR CHARACTER SET utf8) COLLATE utf8_bin) AS Name FROM X;

See this SQLFiddle

like image 90
Himanshu Jansari Avatar answered Oct 20 '22 23:10

Himanshu Jansari


I would rather update the column definition to be case sensitive collision.

Like this:

create table X (name VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin NULL);
insert into X values ('this'), ('This'); 

SQLFiddle: http://sqlfiddle.com/#!2/add276/2/0

like image 37
Roberto Navarro Avatar answered Oct 20 '22 23:10

Roberto Navarro