Sql Server Ignore Case in a Where Expression
For case-insensitive matching in SQL Server, both sides of the equation can be normalized using UPPER() or LOWER():
However, to fully leverage SQL Server's capabilities, specify a collation:
This SQL_Latin1_General_CP1_CI_AS
collation treats 'Value', 'VALUE', and 'value' as identical.
Quick COLLATE crash course
COLLATE can be defined at different levels; within a query, for a column, or for the entire database. So, if the default case sensitivity of SQL Server or your database's collation doesn't suit your current needs, use COLLATE within your WHERE clause:
Regardless of how 'John' is spelled (maybe 'JOHN' or even 'joHn'), SQL Server will fetch the correct rows.
Know your collation
The collation of a database or column can override the default collation of SQL Server, which is usually case-insensitive. If you need to identify a column's collation, use this handy query:
Common traps you might fall into
When dealing with case-insensitivity in your SQL Server queries:
- Remember
VARBINARY
isn't your friend here, it's meant for binary data. - Don't overutilize
UPPER()
, consider using collation when appropriate. - Don't assume
LIKE
will always be case-insensitive without checking the collation.
Pattern matching and collation
LIKE
operator behaves according to the collation. For example,
The result of this query can be 'Laptop', 'LAPTOP', or only 'laptop', it's all about the ProductName
column's collation or the database default collation.
Exploring COLLATIONPROPERTY
For some deeper insights into your server's default collation, COLLATIONPROPERTY
might come handy:
Case where COLLATE outperforms functions
When dealing with uncertain user inputs or collations, explicitly enforcing case-insensitivity can be a lifesaver:
Knocking out compatibility issues
If you've got an application that is supposed to run on different SQL Server environments, the COLLATE clause helps maintain consistent results:
Was this article helpful?