skip to content

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.

each string against each pattern
name
Sam Leetruetruefalsefalsefalsefalsetrue
Zoë Martinfalsefalsetruefalsefalsefalsefalse
Zoe Martinfalsefalsetruefalsefalsefalsefalse
Sean O'Neiltruefalsefalsefalsefalsetruefalse
Nullfalsefalsefalsefalsefalsefalsefalse
Ana Limafalsefalsefalsefalsetruefalsetrue
Ada Lovelacefalsefalsefalsefalsetruefalsefalse

2 of 7a capital S, then anything. Sam and Sean.

real output, postgres 18.6 (PGlite 0.5.12) · pattern-matching
click a pattern to light its column. LIKE wants the whole name to fit, capitals and all. ILIKE ignores case. the regular expression, with ~*, 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:

S
0
↑S
a
1
m
2
␣
3
↑%
L
4
e
5
e
6

'Sam Lee' LIKE 'S%': the S matches the S, and % takes the other six characters. true.

step 1/3
a pattern lined up against a name. literal characters must match exactly, _ takes one character, a % stretches over the rest. one mismatch and it's false. drawn by hand; the verdicts are the grid's.

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:

sqldb=shop
SELECT email FROM customers WHERE email LIKE 'zoe_martin%' ORDER BY email;
output, from postgres 18.6
SELECT 1
emailtext
zoe.martin@example.com
(1 row)

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:

sqlempty db
SELECT '100%' LIKE '100\%'            AS backslash,
       '100x' LIKE '100\%'            AS not_a_wildcard,
       '100%' LIKE '100!%' ESCAPE '!' AS own_escape;
output, from postgres 18.6
SELECT 1
backslashboolnot_a_wildcardboolown_escapebool
tft
(1 row)

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:

sqldb=shop
SELECT name FROM customers WHERE name ILIKE 'ada%' ORDER BY name;
SELECT name FROM customers WHERE lower(name) LIKE 'ada%' ORDER BY name;
output, from postgres 18.6
#1 · SELECT 1
nametext
Ada Lovelace
(1 row)
#2 · SELECT 1
nametext
Ada Lovelace
(1 row)

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:

sqlempty db
SELECT datcollate, datctype FROM pg_database WHERE datname = current_database();
output, from postgres 18.6
SELECT 1
datcollatetextdatctypetext
CC.UTF-8
(1 row)

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:

charactertextutf8_bytestext
A41
Z5a
a61
e65
z7a
Éc389
ëc3ab
(7 rows)
seven characters, sorted by this page's postgres, with the UTF-8 bytes it sorted by. capitals are 41 to 5a, small letters 61 to 7a, and anything accented starts with c3, after all of them.

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:

sqlempty db
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;
output, from a real postgres 18.6 server
#1 · CREATE COLLATION
#2 · SELECT 2
nametext
ZOË MARTIN
Zoë Martin
(2 rows)

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.

predict the output
sql
SELECT 'Sam Lee' LIKE 'Lee' AS like_lee,
       'Sam Lee' ~ 'Lee'    AS regex_lee;
sqlempty db
SELECT 'Sam Lee' LIKE 'Lee' AS like_lee,
       'Sam Lee' ~ 'Lee'    AS regex_lee,
       'Sam Lee' ~ '^Lee$'  AS anchored;
output, from postgres 18.6
SELECT 1
like_leeboolregex_leeboolanchoredbool
ftf
(1 row)

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.

sqldb=shop
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}$';
output, from postgres 18.6
#1 · SELECT 2
skutextnametext
MSC-0100large lantern
MSC-0150smart stapler
(2 rows)
#2 · SELECT 1
odd_skusint8
0
(1 row)

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:

sqlempty db
SELECT substring('ada@example.com' from '@(.*)$') AS domain,
       regexp_replace('Sean O''Neil', '[^A-Za-z]', '', 'g') AS letters_only;
output, from postgres 18.6
SELECT 1
domaintextletters_onlytext
example.comSeanONeil
(1 row)
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:

sqldb=shop
EXPLAIN (COSTS OFF) SELECT id FROM products WHERE name SIMILAR TO '%(kite|yo-yo)';
output, from postgres 18.6
EXPLAIN
Seq Scan on products Filter: (name ~ '^(?:.*(?:kite|yo-yo))$'::text)

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.