Sub topic 2
Matching text patterns with LIKE
This chapter assumes you can write a basic SELECT ... WHERE query and use comparison operators, AND, and OR. You don't need to know IN, BETWEEN, or NULL handling yet. Later chapters cover those. Escaping, case sensitivity, negation, and indexes get their own chapters, so this one only points to them.
What LIKE does
The = operator 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 the value |
|---|---|---|---|
| `%` | Any sequence of zero or more characters | `'A%'` | `Alice`, `A`, `Aaron` |
| `_` | Exactly one character | `'_ob'` | `Bob`, `Rob` (not `ob` or `Bobby`) |
Every other character in the pattern matches only itself. The general form is:
SELECT columns
FROM table_name
WHERE text_column LIKE 'pattern';LIKE is a predicate. Like = or >, it produces a truth value for each row, and WHERE keeps the rows where that value is true.
A dataset to follow along
The examples below use this small table. The statements are plain SQL and run on PostgreSQL, MySQL, SQLite, and SQL Server (use INT and VARCHAR as shown).
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50)
);
INSERT INTO employees (id, name) VALUES
(1, 'Alice'),
(2, 'Aaron'),
(3, 'Bob'),
(4, 'Carla'),
(5, 'Diana'),
(6, 'Hannah'),
(7, NULL);The whole value must match
The most common mistake is forgetting that LIKE compares the pattern against the entire string, not against a fragment of it. The pattern 'Al' matches only a value that is exactly Al. It does not match Alice. To say "starts with", you must add a % at the end.
SELECT id, name
FROM employees
WHERE name LIKE 'A%';This returns Alice and Aaron. The A must be the first character, and % absorbs everything after it, including nothing at all. A value that is just A would match too.
The position of the % decides what kind of search you are doing:
| Pattern | Meaning | Matches in the dataset |
|---|---|---|
| `'A%'` | Starts with `A` | Alice, Aaron |
| `'%a'` | Ends with `a` | Carla, Diana, Hannah |
| `'%an%'` | Contains `an` anywhere | Diana, Hannah |
| `'A%e'` | Starts with `A` and ends with `e` | Alice |
Here is the "contains" search as a full query:
SELECT id, name
FROM employees
WHERE name LIKE '%an%';Aaron is not returned. It ends in on and has no a followed directly by n.
Matching one character with the underscore
The _ wildcard stands for exactly one character. It is useful for fixed-format values such as codes, where each position has a meaning. It is also useful for length checks.
SELECT id, name
FROM employees
WHERE name LIKE '_ob';This returns Bob. The pattern requires three characters, and the last two must be ob.
You can repeat the underscore to count characters. Five underscores match any five-character value:
SELECT id, name
FROM employees
WHERE name LIKE '_____';This returns Alice, Aaron, Carla, and Diana. Bob has three characters and Hannah has six. Counting underscores by eye is error-prone, so use this form only for short patterns.
You can mix both wildcards. The pattern 'A_r%' means: A, then any one character, then r, then anything. It matches Aaron but not Alice.
Next is a realistic fixed-format example. Product codes begin with AB, then one variable letter, then a hyphen:
SELECT id, product_code
FROM products
WHERE product_code LIKE 'AB_-%';This matches ABX-100 and ABZ-200. It does not match AB-100, because after AB the pattern needs exactly one character before the hyphen. In AB-100 the hyphen sits in that position, and the pattern then expects a second hyphen where the digit 1 appears. The pattern fails.
How a row is evaluated
The NULL branch matters. NULL means "no value", and a comparison with an unknown value is itself unknown. WHERE only keeps rows where the test is true, so a NULL name never matches a LIKE pattern. This holds even for the widest pattern:
SELECT id, name
FROM employees
WHERE name LIKE '%';This returns six rows. Employee 7 is missing because their name is NULL. If you need those rows too, test for them explicitly:
SELECT id, name
FROM employees
WHERE name LIKE '%' OR name IS NULL;Chapter 9 covers NULL in depth. For now, remember that LIKE never matches NULL.
Empty strings and the lone percent sign
An empty string ('') is a real value with zero characters. It is different from NULL. The pattern '%' matches the empty string, because % accepts zero characters. The pattern '_' does not match it, because _ needs exactly one. A pattern with no wildcards, such as '', matches only the empty string.
Patterns are strings, so use LIKE only on text
The pattern is a string literal in single quotes. Double quotes mean an identifier in standard SQL, so LIKE "A%" is an error on most databases.
LIKE is designed for character columns. Some databases will quietly convert a number or date to text so that LIKE works on it. Others raise an error. Even where it works, you get a string comparison, not a numeric one, and the result depends on the display format of the value. If you find yourself writing LIKE '2026%' against a date column, use a range instead. The date chapter later in this tutorial shows how.
Building patterns from variables
Applications often take a search term and wrap it in wildcards. In standard SQL, the string concatenation operator is ||:
SELECT id, name
FROM employees
WHERE name LIKE '%' || 'an' || '%';In real code, the 'an' would be a bound parameter. Some databases don't support || for strings. MySQL treats it as a logical OR by default and uses CONCAT('%', 'an', '%') instead. SQL Server uses + or CONCAT.
There is also a safety point. If the search term comes from a user, any % or _ they type becomes a wildcard in your pattern. Searching for 100% would match anything starting with 100. To treat those characters literally, you must escape them. The next chapter covers how.
Common errors
- Using
=with a wildcard.WHERE name = 'A%'looks for a value that is literallyA%. It usually returns nothing and raises no error. UseLIKE. - Forgetting the surrounding
%.LIKE 'an'matches only the exact valuean. Use'%an%'for "contains". - Using shell or regex wildcards.
*and?are ordinary characters inLIKE.LIKE 'A*'matches the two-character valueA*. - Miscounting underscores. Each
_is one character, and a trailing%can add any number more.'A_'means exactly two characters.'A_%'means at least two. - Expecting
NULLrows. As shown above,LIKEnever returns rows where the column isNULL. - Ignoring trailing spaces. In fixed-width
CHAR(n)columns, values are padded with spaces, and databases differ in how that padding affectsLIKE. A pattern like'%a'can fail on a padded value that ends in spaces. PreferVARCHARfor text you search, or test the behavior on your database. - Assuming case rules. Whether
'a%'matchesAlicedepends on the database and the column's collation (its sorting and comparison rules). A later chapter covers this.
A note on performance
A pattern with a fixed beginning, such as 'A%', lets many databases use an index on the column to narrow the search. A pattern that starts with a wildcard, such as '%an%', generally forces the database to check every row. This is only a preview. The final chapter explains which patterns can use an index and why.
Putting it together
The next query combines two LIKE conditions. It finds names that start with A and have exactly five characters:
SELECT id, name
FROM employees
WHERE name LIKE 'A%'
AND name LIKE 'A____';It returns Alice and Aaron. In practice, you can write the same thing with a single pattern: 'A____' (an A followed by four underscores). Check that you can see why both forms give the same result.
Exercise
Using the employees table from this chapter, write a query that returns the names that end with a and have exactly six characters or fewer... more precisely, names that start with any one letter, then a, and then anything. Which names does the pattern '_a%' return, and does it return the row where name is NULL?
Show answer
The pattern '_a%' means: exactly one character, then a lowercase a, then any sequence of characters. Against the dataset it returns Carla (C, a, rla), Hannah (H, a, nnah), and Aaron (A, a, ron). Alice and Diana have another letter in second position, and Bob has o. The NULL row is never returned, because LIKE on NULL gives unknown, and WHERE keeps only rows that are true. The query is: SELECT id, name FROM employees WHERE name LIKE '_a%';
Exercise
A table tickets has a column code with values such as TK-2026-001, TK-2026-017, TK-2025-114, and TKT-2026-001. Write a LIKE pattern that matches only codes from 2026 that begin with exactly TK-, whatever the three-digit number at the end.
Show answer
Use WHERE code LIKE 'TK-2026-___'. The literal text TK-2026- must match exactly, and the three underscores require exactly three more characters. This matches TK-2026-001 and TK-2026-017. It rejects TK-2025-114 (wrong year) and TKT-2026-001 (the fourth character is T, not -). If the number could have a variable length, replace the underscores with %.