Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a case sensitive GROUP BY?

If I execute the code below:

with temp as (   select 'Test' as name   UNION ALL   select 'TEST'   UNION ALL   select 'test'   UNION ALL   select 'tester'   UNION ALL   select 'tester' ) SELECT name, COUNT(name) FROM temp group by name 

It returns the results:

TEST   3 tester 2 

Is there a way to have the group by be case sensitive so that the results would be:

Test   1 TEST   1 test   1 tester 2 
like image 213
Abe Miessler Avatar asked Jun 08 '12 16:06

Abe Miessler


People also ask

Can you use case in group by?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.

Is Groupby case sensitive?

If the User Locale is set to 'English', the GROUP BY in the SOQL behaves as case insensitive but for other user locales, it behaves as case sensitive.

How do I select case sensitive in SQL?

The SQL case sensitivity can be set for non-keyword objects such as tables and columns by specifying the collation against the database, tables, and column level by mentioning CI or CS in it that stands for case insensitive and case sensitive respectively.

How do I make a SQL table case sensitive?

COLUMNS WHERE TABLE_NAME = '<Name of the table that contains the column(s) you want to check>' If the output of the field contains 'CI', like in 'Latin1_General_CI_AI' then the column is case insensitive. If the output of the field contains 'CS', like in 'Latin1_General_CS_AS' then the column is case sensitive.


2 Answers

You need to cast the text as binary (or use a case-sensitive collation).

With temp as (   select 'Test' as name   UNION ALL   select 'TEST'   UNION ALL   select 'test'   UNION ALL   select 'tester'   UNION ALL   select 'tester' ) Select Name, COUNT(name) From temp Group By Name, Cast(name As varbinary(100)) 

Using a collation:

Select Name Collate SQL_Latin1_General_CP1_CS_AS, COUNT(name) From temp Group By Name Collate SQL_Latin1_General_CP1_CS_AS 
like image 123
Thomas Avatar answered Sep 28 '22 03:09

Thomas


You can use an case sensitive collation:

with temp as (   select 'Test' COLLATE Latin1_General_CS_AS as name   UNION ALL   select 'TEST'   UNION ALL   select 'test'   UNION ALL   select 'tester'   UNION ALL   select 'tester' ) SELECT name, COUNT(name) FROM temp group by name 
like image 32
Lamak Avatar answered Sep 28 '22 05:09

Lamak