In PostgreSQL, why can't a B-tree serve WHERE name ILIKE '%ridge%', and how does a gin_trgm_ops index make that search fast?
answer
- the wildcard comes first
- three-character pieces
- an extension, then an opclass
- short patterns give nothing to find
basics
~20 sA B-tree can only narrow a pattern anchored at the start. The pg_trgm extension's gin_trgm_ops indexes every three-character piece of the text, so LIKE, ILIKE and regex searches look up the pattern's trigrams and recheck only the candidate rows.
solid answer
~40 sA B-tree keeps strings in sort order, so it can narrow only a left-anchored pattern such as `'Ridge%'` (the B-tree leaf covers `text_pattern_ops` for that). `'%ridge%'` can start anywhere, so there is no range to scan. After `CREATE EXTENSION pg_trgm`, `CREATE INDEX ... USING gin (name gin_trgm_ops)` indexes the **trigrams**, the three-character groups of each name. For `ILIKE '%ridge%'`, PostgreSQL extracts the pattern's trigrams, looks each one up, intersects the row sets in a bitmap, and **rechecks** every candidate against the real pattern. One index serves `LIKE`, `ILIKE`, `~` and `~*`: trigrams are extracted case-insensitively in a default build, and the recheck applies the exact operator. A pattern too short to yield a trigram, such as `'%ab%'`, degenerates to a full-index scan, and inequality operators are not supported.
code
sql · 10 linesCREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX stations_name_trgm ON stations
USING gin (name gin_trgm_ops);
-- infix, case-insensitive: served by the trigram index
SELECT station_id, name FROM stations WHERE name ILIKE '%ridge%';
-- regular expression: also served
SELECT station_id, name FROM stations WHERE name ~* '(ridge|summit)';go deeper
Recall that a leading wildcard defeats a normal index and that the pg_trgm extension with a GIN trigram index is the standard fix for LIKE '%text%'.
Explain how trigrams are extracted from the pattern, why the Bitmap Heap Scan rechecks rows, and which operators the class supports, including ILIKE and regular expressions.
Judge when the index pays: pattern length, trigram selectivity, write volume on the column, and whether GIN or GiST with a tuned siglen fits the search.
Decide where infix search belongs as data grows, in PostgreSQL with trigram indexes or in a dedicated search tier, weighing consistency, operational cost and relevance needs.
## Why the B-tree cannot help A **B-tree** stores keys in sort order, so it can narrow a search only when it knows where in that order the matches start. `name LIKE 'Ridge%'` defines such a range (under a suitable collation or operator class, which the B-tree leaf covers). `name ILIKE '%ridge%'` does not: the fragment can sit anywhere in the string, so matching names are scattered across the whole sort order. Without another index, PostgreSQL reads every row of `stations` and tests the pattern. An expression index on `lower(name)` does not rescue it either. It makes case-insensitive equality and anchored prefixes indexable, but it still cannot locate a fragment in the middle of a string. ## Trigrams The **`pg_trgm`** contrib extension splits text into **trigrams**, groups of three consecutive characters. Each word is padded with spaces at its edges before splitting, and in a default build the characters are folded to lower case. A station named `Ridge Point` therefore yields trigrams such as `rid`, `idg`, `dge`, `poi` and `oin`. The extension provides two index operator classes: | Class | Method | Structure | |---|---|---| | `gin_trgm_ops` | GIN | an inverted index: each trigram with the set of rows containing it | | `gist_trgm_ops` | GiST | a lossy bitmap **signature** per entry, sized by `siglen` (default 12 bytes) | Both must be created inside a database where the extension is installed: ```sql CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE INDEX stations_name_trgm ON stations USING gin (name gin_trgm_ops); ``` ## How the search runs For `name ILIKE '%ridge%'`: 1. PostgreSQL extracts the trigrams the pattern guarantees, such as `rid`, `idg` and `dge`. 2. GIN looks up each trigram and intersects the row sets into a **bitmap**. 3. A **Bitmap Heap Scan** visits the candidate rows and **rechecks** the real `ILIKE` condition, because a row can contain all the trigrams without containing the fragment in that order. The index supports `LIKE`, `ILIKE`, the regular-expression operators `~` and `~*`, and `=`. It does not support inequality operators, and for plain equality a B-tree is usually more efficient. ## When it barely helps - **Short fragments.** `'%ab%'` has only two characters between wildcards, so no trigram can be extracted and the search degenerates to a **full-index scan**. The more trigrams a pattern yields, the more selective the lookup. - **Very common trigrams.** A fragment made only of trigrams found in most names gives a large bitmap, and the recheck then dominates. - **Write cost.** Every insert or update of `name` adds one entry per trigram. On a small `stations` table this is negligible; on a high-churn text column it is the usual GIN write amplification, softened by the pending list. ## GIN or GiST for trigrams The text-search chapter calls GIN the preferred index type for searching documents, and the same trade-off applies here: - **GIN** lookups are exact per trigram and fast to search; the index is larger and slower to update. - **GiST** stores a lossy signature, so it rechecks more rows; a larger `siglen` buys precision at the price of size. GiST can also order by trigram distance, which belongs to similarity ranking rather than pattern search. For an infix filter over station names, `gin_trgm_ops` is the normal choice. Similarity functions and ranking by closeness are a separate subject in the text-search leaf. ## Checking that it works 1. Run the query under `EXPLAIN (ANALYZE)` and look for a **Bitmap Index Scan** on `stations_name_trgm` beneath a Bitmap Heap Scan. 2. Compare the rows the index produced with the rows that survived the recheck; a large gap means the pattern's trigrams are not selective. 3. Try the real patterns users type, including short ones, before deciding the index is worth its write cost. On a table of a few thousand stations the planner may rightly prefer a sequential scan, because reading the whole table is cheap. The index earns its keep as the table grows, or when the same kind of filter runs over a much larger text column.
- Why does the plan still show rows removed by the index recheck after the trigram index is used?Trigram matching is a necessary but not sufficient test: a name can contain `rid`, `idg` and `dge` in other words or another order without containing `ridge`. GIN returns every row that has all the extracted trigrams, and the Bitmap Heap Scan rechecks the real `ILIKE` condition, discarding the false matches. Longer, more distinctive patterns leave fewer rows to discard.
- Does one gin_trgm_ops index serve both LIKE and ILIKE?Yes. In a default build of `pg_trgm`, trigrams are extracted case-insensitively, so the same index can find candidates for `LIKE`, `ILIKE`, `~` and `~*`. The recheck then applies the case-sensitive or case-insensitive operator the query actually used, so results stay exact.
- A B-tree on name serves ILIKE '%ridge%' once the table is analyzed.
- gin_trgm_ops works without installing any extension.
- A trigram index makes '%ab%' as fast as a long pattern.
- Rows returned by a trigram index never need rechecking.
- A trigram index on name also speeds up name > 'M'.