Skip to content
Advertisement

SQL case sensitive compare

I like to know with a CASE statement wether two fields are the same.

I managed to do it with following query but I wonder if there is a better approach? I just want the ‘=’ to do a case sensitive compare. I tried with COLLATE but then I need to use a WHERE clause which filters my results, I want all the rows. And with HASHBYTES it seems overkill especially when I need to combine it with ISNULL

DECLARE @myTable AS TABLE (old varchar(255), new varchar(255));
INSERT INTO @myTable VALUES
    ('test', 'test'),
    ('test', 'TEST'),
    (null, null)


SELECT old, new, 
    CASE WHEN HASHBYTES('SHA2_512', old) = HASHBYTES('SHA2_512', new) THEN 'same' ELSE 'changed' END AS updated,
    CASE WHEN HASHBYTES('SHA2_512', ISNULL(old, '')) = HASHBYTES('SHA2_512', ISNULL(new, '')) THEN 'same' ELSE 'changed' END AS updated_isnull
FROM @myTable
--where old = new COLLATE Latin1_General_CS_AS

I need column ‘updated_isnull’

| old  | new  | updated | updated_isnull |
| ---- | ---- | ------- | -------------- |
| test | test | same    | same           |
| test | TEST | changed | changed        |
| NULL | NULL | changed | same           |

Advertisement

Answer

The proper solution would be to fix your columns so your data is stored in a case-sensitive collation. Then you would just do:

select old, new,
    case when old = new
             or (old is null and new is null)
         then 1
        else 0 
    end as is_same
from @mytable

Using a case-insensitive collation, we could work around like this

select old, new,
    case when old collate Latin1_General_Bin = new collate Latin1_General_Bin 
             or (old is null and new is null)
         then 1
        else 0 
    end as is_same
from @mytable

Demo on DB Fiddle:

old  | new  | is_same
:--- | :--- | ------:
test | test |       1
test | TEST |       0
null | null |       1
7 People found this is helpful
Advertisement