SQL Server LIKE containing bracket characters

SqlSql ServerPattern Matching

Sql Problem Overview


Using SQL Server 2008. I have a table with the following column:

sampleData (nvarchar(max))

The value for this column in some of these rows are lists formatted as follows:

["value1","value2","value3"]

I'm trying to write a simple query that will return all rows with lists formatted like this, by just detecting the opening bracket.

SELECT * from sampleTable where sampleData like '[%'

The above query doesn't work because '[' is a special character, and I can't for the life of me figure out how to escape the bracket so my query does what I want.

Thanks for any suggestions!

Sql Solutions


Solution 1 - Sql

 ... 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...

Solution 2 - Sql

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

Solution 3 - Sql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCJSView Question on Stackoverflow
Solution 1 - SqlgbnView Answer on Stackoverflow
Solution 2 - SqlEd HarperView Answer on Stackoverflow
Solution 3 - SqlKeithFearnleyView Answer on Stackoverflow