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?
DISTINCT and Collations My SQL Server installation uses the SQL_Latin1_General_CP1_CI_AS collation, which is case-insensitive.
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.
You can only apply distinct to the column expression, not to the THEN clause within the CASE.
If you want case-insensitive distinct, you need to use UPPER() or LOWER(). Case 1: Using UPPER().
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With