How To do Case Sensitive String Match in SQL Server
How To do Case Sensitive String Match in SQL Server
In this post we will try to understand how can we perform case sensitive search/ string match in SQL server. As most of us continue to use SQL server with the default setup where the regular string match is case-insensitive.
So, to understand the concept let's take an example.
Let say we have a table with 2 columns ID and UserName, i.e., like this.
CREATE TABLE TestTable (
Id int,
[UserName] varchar(255)
);
Also let's add some data to our table using the following script.
insert into TestTable Values (1,'Kumar');
insert into TestTable Values (2,'Prateek');
insert into TestTable Values (3,'Kumar Prateek');
insert into TestTable Values (4,'KUMAR');
insert into TestTable Values (5,'PRATEEK');
insert into TestTable Values (6,'KUMAR PRATEEK');
And so, the data in our table looks like this.
Id UserName
1 Kumar
2 Prateek
3 Kumar Prateek
4 KUMAR
5 PRATEEK
6 KUMAR PRATEEK
Now let's try to do some searches.
Query #1:
select * from TestTable where [UserName] ='Kumar'
Response:
Id UserName
1 Kumar
4 KUMAR
Query #2:
select * from TestTable where [UserName] ='KUMAR'
Response:
Id UserName
1 Kumar
4 KUMAR
As we can see that in both Query #1 and #2 the response is same even though we are trying to look for a user with username as "Kumar" or "KUMAR", which may not be true all the time as we might want to keep our data (usernames in this example) case sensitive in some cases.
So, the solution to this is to append our query with COLLATE Latin1_General_CS_AS for whichever column we wanted to perform the case sensitive search.
So, let’s now try to use it and see the difference.
Updated Query #1:
select * from TestTable where [UserName] ='Kumar' COLLATE Latin1_General_CS_AS
Response:
Id Name
1 Kumar
Updated Query #2:
select * from TestTable where [UserName] ='KUMAR' COLLATE Latin1_General_CS_AS
Response:
Id Name
4 KUMAR
Also, if we want to do this similarly on queries with IN condition we can do that to like:
select * from TestTable where [UserName] IN ('Kumar', 'KUMAR') COLLATE Latin1_General_CS_AS
So, we got what we were looking for as an output. Now interesting thing is that we can do this at SQL server level, Database level and even at column level when we define them respectively over and above the way we saw on how to use it in the SQL queries. By the way the default COLLATE which we continue to use SQL server is SQL_Latin1_General_CP1_CI_AS.
Hope you liked the post, do provide inputs in the comment, also if you think the article will be helpful for any of your friends and relatives then please do share the article with them.
And don't forget to subscribe for the new post available so that you get notified on your mailbox.
Happy Learning. 📚
Comments