Closing bracket ']' in LIKE wildcard
-
15-02-2021 - |
Question
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 LIKE
s?
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
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange