Sub topic 15
Indexing for lower(), LIKE and trigram searches
This chapter assumes you can read a basic EXPLAIN plan and know what a B-tree index is. It also assumes you have met lower(), LIKE, ILIKE and ~ in the earlier chapters. Here you will learn which index serves which string filter, and why a query often ignores an index you think should help.
Why a plain index is not enough
A B-tree index on email stores the column values in sorted order. The planner can use it only when the query's condition is expressed in terms of the indexed value, using an operator the index supports. These filters look harmless, but each one breaks that rule:
WHERE lower(email) = '[email protected]'filters on a computed value that the index does not contain.WHERE name ILIKE '%phone%'starts with a wildcard, so sort order gives no starting point for the search.WHERE name LIKE 'Ph%'can use a plain B-tree only under certain collations (see below).
The result is a sequential scan of the whole table. That is fine for a few thousand rows and a problem for millions.
Expression indexes for case-insensitive equality
An expression index stores the result of an expression instead of the raw column. PostgreSQL computes the expression once when each row is written, then looks the value up like any other key.
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL
);
INSERT INTO users (email)
SELECT 'User' || g || '@Example.com'
FROM generate_series(1, 100000) AS g;
CREATE INDEX idx_users_email_lower ON users (lower(email));
ANALYZE users;
EXPLAIN
SELECT id
FROM users
WHERE lower(email) = lower('[email protected]');The plan should show an index scan or bitmap index scan on idx_users_email_lower. The right-hand side, lower('[email protected]'), is a constant, so the planner evaluates it once.
The query must use the same expression as the index. An index on lower(email) does nothing for upper(email) = ... or for email ILIKE .... The match is on the expression tree, so lower(email) and lower(trim(email)) are different expressions.
Enforcing uniqueness regardless of case
The same technique makes a unique constraint case-insensitive:
CREATE UNIQUE INDEX idx_users_email_lower_uq ON users (lower(email));After this, inserting [email protected] fails if [email protected] already exists. A normal UNIQUE constraint on email would treat them as different values.
Expression indexes must use immutable functions
Index expressions may only call functions marked IMMUTABLE, meaning the same input always gives the same output. lower() qualifies for a fixed column collation. Functions that depend on the current time or on session settings do not qualify. If you try, PostgreSQL rejects the statement with an error such as functions in index expression must be marked IMMUTABLE. Do not work around this by relabelling a function you do not control, because a wrong label leads to a corrupt index.
Prefix searches with LIKE
LIKE 'abc%' is a range search in disguise: everything from abc up to just before abd. A B-tree can do that, but only if its sort order agrees with the character-by-character ordering the range assumes. Locale-aware collations such as en_US.UTF-8 sort by linguistic rules, which ignore punctuation and case differences at the first level, so the planner cannot use the index for LIKE.
You have two options:
- Create the database or column with the
Ccollation, where order is byte order. - Add an index with the
text_pattern_opsoperator class, which compares character by character.
CREATE INDEX idx_users_email_prefix
ON users (email text_pattern_ops);
CREATE INDEX idx_users_email_lower_prefix
ON users (lower(email) text_pattern_ops);
EXPLAIN
SELECT id
FROM users
WHERE lower(email) LIKE 'user77%';For varchar columns use varchar_pattern_ops. The second index serves case-insensitive prefix searches, since the query lowercases the column and the pattern is lowercase.
An index with a pattern operator class is useful for LIKE, anchored regular expressions such as ~ '^abc', and equality. It cannot serve <, > or ORDER BY in a locale-aware order. If you need both, keep two indexes: a default one and a pattern one.
Trigram indexes for substring, ILIKE and regex searches
A trigram is a group of three consecutive characters. The pg_trgm extension splits text into trigrams, so phone yields roughly pho, hon and one, plus padded edge forms. A trigram index records which rows contain which trigrams. To answer ILIKE '%phone%', PostgreSQL looks up the trigrams of phone, intersects the row lists, and rechecks the candidates against the real pattern.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
INSERT INTO products (name)
SELECT 'Product ' || md5(g::text) || CASE WHEN g % 500 = 0 THEN ' Phone case' ELSE '' END
FROM generate_series(1, 100000) AS g;
CREATE INDEX idx_products_name_trgm
ON products USING gin (name gin_trgm_ops);
ANALYZE products;
EXPLAIN
SELECT id, name
FROM products
WHERE name ILIKE '%phone%';The plan should use a bitmap index scan on idx_products_name_trgm. One index covers these filters:
LIKEandILIKEwith any wildcard placement.- Regular expression operators
~and~*. - Similarity search with
%and<%, which finds approximate matches such as typos.
SELECT id, name, similarity(name, 'Fone case') AS score
FROM products
WHERE name % 'Fone case'
ORDER BY score DESC
LIMIT 5;The % operator here is the similarity operator from pg_trgm, not a LIKE wildcard. It returns true when similarity exceeds pg_trgm.similarity_threshold, which defaults to 0.3.
GIN or GiST
Both index types accept the trigram operator classes. gin_trgm_ops makes faster lookups and larger, slower-to-update indexes. gist_trgm_ops is smaller and cheaper to maintain, and it supports ordering by distance with <-> for nearest-match queries. For mostly-read tables with LIKE filters, start with GIN.
Limits of trigram search
- Patterns shorter than three useful characters give the index little to work with.
ILIKE '%ph%'may fall back to scanning most of the index or the table. - The index is a filter. PostgreSQL still rechecks each candidate row against the real pattern.
- Case-insensitive
ILIKEworks with the index directly, because trigrams are built from lowercased text. You do not needlower()here. - Trigram handling of non-alphanumeric characters depends on the database locale. Test with your real data.
What indexes cost
Every index slows writes and takes disk space. A GIN trigram index on a long text column can be several times the size of the column itself. Each insert or update of that column has to add trigram entries. Create the indexes your actual queries need, and check with EXPLAIN (ANALYZE, BUFFERS) that the planner uses them. On a tiny table the planner prefers a sequential scan because it is cheaper, so test with realistic row counts.
Summary table
| Filter | Index that helps |
|---|---|
| `lower(col) = lower($1)` | B-tree on `lower(col)` |
| `col LIKE 'abc%'` in a non-C collation | B-tree with `text_pattern_ops` |
| `lower(col) LIKE 'abc%'` | B-tree on `lower(col) text_pattern_ops` |
| `col LIKE '%abc%'` or `col ILIKE '%abc%'` | GIN or GiST with `gin_trgm_ops` or `gist_trgm_ops` |
| `col ~* 'pattern'` | Trigram index |
| `col % 'typo'` (fuzzy match) | Trigram index |
Common mistakes
- Indexing
emailand queryinglower(email). The index is ignored. - Indexing
lower(email)and queryingemail ILIKE .... The index is ignored. - Expecting a default B-tree to serve
LIKE 'abc%'underen_US.UTF-8. - Judging an index on a table with a few hundred rows. The planner correctly skips it.
- Forgetting that the unique index on
lower(email)needs your application to handle the duplicate-key error.
Exercise
Your table customers(id, last_name text) has about 5 million rows in a database with the en_US.UTF-8 collation. Users search with WHERE last_name ILIKE 'mc%' and with WHERE last_name ILIKE '%son'. Name one index that serves both queries, and explain why a B-tree on last_name serves neither.
Show answer
Create a trigram index: CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE INDEX idx_customers_last_name_trgm ON customers USING gin (last_name gin_trgm_ops);. It supports ILIKE with the wildcard at the start or the end. A plain B-tree on last_name is not used for ILIKE, because its operators are for case-sensitive comparison. It is also unusable for '%son', which has a leading wildcard, and under en_US.UTF-8 it cannot serve even a case-sensitive LIKE 'Mc%' without text_pattern_ops.
Exercise
You created CREATE INDEX ON users (lower(email));. Which of these queries can use it: (a) WHERE lower(email) = '[email protected]', (b) WHERE email = '[email protected]', (c) WHERE lower(trim(email)) = '[email protected]'?
Show answer
Only (a). The index stores the value of lower(email), so the query must contain that exact expression. Query (b) compares the raw column, and query (c) uses a different expression, lower(trim(email)), so neither can use the index.