Wednesday, December 24, 2003

Doing case sensitive searches

As we know, by default SQL Server installation (6.5/7/0/2K) is case insensitive. What does that mean? The DB would consider the string "VADIVEL" & "vadivel" as same. Perfect! But what if we want to do a case sensitive search in a database. i.e., we want to search for a string "SMART" (Note all characters should be capitals/upper case).

If we do a normal select query as shown below it won't work because as said earlier SQL Server installation by default is case insensitive

Select *
from testTable
where testField = 'SMART'


In order to overcome this situation, we need to select binary sort order (or) collation while installing SQL Server. After that one way is we need to convert the strings into binary and then compare. Since, 'S' and 's' have different ASCII values, when you convert them to binary, the binary representations wouldn't match and you could get case sensitive results.

For example,

Select *
from testTable
where cast ( testField as varbinary(25)) = cast('SMART' as varbinary(25))


Though the above query solves our purpose as far as performance (!) is concerned it wouldn't make use of Index (if we have one on the field testField) as our column name is within a function "CAST". Here I have added redundant :-) testField column so the optimizer would check for indexed values for testField before entering the Cast function

Select * from testTable
where testField = 'SMART'
and
cast(testField as varbinary(25)) = cast('SMART' as varbinary(25))

Another way of searching for case-sensitive data is by using Binary_Sum() function. For example,

Select * from testTable
where testField = 'SMART' and
binary_checksum(testField) = binary_checksum('SMART')