Using Escape with like in SQL
- sqltutor
- Jan 17, 2016
- 1 min read
How to indicate that the wildcard should be interpreted as a regular character and not as a wildcard?
escape_character?
Is a character that is put in front of a wildcard character to indicate that the wildcard should be interpreted as a regular character and not as a wildcard. escape_character is a character expression must be only one character. And you can use any one character as escape_character which is not in your pattern.
e.g. Where match_expression LIKE pattern [ ESCAPE escape_character ]
Table
Row | Date | Log Message
1 |2016-01-01 |'[Error] Something failed in (Freds) session'
2 |2016-01-01 |'[Error] Something failed in (Ilenes) session'
3 |2016-01-01 |'[Error] Something failed in (Freds) session'
........
........
101 |2016-01-01 |'[Warning] Something else went wrong'
........
500 |2016-01-01 |'[Warning] Some other warning'
What Query would give me:
Row |Date | Log Message
1 |2016-01-01 |'[Error] Something failed in (Freds) session'
2 |2016-01-01 |'[Error] Something failed in (Ilenes) session'
3 |2016-01-01 |'[Error] Something failed in (Freds) session'
Wrong Query: select * From Table Where name like '%[Error] Something failed in (%) session%'
Because it is due to the presence of [] in string. [] is used with LIKE operator to find any single character within the specified range ([a-f]) or set ([abcdef]). so you need to use ESCAPE the square bracket's
Right Query: select * From Table where name like '%\[Error] Something failed in (%) session%' escape '\'
Here '/' is used as escape_character so that [Error] should be interpreted as a regular character and not as a wildcard.
Comments