SQL Wildcards
SQL Wildcards
Wildcards are special characters used with the LIKE operator to match patterns in text data.
Percent Wildcard (%)
The percent sign (%) represents zero, one, or multiple characters.
SELECT name FROM customers WHERE name LIKE 'A%';
Matches names starting with A.
SELECT name FROM customers WHERE name LIKE '%son';
Matches names ending with "son".
Underscore Wildcard (_)
The underscore (_) represents exactly one character.
SELECT name FROM customers WHERE name LIKE 'A___';
Matches names that start with A and contain exactly four characters.
Combining Wildcards
You can combine % and _ to build complex patterns.
SELECT name FROM customers WHERE name LIKE 'A_%e';
Searching for Special Characters
If your pattern needs to include % or _ literally, you may need to use an ESCAPE character (database-specific).
SELECT name FROM customers WHERE name LIKE '100\%%' ESCAPE '\';
LIKE vs Regular Expressions
LIKE is simple and portable across database systems. Some systems also support REGEXP or similar operators for advanced pattern matching.
Case Sensitivity
Case sensitivity depends on database collation settings. In many MySQL configurations, LIKE is case-insensitive by default.
Performance Considerations
- Patterns starting with % (for example '%phone') usually cannot use indexes efficiently.
- Patterns like 'phone%' can often use indexes.
Next Step
Continue with SQL IN to learn how to match a column against multiple values more efficiently.