Home > Article > Backend Development > Why Do I Need to Escape Slashes Differently in MySQL\'s WHERE and LIKE Clauses?
In MySQL, handling slashes () within queries can be confusing. Consider the following query:
<code class="sql">(SELECT * FROM `titles` where title = 'test\') UNION ALL (SELECT * FROM `titles` where title LIKE 'test\\')</code>
You might expect that the second query, using the LIKE clause, would require an additional backslash to escape the original slash in "test". However, the results show that both queries successfully return the same row, with "test" as the title.
The discrepancy arises because of MySQL's behavior with escape characters in WHERE and LIKE clauses. In the WHERE clause, backslash serves as an escape character, protecting special characters from being interpreted literally. In contrast, in the LIKE clause, backslash is the default escape character, allowing you to escape other characters within the search pattern.
As stated in the MySQL manual for LIKE:
"Because MySQL uses C escape syntax in strings ... you must double any " that you use in LIKE strings. For example, to search for "n", specify it as "\n"."
Thus, while the backslash in "test" is automatically escaped during parsing for the WHERE clause, it must be explicitly doubled (to "test\") for the LIKE clause to match the intended escape sequence.
Alternatively, you can specify a different escape character for LIKE, as shown in the following modified query:
<code class="sql">SELECT * FROM `titles` WHERE title LIKE 'test\' ESCAPE '|'</code>
By replacing the backslash with a pipe character as the escape character, you can accurately search for the literal "test" without doubling the backslash.
The above is the detailed content of Why Do I Need to Escape Slashes Differently in MySQL\'s WHERE and LIKE Clauses?. For more information, please follow other related articles on the PHP Chinese website!