Sub topic 3
Matching a literal % or _ with ESCAPE
This chapter covers how to search for the characters % and _ as ordinary text. It assumes you can write a basic SELECT ... WHERE query and that you know how LIKE uses the % and _ wildcards from the previous chapter. You only need basic string literals and comparison operators beyond that.
The problem: wildcards have no literal meaning
In a LIKE pattern, % matches any sequence of characters, including none. _ matches exactly one character. That works until the text you are looking for contains one of those characters.
Suppose a promotions table holds these rows:
| id | label |
|---|---|
| 1 | 10% off |
| 2 | 100 items |
| 3 | 10 percent |
| 4 | snake_case |
| 5 | snakeXcase |
You want labels that start with the text 10%. This query looks right but is not:
SELECT id, label
FROM promotions
WHERE label LIKE '10%';The % is read as a wildcard, so the pattern means "starts with 10, then anything". It returns rows 1, 2, and 3. The same thing happens with _. The pattern 'snake_case' matches both snake_case and snakeXcase, because _ accepts any single character.
The database cannot guess which meaning you intend, so you have to mark the wildcard as literal.
The ESCAPE clause
LIKE accepts an optional ESCAPE clause that names one character as the escape character. Inside the pattern, when the escape character is followed by %, _, or the escape character itself, the character that follows is matched literally. The escape character is not part of the text being matched.
SELECT id, label
FROM promotions
WHERE label LIKE '10!%%' ESCAPE '!';Read the pattern 10!%% from left to right:
1and0match themselves.!%is the escape character followed by%, so it matches a literal percent sign.- The final
%has no escape in front of it, so it is still a wildcard that matches any remaining text.
The query returns only row 1, 10% off. The pattern as a whole means "starts with the text 10%".
The same approach works for the underscore:
SELECT id, label
FROM promotions
WHERE label LIKE 'snake!_%' ESCAPE '!';This returns snake_case and does not return snakeXcase. !_ is a literal underscore, and the trailing % allows any suffix.
Escaping the escape character
If you choose ! as the escape character, a literal ! in the pattern must also be escaped, by doubling it. To find labels that contain an exclamation mark:
SELECT id, label
FROM promotions
WHERE label LIKE '%!!%' ESCAPE '!';The first % and last % are wildcards. The !! in the middle matches one literal !.
This is why the escape character should be something that rarely appears in your data. It does not have to be absent from the data, because you can always double it. A rare character just keeps patterns readable.
Choosing the escape character
Any single character works. Common choices are !, #, ~, and \. The ESCAPE value must be exactly one character. Using % or _ as the escape character is legal in some databases, but it makes patterns confusing and you should avoid it.
Backslash is the traditional choice, but it is the most error-prone, for two reasons.
- Some databases treat backslash as an escape character in
LIKEeven when you write noESCAPEclause. Others have no default at all. - In some databases the string literal parser also treats backslash specially, so
'10\%'may reach theLIKEengine as10%with the backslash already consumed.
The table summarizes what to expect. Check your database's documentation for your exact version and settings.
| Database | Escape character when no ESCAPE clause is given | Notes |
|---|---|---|
| PostgreSQL | Backslash | `ESCAPE ''` turns escaping off. |
| MySQL | Backslash | Backslash is also special in string literals, so a literal `%` may need `'\\%'`, unless the `NO_BACKSLASH_ESCAPES` mode is on. |
| SQLite | None | `ESCAPE` is the only way to match a literal wildcard. |
| SQL Server | None | Also supports `[%]` and `[_]` bracket syntax, which is not portable. |
| Oracle | None | `ESCAPE` clause required. |
Because of these differences, the portable habit is to always write an explicit ESCAPE clause with a character that is not special in string literals, such as !. The query then behaves the same on every database that implements standard LIKE.
Escaping with NOT LIKE
NOT LIKE takes the same ESCAPE clause and has the same rules:
SELECT id, label
FROM promotions
WHERE label NOT LIKE '%!%%' ESCAPE '!';Here %!%% means "anything, then a literal %, then anything". The query returns labels that do not contain a percent sign. As with every NOT LIKE, rows where label is NULL are not returned, because the comparison with NULL is unknown rather than true. The negation chapter covers this in detail.
Escaping user input safely
The most common reason to need ESCAPE is a search box. A user types text, and your code builds a pattern such as '%' || input || '%'. If the user types 50% or a_b, those characters act as wildcards, and the search returns more rows than the user intended.
Two separate protections are needed:
- Use a parameterized query, so the user's text can never change the structure of the SQL statement. This prevents SQL injection.
- Escape
%,_, and the escape character in the text before you add your own wildcards. This keeps the user's text literal.
Parameterization does not escape wildcards. A bound parameter is still interpreted as a pattern by LIKE.
This Python program shows both steps with SQLite. It runs as written.
import sqlite3
def escape_like(text, escape="!"):
"""Make text safe to embed in a LIKE pattern that uses the given escape."""
return (
text.replace(escape, escape + escape) # escape the escape character first
.replace("%", escape + "%")
.replace("_", escape + "_")
)
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE promotions (id INTEGER PRIMARY KEY, label TEXT)")
conn.executemany(
"INSERT INTO promotions (id, label) VALUES (?, ?)",
[
(1, "10% off"),
(2, "100 items"),
(3, "10 percent"),
(4, "snake_case"),
(5, "snakeXcase"),
],
)
sql = "SELECT id, label FROM promotions WHERE label LIKE ? ESCAPE '!' ORDER BY id"
for user_input in ["10%", "snake_"]:
unescaped = conn.execute(sql, (user_input + "%",)).fetchall()
escaped = conn.execute(sql, (escape_like(user_input) + "%",)).fetchall()
print(user_input)
print(" unescaped:", unescaped)
print(" escaped: ", escaped)The output is:
10%
unescaped: [(1, '10% off'), (2, '100 items'), (3, '10 percent')]
escaped: [(1, '10% off')]
snake_
unescaped: [(4, 'snake_case'), (5, 'snakeXcase')]
escaped: [(4, 'snake_case')]The order of the replacements matters. The escape character must be doubled first. If you escaped % first, the ! you just added would then be doubled again, and the pattern would be wrong.
Edge cases and common errors
- A pattern that ends with the escape character. A pattern such as
'abc!'withESCAPE '!'has an escape with nothing after it. Most databases raise an error. PostgreSQL, for example, rejects it with a message that the pattern must not end with the escape character. - An escape before an ordinary character. The standard calls
'a!b'an invalid escape sequence. Some databases raise an error, and others treat!bas a literalb. Avoid depending on either behavior. Escape only%,_, and the escape character itself. - Forgetting the clause. On databases with no default escape,
'10!%%'withoutESCAPE '!'matches a literal!followed by anything. The query returns no rows or the wrong rows, and no error tells you why. - A NULL escape. If the
ESCAPEexpression isNULL, many databases returnNULLfor the whole comparison, so no rows match. Pass a real character. - Escaping outside the pattern.
ESCAPEaffects only theLIKEpattern. Do not escape the column values or the text you compare in=conditions. - Case.
ESCAPEdoes not change case sensitivity. WhetherLIKE '10!%%'matches10% OFFand10% offidentically depends on the database, as the next chapter explains.
Putting it together
Use this checklist when a pattern contains characters that might be wildcards:
- Decide which characters in the text should be literal.
- Pick an escape character that rarely appears, such as
!. - Double the escape character, then put it before each literal
%and_. - Add any real wildcards you need at the start or end.
- Write
ESCAPE '!'after the pattern, every time, in every database.
Exercise
A table files has a column name with values such as report_2026.csv, reportA2026.csv, and 100%_final.txt. Write a query that returns only names that start with the literal text report_ and may continue with anything. Use ! as the escape character.
Show answer
SELECT id, name FROM files WHERE name LIKE 'report!%' ESCAPE '!'; The `! matches a literal underscore, so report_2026.csv matches and reportA2026.csv does not. The final %` is an unescaped wildcard that allows any ending.
Exercise
What does the pattern '%!!!%%' with ESCAPE '!' match, reading it from left to right?
Show answer
It matches any text that contains an exclamation mark followed immediately by a percent sign. The first % is a wildcard, !! is one literal !, !% is one literal %, and the last % is a wildcard.
Exercise
A search function builds the pattern '%' + user_text + '%' and passes it as a bound parameter. A user searches for 5_. The results include 5A, 5B, and 50. Why does this happen, and how do you fix it?
Show answer
Binding the parameter prevents SQL injection but does not stop LIKE from reading _ as a wildcard that matches any one character. Fix it by escaping the user's text first (double the escape character, then prefix % and _ with it), building the pattern as '%' + escaped_text + '%', and adding an ESCAPE clause such as ESCAPE '!' to the query.