Search code examples
mysqlwildcardsql-like

What does \% and \\ mean in a SQL query?


I know the meaning of % and _ wildcard characters ,but i was stuck in a question which was using the two additional characters \% and \\,i was not able to understand what these characters actually mean in the SQL query

SELECT productID 
FROM productList 
WHERE productName LIKE 'ab\%cd%'

and

SELECT productID 
FROM productList 
WHERE productName LIKE 'ab\\cd%'

are these two same things or different ??


Solution

  • Since % is a special character, you have to escape it with a \ to match a literal % symbol in your data. So, 'ab\%cd%' matches the letter a, followed by the letter b, followed by a % symbol, the letter c, the letter d, then any other text (because the last % is a wildcard).

    Similarly, since \ is a special character used to create escape sequences, you have to escape it to match a literal \ in a pattern, so to match a single \ you have to encode it as \\.