tags:

views:

3174

answers:

7

How do I construct a SQL query (MS SQL Server) where the "where" clause is case-insensitive?

SELECT * FROM myTable WHERE myField = 'sOmeVal'

I want the results to come back ignoring the case

A: 

What database are you on? With MS SQL Server, it's a database-wide setting, or you can over-ride it per-query with the COLLATE keyword.

Chase Seibert
+8  A: 

In the default configuration of a SQL Server database, string comparisons are case-insensitive. If your database overrides this setting (through the use of an alternate collation), then you'll need to specify what sort of collation to use in your query.

SELECT * FROM myTable WHERE myField = 'sOmeVal' COLLATE SQL_Latin1_General_CP1_CI_AS

Note that the collation I provided is just an example (though it will more than likely function just fine for you). A more thorough outline of SQL Server collations can be found here.

Adam Robinson
+4  A: 

Usually, string comparisons are case-insensitive. If your database is configured to case sensitive collation, you need to force to use a case insensitive one:

SELECT balance FROM people WHERE email = '[email protected]'
  COLLATE SQL_Latin1_General_CP1_CI_AS
Andrejs Cainikovs
Looks like someone is faster than me :-)
Andrejs Cainikovs
A: 

If the Database is case sensitive you can't. To create a case insensitive db choose another collation on db creation. For the right collation see here.

zoidbeck
This is incorrect. You can specify what collation to use for a given comparison in your where clause. Not only can the collation be different from that of the database, it can differ within a particular query.
Adam Robinson
+1  A: 

You can force the case sensitive, casting to a varbinary like that:

SELECT * FROM myTable 
WHERE convert(varbinary, myField) = convert(varbinary, 'sOmeVal')
While this is functional, it's not an advisable approach. Collations are there for managing sorting and string comparisons.
Adam Robinson
A: 
SELECT * FROM myTable WHERE myField LIKE 'sOmeVal' COLLATE SQL_Latin1_General_CP1_CI_AS

is not working for my H2 database. Can't I use the collation method for 'like' instead of '=' ?

Sagar Jauhari
even this doesn't work:SET IGNORECASE TRUE;SELECT RNAME1FROM RECIPE1WHERE RNAME1 LIKE ('%greek%')
Sagar Jauhari
A: 

I found another solution elsewhere; that is, to use

upper(@yourString)

but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.

Danny