Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"SELECT DISTINCT" ignores different cases

Tags:

sql

sql-server

I have the problem, that MSSQL Server 2000 should select some distinct values from a table (the specific column is of the nvarchar type). There are the sometimes the same values, but with different cases, for example (pseudocode):

SELECT DISTINCT * FROM ("A", "a", "b", "B") 

would return

A,b 

But I do want (and do expect)

A,a,b,B 

because they actually are different values.

How to solve this problem?

like image 359
powerbar Avatar asked Apr 15 '10 11:04

powerbar


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.

Can you use SELECT distinct with multiple columns?

In SQL multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.

Does SELECT distinct apply to all columns?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.

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

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


2 Answers

The collation will be set to case insensitive.

You need to do something like this

Select distinct col1 COLLATE sql_latin1_general_cp1_cs_as From dbo.myTable 
like image 86
codingbadger Avatar answered Sep 21 '22 21:09

codingbadger


Not sure about MS SQL but with MySQL or postgres, use BINARY for this operation. Cast the column to binary like so:

SELECT DISTINCT BINARY(column1) from table1; 

Just change column1 and table1 as per your schema.

Full example that works for me in MySQL 5.7, should work for others:

SELECT DISTINCT BINARY(gateway) from transactions; 

Cheers!

like image 36
radtek Avatar answered Sep 22 '22 21:09

radtek