MySQL Wildcards: Using LIKE with % and _
In MySQL, wildcards are used to match strings in a fuzzy manner. There are two commonly used wildcards.
- Percent sign (%): Represents zero or more arbitrary characters.
- Underscore (_): represents a single arbitrary character
Wildcards are usually used together with the LIKE operator for conducting fuzzy searches in the WHERE clause, with the following syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Here, column_name is the name of the column to be queried, table_name is the name of the table to be queried, and pattern is the pattern to be matched. Below are some examples using wildcards:
- Search for all names that start with the letter “J”.
SELECT * FROM customers
WHERE name LIKE 'J%';
- Find all records that contain “an” in their names.
SELECT * FROM customers
WHERE name LIKE '%an%';
- Find all records where the third character in the name is “o”.
SELECT * FROM customers
WHERE name LIKE '__o%';
Be cautious of using wildcard characters for performance reasons, as they may slow down queries when used in large tables.