Sub topic 9
Matching text patterns with LIKE
This chapter assumes you can write a SELECT ... FROM ... WHERE query and know that text values go in single quotes. It also assumes you know that a condition in WHERE can be true, false, or unknown (the NULL logic from the previous chapter). The examples use the employees table from earlier chapters.
What LIKE does
= tests whether two strings are identical. LIKE tests whether a string fits a pattern. A pattern is ordinary text with two special characters, called wildcards:
| Wildcard | Matches | Example pattern | Matches | Does not match |
|---|---|---|---|---|
| `%` | Any run of characters, including none | `Mc%` | McDonald, Mc | Macdonald |
| `_` | Exactly one character | `J_n` | Jon, Jan | John, Jn |
Any other character in the pattern matches only itself. The whole value must fit the pattern, not just part of it. 'Mc%' therefore means "starts with Mc", and '%son' means "ends with son".
SELECT first_name, last_name
FROM employees
WHERE last_name LIKE 'Mc%';The four common shapes
Most patterns you write are one of these four.
| Goal | Pattern | Example match |
|---|---|---|
| Starts with | `'Mc%'` | McBride |
| Ends with | `'%son'` | Johnson |
| Contains | `'%an%'` | Hanson, Banerjee |
| Fixed length or position | `'A___'` | Anna, Adam (four characters total) |
A pattern with no wildcard behaves like =. These two conditions are equivalent, apart from case rules covered below:
WHERE department LIKE 'Sales'
WHERE department = 'Sales'Practice data
To run the examples, create a small table. This works in PostgreSQL, MySQL, and SQLite.
CREATE TABLE people (
id INTEGER PRIMARY KEY,
last_name VARCHAR(30),
email VARCHAR(50)
);
INSERT INTO people (id, last_name, email) VALUES
(1, 'McBride', '[email protected]'),
(2, 'Macdonald', '[email protected]'),
(3, 'Johnson', '[email protected]'),
(4, 'mcgee', NULL),
(5, 'Jones', '[email protected]');Now try some patterns:
SELECT last_name FROM people WHERE last_name LIKE 'J%son';
SELECT last_name FROM people WHERE last_name LIKE 'Jo_es';
SELECT last_name FROM people WHERE last_name LIKE '%on%';The first query returns Johnson. The second returns Jones. The third returns Johnson only, because Macdonald contains on only as part of ona, so check it yourself by reading the string: M-a-c-d-o-n-a-l-d does contain on, so Macdonald is also returned. Always check a contains pattern against every row, because it matches more than people expect.
NOT LIKE
Put NOT before LIKE to keep rows that do not fit the pattern:
SELECT last_name
FROM people
WHERE last_name NOT LIKE 'Mc%';A NULL value never passes either LIKE or NOT LIKE. This is a frequent surprise, as the section on NULL below explains.
Case sensitivity depends on the database
The SQL standard does not say whether LIKE ignores case. Databases differ, and the same query can return different rows.
| Database | Default behavior of LIKE |
|---|---|
| PostgreSQL | Case-sensitive. `ILIKE` is a PostgreSQL extension for case-insensitive matching. |
| MySQL | Depends on the column's collation. The common default collations are case-insensitive. |
| SQLite | Case-insensitive for ASCII letters only. |
With the practice data, last_name LIKE 'Mc%' returns McBride in every database. It also returns mcgee in MySQL and SQLite, but not in PostgreSQL.
A portable way to ignore case is to convert both sides to the same case:
SELECT last_name
FROM people
WHERE LOWER(last_name) LIKE 'mc%';This works everywhere. The cost is that the database must compute LOWER for every row, which can stop it from using a plain index on last_name.
Matching a literal % or _
What if the data itself contains % or _? In the practice table, [email protected] has an underscore. The pattern 'mac_donald%' would also match macxdonald..., because _ means "any one character".
To match the symbol itself, declare an escape character with ESCAPE, then put it before the wildcard:
SELECT email
FROM people
WHERE email LIKE 'mac!_donald%' ESCAPE '!';Here !_ means a literal underscore, and the final % is still a wildcard. The query returns [email protected] only.
Choose an escape character that does not appear in your data and does not have special meaning to the database. ! is a safe, portable choice. Backslash is a poor choice. MySQL treats it as an escape inside string literals, so you would need to write '\\'. Some other databases treat it differently again.
LIKE and NULL
LIKE follows the same three-valued logic as other comparisons. If the value is NULL, the result is unknown, and WHERE keeps only rows where the condition is true.
SELECT last_name
FROM people
WHERE email NOT LIKE '%.org';You might expect this to return everyone except Jones. It returns McBride, Macdonald, and Johnson, but not mcgee, because mcgee's email is NULL. To include rows with no email, test for NULL separately:
SELECT last_name
FROM people
WHERE email NOT LIKE '%.org'
OR email IS NULL;Performance: where the wildcard goes
An index on a text column is sorted, like a phone book. A pattern that starts with fixed text, such as 'Mc%', lets the database jump to the Mc section and read forward. A pattern that starts with a wildcard, such as '%son', gives it nothing to jump to, so it usually reads every row.
Whether the index is actually used also depends on the database and the collation. In PostgreSQL, for example, a plain index often cannot serve LIKE unless it was built with a suitable operator class. On small tables none of this matters. On large tables, avoid leading wildcards in frequently run queries. For searching inside text, databases offer dedicated full-text search features.
Common errors
- Using
=with a wildcard.WHERE last_name = 'Mc%'looks for the literal textMc%. It returns nothing, with no error. - Forgetting the wildcard.
LIKE 'Mc'matches only the exact valueMc. - Wrapping a pattern in double quotes. In standard SQL, double quotes name identifiers. Use single quotes for text.
- Expecting
_to match zero characters. It always matches exactly one. - Trailing spaces in fixed-width
CHARcolumns. ACHAR(10)column holdingJonesmay be padded to ten characters. In some databasesLIKE '%s'then fails because the value ends in spaces. UseVARCHAR, orTRIM()the column. - Relying on default case rules, as described above.
Combining LIKE with other conditions
LIKE is a normal condition, so it combines with AND, OR, and NOT. Use parentheses when you mix AND and OR:
SELECT last_name, email
FROM people
WHERE (last_name LIKE 'Mc%' OR last_name LIKE 'Mac%')
AND email IS NOT NULL;For several prefixes, repeat LIKE with OR. IN does not accept wildcards, so last_name IN ('Mc%', 'Mac%') would only match the literal text.
Exercise
Using the people table, write a query that returns the lastname of every person whose email address contains a literal underscore, regardless of letter case in the email, and explain why a plain LIKE '%%' pattern gives the wrong result.
Show answer
SELECT lastname FROM people WHERE LOWER(email) LIKE '%!%' ESCAPE '!'; This returns Macdonald only. The pattern '%%' is wrong because is a wildcard meaning "any one character", so it matches every email that has at least one character, which is every non-NULL email. Rows with a NULL email are excluded either way. The ESCAPE character makes !_ mean a literal underscore, and LOWER() makes the match ignore case on every database.