This Fixes: Slow LIKE and ILIKE Queries With pg_trgm

A search box that runs WHERE name ILIKE '%acme%' against a million-row table reads every one of those rows, every time. A B-tree index cannot help a leading wildcard, so Postgres falls back to a sequential scan. The fix is a trigram index, and it takes about three lines of SQL.

This is one of the most common performance complaints I get called in on: the customer-lookup screen, the audit-log filter, the “search by reference” box that was fine in staging with ten thousand rows and crawls in production with ten million. The query is honest, the plan is not the problem, and adding an ordinary index does nothing. The reason is structural, and once you see it the fix is obvious.

Why a B-tree cannot help a leading wildcard

A B-tree indexes values in sorted order. That makes it excellent at anchored prefix matches: name LIKE 'acme%' can use a standard B-tree, because Postgres knows every match sorts together in one contiguous range. The moment you put a wildcard at the front — '%acme%' or '%acme' — that ordering is worthless. The matching rows are scattered arbitrarily through the index, so the planner does the only thing it can and scans the whole table. ILIKE makes it worse, because the case-folding defeats even the anchored-prefix optimisation unless you have built the index to match.

You can see this directly. Given a table customers with a million rows:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name
FROM customers
WHERE name ILIKE '%acme%';

-- Seq Scan on customers  (cost=0.00..21943.00 rows=100 width=...)
--   Filter: (name ~~* '%acme%'::text)
--   Rows Removed by Filter: 999900
--   Execution Time: 180.4 ms

If you have ever stared at a plan like this and wondered why your carefully-built index is being ignored, the general answer is in why isn’t Postgres using my index — but for substring search the honest answer is that no B-tree could have helped in the first place.

Trigrams, and the three lines that fix it

A trigram is a three-character slice of a string. The word acme decomposes into the trigrams   a,  ac, acm, cme, me  (pg_trgm pads the ends). The insight is that a substring shares trigrams with any string that contains it, so if you index the trigrams of every value, you can find candidate rows for '%acme%' by looking up the trigrams of acme. A GIN index — an inverted index that maps each trigram to the rows containing it — does exactly that.

The extension ships with Postgres in contrib; you just enable it and build the index:

CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- GIN inverted index over the column's trigrams
CREATE INDEX customers_name_trgm_idx
    ON customers
    USING gin (name gin_trgm_ops);

-- On a busy table, avoid the write lock:
-- CREATE INDEX CONCURRENTLY customers_name_trgm_idx
--     ON customers USING gin (name gin_trgm_ops);

The gin_trgm_ops operator class is what teaches GIN to support LIKE, ILIKE, and regular-expression operators (~, ~*) as well as the similarity operators. Re-run the same ILIKE query and the plan changes to a bitmap index scan:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, name FROM customers WHERE name ILIKE '%acme%';

-- Bitmap Heap Scan on customers  (cost=... rows=...)
--   Recheck Cond: (name ~~* '%acme%'::text)
--   ->  Bitmap Index Scan on customers_name_trgm_idx
--         Index Cond: (name ~~* '%acme%'::text)
--   Execution Time: a few ms

The index produces a set of candidate rows; the Recheck Cond line is Postgres re-applying the original predicate to those candidates, because trigram matching is a filter that over-fetches slightly. That recheck is cheap because it runs against a handful of rows, not the whole table.

GIN or GiST: pick the right operator class

pg_trgm offers two operator classes and they are not interchangeable. gin_trgm_ops builds a GIN index: faster to search, and the right default for substring and ILIKE filtering. gist_trgm_ops builds a GiST index: slower to search and generally larger for this workload, but it supports ordered nearest-neighbour queries with the distance operator <->. If your query is ORDER BY name <-> 'acme' LIMIT 10 — give me the ten closest matches — GiST can return them straight from the index, which GIN cannot. For the ordinary “find rows containing this substring” case, choose GIN. For a top-N “most similar” ranking, choose GiST. The wider trade-offs between the index families are in the Postgres index type cheat-sheet.

Fuzzy matching, for free

The same index accelerates similarity search, which is what you actually want behind a “did you mean” box or a deduplication check. The % operator returns true when two strings exceed a similarity threshold, and similarity() returns the score between 0 and 1:

-- Default threshold is 0.3; raise it to be stricter
SET pg_trgm.similarity_threshold = 0.4;

SELECT name, similarity(name, 'acme corp') AS score
FROM customers
WHERE name % 'acme corp'          -- uses the GIN index
ORDER BY score DESC
LIMIT 20;

The % operator is index-accelerated; the ORDER BY similarity() still needs to sort the candidate set, but that set is small. Note the modern spelling: set pg_trgm.similarity_threshold as a normal parameter rather than calling the older set_limit() function, which is deprecated. The default threshold is 0.3.

What it costs

Nothing is free. A trigram GIN index is large — often a sizeable fraction of the indexed column’s own size — because it stores a posting list for every distinct trigram. It is also slower to build than a B-tree; on a large table budget real time for the initial CREATE INDEX, and use CONCURRENTLY so you do not take a write lock on a live table. Writes carry more overhead too, though GIN’s fastupdate mechanism buffers that and flushes it in batches. Very short search terms are the weak spot: a one- or two-character term has too few trigrams to be selective, so the planner may still choose a sequential scan — and correctly so.

If your candidate sets are large and the recheck-and-sort step spills, that is a memory-sizing question rather than an index one — see why a query suddenly spills to disk. But for the overwhelmingly common case — a substring search box that scans a growing table — the trigram index is the answer, and it is three lines. Add it before you reach for a separate search engine you then have to keep in sync.

Build and rescue work

Hands-on delivery of this kind is handled by Sixteen Pillars Studio.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Can you trust the architecture you have?

Architecture diagrams rarely show the reality of how systems actually operate. An independent review establishes what is really there.