Case Sensitive or Insensitive SQL Query

Suppose you need to perform a SQL query and you need for it to be case sensitive or case insensitive, and either your database is set up the opposite way or you're smart and you're trying to write your query so that it will work regardless of how the database may or may not be configured. For instance, consider this query:

SELECT UserId, email
FROM UserInfo
WHERE email =
'ashvin@padhiyar.com'

If your database contains an email for Bill like this one: ASHVIN@padhiyar.com then whether or not your query will return any rows will depend on the COLLATION for the database. If you want to ensure that you DO get results, you can force it to use a CASE INSENSITIVE collation like so:

SELECT UserId, email
FROM
UserInfo
WHERE email = 'ashvin@padhiyar.com' COLLATE SQL_Latin1_General_CP1_CI_AS

Similarly, if you don't want it to return any rows unless you specify the correct case for the email, you would change the collation to replace _CI_ with _CS_ where CI is short for Case Insensitive and CS is short for Case Sensitive. The following query would not match ASHVIN@padhiyar.com because it is using a case sensitive collation.

SELECT UserId, email
FROM UserInfo
WHERE email =
'ashvin@padhiyar.com' COLLATE SQL_Latin1_General_CP1_CS_AS

Also note that most of the time, passwords are expected to be case sensitive, so you can improve the security of your system by forcing any check comparing the password to use case sensitivity. However, if you're using hashed passwords (which you should be) then this is a non-issue since your hash algorithm will likely return all caps or all lowercase depending on how it is configured, and as long as you use the same hash settings when you set the password and when you check it, the collation of the database will not matter.

Comments

Popular posts from this blog

Page Life Cycle in ASP.NET

Managed Code and UnManaged Code

Print Function By JavaScript

Select nth Row from Table in SQL Server

SQL Server 2005 with XML Parameters

Variable Value in Top Statement

Email Validation by Javascript

Overview of MVC