LIKE, ILIKE and regular expressions
wildcards, escapes, ~ and ~*. and the case-sensitivity surprise in the C collation.
- address
- everything.basics.pattern_matching
- part
- part 2, one table
- chapter
- chapter 8 of 12
- reading time
- 8 min
LIKE matches text against a pattern with two wildcards: % is any run of characters (none included) and _ is exactly one. it's case-sensitive. ILIKE isn't, and it's postgres only. ~ and ~* match POSIX regular expressions.
the postgres in this page uses the C collation: text compares by its bytes, so every capital sorts before every lower-case letter, and 'Zoe' < 'a'.
the picture
you know how WHERE name = 'ada lovelace' finds nobody, even though Ada is right there? = means the exact same string, capital A and capital L included. when you know only part of what you're looking for, or not the capitals, you need a pattern.
think of a stencil laid over each name. most of the stencil is solid letters that have to match exactly. an _ is a hole one letter wide, anything shows through. a % is a hole that stretches to whatever length it needs, including nothing. if the whole name fits the stencil, end to end, it matches.
| name | |||||||
|---|---|---|---|---|---|---|---|
| Sam Lee | true | true | false | false | false | false | true |
| Zoë Martin | false | false | true | false | false | false | false |
| Zoe Martin | false | false | true | false | false | false | false |
| Sean O'Neil | true | false | false | false | false | true | false |
| Null | false | false | false | false | false | false | false |
| Ana Lima | false | false | false | false | true | false | true |
| Ada Lovelace | false | false | false | false | true | false | false |
2 of 7a capital S, then anything. Sam and Sean.
~*, looks for its pattern anywhere in the name and ignores case too.% and _
LIKE has to match the whole string, which is why most patterns start or end with %. here's how three of them line up, one character at a time:
the wildcards are ordinary characters everywhere else, which makes _ sneaky. in an email, a sku or an identifier, an underscore you meant literally matches any character:
SELECT email FROM customers WHERE email LIKE 'zoe_martin%' ORDER BY email;| emailtext |
|---|
| zoe.martin@example.com |
that pattern was meant to find zoe_martin@.... it found zoe.martin@example.com, because _ matched the dot. to mean a literal % or _, put a backslash in front of it, or name your own escape character with ESCAPE:
SELECT '100%' LIKE '100\%' AS backslash,
'100x' LIKE '100\%' AS not_a_wildcard,
'100%' LIKE '100!%' ESCAPE '!' AS own_escape;| backslashbool | not_a_wildcardbool | own_escapebool |
|---|---|---|
| t | f | t |
case, ILIKE and the C collation
LIKE is case-sensitive, always. postgres has ILIKE for case-insensitive matching (~~* is its operator, if you see that in a plan), but it's postgres only. the portable spelling lowers both sides:
SELECT name FROM customers WHERE name ILIKE 'ada%' ORDER BY name;
SELECT name FROM customers WHERE lower(name) LIKE 'ada%' ORDER BY name;| nametext |
|---|
| Ada Lovelace |
| nametext |
|---|
| Ada Lovelace |
Ada Lovelace either way. so where's the surprise? it's in comparing and sorting text, and it comes from the collation this page's database was created with:
SELECT datcollate, datctype FROM pg_database WHERE datname = current_database();| datcollatetext | datctypetext |
|---|---|
| C | C.UTF-8 |
datcollate is C: strings compare by their bytes. datctype is C.UTF-8: postgres still knows that ë is a letter and that its capital is Ë, so upper(), lower() and ILIKE work on any alphabet here. it's only the order that's byte by byte:
| charactertext | utf8_bytestext |
|---|---|
| A | 41 |
| Z | 5a |
| a | 61 |
| e | 65 |
| z | 7a |
| É | c389 |
| ë | c3ab |
so here, 'Zoe' < 'a' is true, ORDER BY name puts every capitalised name before every lower-case one, and Zoë sorts after Zoe, because ë's first byte (c3) is bigger than e's (65). a range like name >= 'a' AND name < 'b' finds names starting with a small a, and no Ada. a server created with a language's collation sorts the way a dictionary does (sorting with ORDER BY shows one), and text, varchar and collations covers how to choose.
asking otherwise means a nondeterministic ICU collation, where strings that differ only in case count as equal. since postgres 18 pg 18+, LIKE works with those too. the browser engine can't build one, so here's a real server:
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
SELECT name
FROM (VALUES ('Zoë Martin'), ('ZOË MARTIN'), ('Zoe Martin')) AS t (name)
WHERE name LIKE 'zoë%' COLLATE ci
ORDER BY name;| nametext |
|---|
| ZOË MARTIN |
| Zoë Martin |
checked on a real postgres 18.6 server. the browser engine can't run this one.
ks-level2 means "case doesn't matter, accents do": both spellings of Zoë match, plain Zoe doesn't. before 18, the same LIKE was an error.
regular expressions
when % and _ aren't enough, postgres has POSIX regular expressions: ~ matches, ~* matches ignoring case, and !~ and !~* are their negations.
SELECT 'Sam Lee' LIKE 'Lee' AS like_lee,
'Sam Lee' ~ 'Lee' AS regex_lee;SELECT 'Sam Lee' LIKE 'Lee' AS like_lee,
'Sam Lee' ~ 'Lee' AS regex_lee,
'Sam Lee' ~ '^Lee$' AS anchored;| like_leebool | regex_leebool | anchoredbool |
|---|---|---|
| f | t | f |
two differences from LIKE trip people up, and that was the first: a regular expression matches anywhere in the string unless you anchor it with ^ and $. the second is that its wildcards are different: . is one character, .* is any run.
SELECT sku, name FROM products WHERE sku ~ '^MSC-' ORDER BY sku;
SELECT count(*) AS odd_skus FROM products WHERE sku !~ '^[A-Z]{3}-[0-9]{4}$';| skutext | nametext |
|---|---|
| MSC-0100 | large lantern |
| MSC-0150 | smart stapler |
| odd_skusint8 |
|---|
| 0 |
the two products with an MSC- sku are the generated ones with no category (their sku prefix fell back to MSC), and every sku fits the three letters, dash, four digits shape. the same syntax pulls pieces out of strings and rewrites them:
SELECT substring('ada@example.com' from '@(.*)$') AS domain,
regexp_replace('Sean O''Neil', '[^A-Za-z]', '', 'g') AS letters_only;| domaintext | letters_onlytext |
|---|---|
| example.com | SeanONeil |
one level deeperSIMILAR TO, the third syntax
the standard has one more: SIMILAR TO, which takes LIKE's % and _ and adds a few regular-expression pieces like | and parentheses. postgres implements it by translating the pattern into a regular expression, and the plan shows the translation:
EXPLAIN (COSTS OFF) SELECT id FROM products WHERE name SIMILAR TO '%(kite|yo-yo)';it's neither as simple as LIKE nor as capable as ~, so most people use one of those instead.
keylines
- LIKE matches the whole string: % is any run of characters, _ is exactly one.
- LIKE is case-sensitive. ILIKE isn't, and is postgres only. lower() on both sides is portable.
- escape a literal % or _ with a backslash, or pick your own with ESCAPE.
- ~ and ~* are regular expressions, and they match anywhere unless anchored.
- this page compares text in C: by bytes, so capitals come first and Zoë sorts after Zoe.