Sub topic 10
Matching patterns with LIKE and ILIKE
This chapter assumes you can write SELECT queries with WHERE, and that you know PostgreSQL treats NULL as "unknown". Earlier chapters covered text columns, lower() and strpos(). Here you use pattern matching to answer questions like "which names start with Ph?" or "which names contain the letters phone, in any case?"
The two wildcards
LIKE compares a string with a pattern. The pattern is ordinary text with two special characters:
| Character | Matches |
|---|---|
| `%` | Any sequence of characters, including none |
| `_` | Exactly one character |
Every other character matches itself. The pattern must match the whole string, not a part of it. name LIKE 'phone' is therefore the same as name = 'phone', and you need % to match anything around the text.
The examples in this chapter use this temporary table:
CREATE TEMP TABLE products (id int, name text);
INSERT INTO products (id, name) VALUES
(1, 'Phone case'),
(2, 'Smartphone'),
(3, 'phone charger'),
(4, 'Headphones'),
(5, '100% cotton shirt'),
(6, '100 cotton socks'),
(7, NULL);Here are three searches:
SELECT id FROM products WHERE name LIKE 'Phone%' ORDER BY id; -- 1
SELECT id FROM products WHERE name LIKE '%phone%' ORDER BY id; -- 2, 3, 4
SELECT id FROM products WHERE name LIKE '_hone%' ORDER BY id; -- 1, 3The first query returns only row 1. LIKE is case sensitive, so 'phone charger' does not match 'Phone%'. The second query matches the lowercase text phone anywhere in the string. It misses row 1 because Phone case starts with a capital P. The third query requires exactly one character before hone, so it matches Phone case and phone charger but not Smartphone.
ILIKE for case-insensitive matching
ILIKE works like LIKE but ignores case. It is a PostgreSQL extension and is not part of standard SQL.
SELECT id FROM products WHERE name ILIKE '%phone%' ORDER BY id; -- 1, 2, 3, 4Now row 1 matches. Whether two letters count as the same depends on the database's locale settings, covered in the collation chapter. For ordinary English text, ILIKE behaves as you expect.
Operator forms
LIKE is syntax for an operator. The operator forms appear in query plans and error messages, so it helps to recognize them.
| Syntax | Operator | Meaning |
|---|---|---|
| `a LIKE p` | `a ~~ p` | Matches, case sensitive |
| `a NOT LIKE p` | `a !~~ p` | Does not match, case sensitive |
| `a ILIKE p` | `a ~~* p` | Matches, ignoring case |
| `a NOT ILIKE p` | `a !~~* p` | Does not match, ignoring case |
These are different from ~ and ~*, which use regular expressions. Regular expressions come later in this tutorial.
Matching a literal % or _
Sometimes the text you are searching for contains % or _. In '100% cotton shirt' the percent sign is real text. The pattern '100% cotton%' does not look only for that sign. It matches both 100% cotton shirt and 100 cotton socks, because the % in the pattern matches zero characters in the second string.
To match a wildcard character literally, put the escape character in front of it. The default escape character is the backslash:
SELECT id FROM products WHERE name LIKE '%\%%' ORDER BY id; -- 5Reading the pattern left to right: % matches anything, \% matches a literal percent sign, and the final % matches anything. Only row 5 contains a percent sign.
If you do not want backslashes in your SQL, choose another escape character with the ESCAPE clause:
SELECT id FROM products WHERE name LIKE '%!%%' ESCAPE '!' ORDER BY id; -- 5You can also write ESCAPE '' to turn escaping off. A backslash is then an ordinary character.
Searching with user input
When the search text comes from a user, they may type % or _ without meaning them as wildcards. Escape those characters, and the escape character itself, before you build the pattern. Escape the backslash first so you do not double-escape the others:
SELECT id, name
FROM products
WHERE name ILIKE '%'
|| replace(replace(replace('100%', '\', '\\'), '%', '\%'), '_', '\_')
|| '%'
ORDER BY id;The search term 100% becomes 100\%, so the full pattern is %100\%%. The query returns only row 5. In an application, pass the search term as a bound parameter and do the escaping in application code or in this same expression. Never paste user text into the SQL string itself. The format chapter shows what goes wrong when you do.
NULL and NOT LIKE
If either side of LIKE is NULL, the result is NULL, which WHERE treats as not true. This applies to NOT LIKE as well:
SELECT id FROM products WHERE name NOT LIKE '%phone%' ORDER BY id; -- 1, 5, 6Row 7 has a NULL name. It does not match %phone%, but it is also not returned by NOT LIKE '%phone%'. If you want rows with a missing name included, say so explicitly:
SELECT id
FROM products
WHERE name NOT LIKE '%phone%' OR name IS NULL
ORDER BY id; -- 1, 5, 6, 7Choosing a matching tool
LIKE is simple, but other tools often fit better. This diagram summarizes the usual choices.
PostgreSQL 11 and later provide starts_with(string, prefix). It treats % and _ in the prefix as ordinary characters, so it needs no escaping:
SELECT id FROM products WHERE starts_with(name, '100%') ORDER BY id; -- 5Performance basics
A pattern that starts with a wildcard, such as '%phone%', cannot use an ordinary B-tree index. PostgreSQL has to read every row and test it. Two situations are worth knowing about now. The indexing chapter covers them in full.
- A prefix search like
name LIKE 'Pho%'can use a B-tree index only if the database uses theCcollation or the index is built with thetext_pattern_opsoperator class:
CREATE INDEX idx_products_name_prefix ON products (name text_pattern_ops);ILIKEandLIKE '%text%'searches need a trigram index from thepg_trgmextension to avoid scanning the whole table.
Also keep in mind that lower(name) LIKE 'pho%' is an expression. An index on name alone cannot serve it. You would need an expression index on lower(name).
Common mistakes
- Forgetting that the match is anchored.
LIKE 'phone'finds only the exact valuephone. Add%for partial matches. - Using
LIKEfor case-insensitive matching.LIKEnever ignores case. UseILIKE, or comparelower()of both sides. - Leaving wildcards in user input. A search for
50%ora_bmatches more rows than intended unless you escape it. - Expecting
NOT LIKEto returnNULLrows. It does not. AddOR column IS NULL. - Using
_to mean a space. It means any single character, including a space.
Exercise
Write a query on the products table that returns the ids of products whose name contains the literal text 100%, ignoring case, using the ESCAPE clause with # as the escape character. What rows come back?
Show answer
SELECT id FROM products WHERE name ILIKE '%100#%%' ESCAPE '#' ORDER BY id; It returns only id 5. The #% in the pattern is a literal percent sign. The outer % characters are wildcards. Row 6 (100 cotton socks) has no percent sign, and row 7 is NULL, so neither matches.
Exercise
A colleague writes SELECT id FROM products WHERE name NOT ILIKE 'phone%' and is surprised that row 7 is missing from the result, and that rows 2 and 4 are present. Explain both observations.
Show answer
Row 7 has a NULL name, so NOT ILIKE evaluates to NULL and the row is filtered out. Rows 2 (Smartphone) and 4 (Headphones) are returned because the pattern phone% is anchored at the start of the string, and neither name starts with "phone". To exclude any name containing phone, use NOT ILIKE '%phone%'. To keep NULL rows, add OR name IS NULL.