SQL Wildcards
Wildcards are the placeholder characters that give the LIKE operator its power to match flexible text patterns.
Understanding wildcards
A wildcard is a symbol that stands in for one or more unknown characters inside a pattern. When you combine wildcards with the LIKE operator, you describe the shape of the text you are looking for rather than its exact content. This lets a single query match many different values that share a common structure.
Standard SQL defines two wildcards that every major database supports. The percent sign matches any number of characters, including zero, while the underscore matches exactly one character. Understanding how these two behave together is enough to build most text searches you will need.
The percent sign in practice
The percent sign is the most common wildcard because it is so flexible. Its position in the pattern controls where the flexible part sits: at the end for a prefix search, at the start for a suffix search, or on both sides for a contains search.
Prefix, suffix, and contains searches
SELECT customer_name
FROM Customers
WHERE customer_name LIKE 'Gr%'
OR customer_name LIKE '%ez'
OR customer_name LIKE '%tech%';The underscore for fixed-length matching
The underscore is precise: each one demands a single character to be present. This makes it ideal for values that follow a fixed format, such as product codes or postal codes, where you know the length and want to constrain some positions.
Match a fixed-format code
SELECT product_code, product_name
FROM Products
WHERE product_code LIKE 'A__-2025';The pattern above matches codes that start with A, followed by any two characters, then the fixed suffix -2025. A value like ABX-2025 matches, while A1-2025 does not, because only one character sits between A and the dash.
Combine both wildcards
SELECT customer_name, city
FROM Customers
WHERE city LIKE '_a%';- Percent matches any run of characters, so it is best for open-ended searches.
- Underscore matches exactly one character, so it is best for fixed-length formats.
- Wildcards can be mixed freely within one pattern.
- A leading percent sign disables index use in most engines, which can slow searches on large tables.
- To match a literal % or _, escape it with an ESCAPE clause.