SQL Server LIKE containing bracket characters SQL Server LIKE containing bracket characters sql-server sql-server

SQL Server LIKE containing bracket characters


 ... like '[[]%'

You use [ ] to surround a special character (or range)

See the section "Using Wildcard Characters As Literals" in SQL Server LIKE

Edit, 24 Nov 2011

Note: You don't need to escape the closing bracket...


Aside from gbn's answer, the other method is to use the ESCAPE option:

SELECT * from sampleTable where sampleData like '\[%' ESCAPE '\'

See the documentation for details


Just a further note here...If you want to include the bracket (or other specials) within a set of characters, you only have the option of using ESCAPE (since you are already using the brackets to indicate the set). Also you MUST specify the ESCAPE clause, since there is no default escape character (it isn't backslash by default as I first thought, coming from a C background).

e.g. if I want to pull out rows where a column contains anything outside of a set of 'acceptable' characters, for the sake of argument let's say alphanumerics... we might start with this

SELECT * FROM MyTest WHERE MyCol LIKE '%[^a-zA-Z0-9]%'

So we are returning anything that has any character not in the list (due to the leading caret ^ character).

If we then want to add special characters in this set of acceptable characters, we cannot nest the brackets so we must use an escape character, like this...

SELECT * FROM MyTest WHERE MyCol LIKE '%[^a-zA-Z0-9\[\]]%' ESCAPE '\'

Preceding the brackets (individually) with a backslash and indicating that we are using backslash for the escape character allows us to escape them within the functioning brackets indicating the set of characters.

Sorry for the dumb example, but hope it helps someone