PostgreSQL LIKE & ILIKE
= only finds exact matches. To search inside text, such as all titles that start with "The" or emails at a certain domain, use pattern matching with LIKE.
Wildcards
| Wildcard | Matches | Example | Matches |
|---|---|---|---|
% |
any sequence of characters, including none | 'The %' |
"The Salt Road", "The Map Thief" |
_ |
exactly one character | '_ip' |
"tip", "zip", not "trip" |
SELECT title FROM books WHERE title LIKE 'The %'; title
-------------------
The Salt Road
The Last Orbit
The Quiet Witness
The Age of Canals
The Map Thief
(5 rows)
% can appear anywhere. Titles that contain "of" as a word:
SELECT title FROM books WHERE title LIKE '% of %'; title
------------------------
Empires of Sand
The Age of Canals
A Short History of Tea
(3 rows)
The underscore matches one character exactly. Four-letter first names that end with "a":
SELECT first_name FROM customers WHERE first_name LIKE '___a'; first_name
------------
Anna
Emma
Gina
Isla
(4 rows)
Case-insensitive matching with ILIKE
LIKE is case-sensitive. PostgreSQL's ILIKE ignores case, which is usually what a search box needs:
SELECT title FROM books WHERE title LIKE '%sql%';
SELECT title FROM books WHERE title ILIKE '%sql%'; title
-------
(0 rows)
title
---------------------------
Learning SQL the Calm Way
(1 row)
| Operator | Same as |
|---|---|
LIKE |
~~ |
ILIKE |
~~* |
NOT LIKE |
!~~ |
NOT ILIKE |
!~~* |
NOT LIKE
Customers whose email is not an example.com address. Note that NULL emails are not returned either: NULL NOT LIKE '…' is NULL, not true.
UPDATE customers SET email = 'ben@carter.dev' WHERE id = 2;
SELECT first_name, email
FROM customers
WHERE email NOT LIKE '%@example.com';UPDATE 1
first_name | email
------------+----------------
Ben | ben@carter.dev
(1 row)
Searching for a literal % or _
To match the wildcard characters themselves, escape them with a backslash (the default escape character), or choose another one with ESCAPE:
CREATE TABLE promos (code text);
INSERT INTO promos VALUES ('SAVE10%'), ('SAVE10'), ('BOOK_DAY'), ('BOOKDAY');
SELECT code FROM promos WHERE code LIKE '%\%';
SELECT code FROM promos WHERE code LIKE 'BOOK!_%' ESCAPE '!';CREATE TABLE
INSERT 0 4
code
---------
SAVE10%
(1 row)
code
----------
BOOK_DAY
(1 row)
Regular expressions
When LIKE is not expressive enough, PostgreSQL supports POSIX regular expressions with ~ (case-sensitive) and ~* (case-insensitive). Titles that end in a word of exactly four letters:
SELECT title FROM books WHERE title ~ ' [A-Za-z]{4}