Skip to content
← All posts

Dec 1, 2026

Your search is slow because LIKE '%query%' can't use an index

Every dashboard ships the same search box: `WHERE name ILIKE '%term%'`. It works until the table grows, because a leading wildcard defeats the B-tree index — the database has to check every row. The fix is a trigram index, and knowing when full-text search is the better tool instead.

PostgreSQLNode.jsPerformance

Every dashboard ships the same search box. A customer name, a product, an invoice number — the user types a few letters and the list narrows. The query behind it is always the same shape:

SELECT * FROM customers WHERE name ILIKE '%rahim%';

It works. It works on a thousand rows, and it works on ten thousand. Then the table grows, the search gets slow, and the first instinct is to add an index on the column. So you add one, run the query again, and nothing changes. The index sits there unused while the database scans the whole table anyway.

The index is not broken. The query is asking it a question it cannot answer.

A B-tree is sorted — and a leading wildcard has no starting point

A B-tree index keeps values in sorted order. That is what makes it fast at equality and at prefix searches: LIKE 'rahim%' means "everything between rahim and rahin", a contiguous range in sorted order. The database jumps straight to where that range starts.

LIKE '%rahim%' asks for values that contain rahim anywhere. Those values are scattered across the whole sorted order. There is no range to jump to, so there is nothing for the index to do — the database has no choice but to check every row. ILIKE adds case-insensitivity and changes nothing about this.

Run EXPLAIN ANALYZE on the query and you will see it plainly: Seq Scan, one row at a time, however many rows the table holds. The index exists; the planner just cannot use it.

If your search only ever needs a prefix — autocomplete that matches from the start of the name — the B-tree you already have is the answer. One caveat in PostgreSQL: for LIKE to use a plain B-tree index on a pattern, the index needs the text_pattern_ops operator class, or the column needs the C collation. Without one of those, even the prefix search may scan.

But most dashboard searches are "contains", not "starts with". For that you need a different kind of index.

Trigrams: index every three characters

PostgreSQL ships an extension called pg_trgm that solves exactly this. It breaks every value into every sequence of three characters: rahim becomes r, ra, rah, ahi, him, im — padded at the ends. A GIN index maps each trigram to the rows that contain it, so a search for %rahim% looks up the rows containing rah, ahi, and him, and only checks those rows:

-- once per database
CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- build it without locking the table for writes
CREATE INDEX CONCURRENTLY customers_name_trgm
  ON customers USING gin (name gin_trgm_ops);

The query does not change at all — the same ILIKE '%rahim%' now uses the index. One write-up that tested this on 200,000 product names saw the substring query drop from a parallel scan of about 82 ms to a bitmap index scan of about 16 ms, and a rarer pattern that matched 23 rows took 3.5 ms. Your numbers will differ; the shape of the improvement is the point.

Trigrams buy you a second feature for free: fuzzy matching. The % operator is true when two strings are similar enough, so a typo still finds the row:

-- finds "Rahim" even if the user typed "Rahmi"
SELECT * FROM customers WHERE name % 'Rahmi' ORDER BY name <-> 'Rahmi' LIMIT 10;

The default similarity threshold is 0.3 — raise it with SET pg_trgm.similarity_threshold = 0.5 to be stricter, lower it for more recall. The <-> operator is the distance between two strings, so ordering by it puts the closest match first. A GiST index (gist_trgm_ops) is the better fit if you order by distance often, because it can serve that ordering directly; GIN is usually faster for plain lookups.

Full-text search is a different tool

Trigrams match substrings. Full-text search matches words. If your search is over descriptions, notes, or long text — "find the order about the broken printer" — tsvector and tsquery are the right tool:

CREATE INDEX orders_notes_fts
  ON orders USING gin (to_tsvector('english', notes));

SELECT * FROM orders
WHERE to_tsvector('english', notes) @@ plainto_tsquery('english', 'broken printer');

It normalises words — lowercase, stemming, so running matches run — and it ranks results. But it does not do arbitrary substrings: searching rahim will not match rahman unless you use prefix matching (rahim:*). Trigrams for identifiers and names, full-text for prose. Pick the one that matches what the user is actually typing.

The honest limits

A trigram index is not free. GIN indexes are larger than B-tree indexes and slower to update — every insert and update has to write the trigrams too. PostgreSQL softens this with fastupdate, which buffers new entries in a pending list, but on a write-heavy table, measure before you assume. And a search term shorter than three characters produces no complete trigram, so the index cannot narrow anything — require at least three characters before searching, which pairs naturally with the debounce and request cancellation from the search-box post.

Two things that are not optional. First, the search term goes into the query as a bound parameter, never concatenated into the SQL string. Second, escape % and _ in the user's input before wrapping it in wildcards, or a user can turn their search into a match-everything pattern. And do not reach for Elasticsearch because the search felt slow — a trigram index handles the dashboard search box for a long time before an external search service earns its place.

The index you add has to match the question you ask. A B-tree answers "starts with". A trigram index answers "contains". Put the wrong one behind the search box and you will keep wondering why the query is slow while the index sits there, unused.