'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


Solution 1:[1]

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

Solution 2:[2]

Simply:

SELECT count(*), CAST(lastname as BINARY) AS lastname_cs 
FROM names 
GROUP BY lastname_cs; 

Solution 3:[3]

In MySQL/MariaDB, if you don't want to use collations or casting to binary, just use:

SELECT MAX(name), COUNT(name)
FROM (
  select 'Test' as name
  UNION ALL
  select 'TEST'
  UNION ALL
  select 'test'
  UNION ALL
  select 'test'
  UNION ALL
  select 'tester'
  UNION ALL
  select 'tester'
) as tmp
group by MD5(name)

Solution 4:[4]

This works on my case:

SELECT BINARY example FROM table GROUP BY BINARY example;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thomas
Solution 2 Jordan DjMo
Solution 3 David Vielhuber
Solution 4 Alessandro