HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Closing bracket ']' in LIKE wildcard

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
bracketlikewildcardclosing

Problem

I have a query that looks a bit like this:

SELECT * FROM Stuff WHERE name LIKE '[a\]]%'


My goal is to match all names starting with a or ] (closed bracket). However, this seems to match everything starting with a] or \\].

Is this possible without OR, a lot of auto-generated LIKEs?

Solution

You have to escape the ].
That means before any character you want to literally search for, example % or _ or ], you have to add an escape character. For example \% to search for a literal %

Example:

CREATE TABLE #Test( text varchar(50) )

INSERT INTO #test  VALUES (']'),('atest'),('zz')

SELECT * FROM #test  WHERE text LIKE '[a\]]%' {escape '\'}


To read more about escape chars in LIKE, you can check :

LIKE Predicate Escape Character

You can also test it using SQL fiddle:
SQL Fiddle

Code Snippets

CREATE TABLE #Test( text varchar(50) )

INSERT INTO #test  VALUES (']'),('atest'),('zz')

SELECT * FROM #test  WHERE text LIKE '[a\]]%' {escape '\'}

Context

StackExchange Database Administrators Q#250642, answer score: 2

Revisions (0)

No revisions yet.