Practical technical guides / Core IT: databases (PostgreSQL indexes and collation)

A PostgreSQL LIKE Prefix Search Ignores Its B-tree Index Under a Non-C Collation: text_pattern_ops and COLLATE C

Measured on PostgreSQL 18.4 with an en-US collation: a default B-tree serves ORDER BY but not LIKE prefix%. text_pattern_ops or COLLATE C serve LIKE. Keep both.

By Sandeep Belgavi · Published 2026-11-07

Measured on PostgreSQL 18.4 with an en-US collation: a default B-tree serves ORDER BY but not LIKE prefix%. text_pattern_ops or COLLATE C serve LIKE. Keep both.

The index that a prefix search does not use

The catalogue at Belgavi's Book Store has a book table with a title column and an ordinary B-tree index on it. The search box sends prefix queries: WHERE title LIKE 'The Garden of River%'. On a developer laptop the query is instant and EXPLAIN shows an index scan. On the production database it is a sequential scan of every row, even though the index exists and only 2,000 of 200,000 titles match.

The difference is the database collation. The laptop cluster was created with the C locale; production uses en-US. Under any collation other than C, a default B-tree index on a text column cannot serve a LIKE prefix search. This guide measures exactly which queries each kind of index can serve on PostgreSQL 18.4, and how to get both fast prefix search and fast sorting.

Why the collation matters

A B-tree index stores keys in the collation's sort order. For LIKE 'abc%' the planner rewrites the pattern into a range, roughly title >= 'abc' AND title < 'abd', and scans that range of the index. That rewrite is only valid if every string starting with abc sorts between those two bounds, which is true for byte-wise comparison and not in general for linguistic collations, where case, accents and punctuation can be ignored or weighted and the "next" string is not simply the last character plus one.

The PostgreSQL documentation on operator classes states the consequence and the remedy. The operator classes text_pattern_ops, varchar_pattern_ops and bpchar_pattern_ops compare values "strictly character by character rather than according to the locale-specific collation rules. This makes these operator classes suitable for use by queries involving pattern matching expressions (LIKE or POSIX regular expressions) when the database does not use the standard C locale." It adds: "If you do use the C locale, you do not need the xxx_pattern_ops operator classes", and, importantly, that queries using ordinary <, <=, > or >= comparisons "cannot use the xxx_pattern_ops operator classes".

The measurement

The companion probe creates a disposable schema on a PostgreSQL 18.4 cluster whose default collation is ICU en-US, loads 200,000 synthetic titles such as The Garden of River 1023, and runs EXPLAIN (FORMAT JSON) for six queries under four index setups. Each plan is recorded twice, with enable_seqscan on and off; if the plan is still a sequential scan with it off, the index cannot be used for that query at all.

QueryDefault B-treetext_pattern_opsB-tree on title COLLATE "C"Default plus text_pattern_ops
LIKE 'The Garden of River%'Seq ScanBitmap Index ScanBitmap Index ScanBitmap Index Scan
title COLLATE "C" LIKE '...%'Seq ScanBitmap Index ScanBitmap Index ScanBitmap Index Scan
title ^@ 'The Garden of River'Seq ScanBitmap Index ScanBitmap Index ScanBitmap Index Scan
ORDER BY title LIMIT 20Index ScanSort over Seq ScanSort over Seq ScanIndex Scan
title >= ... AND title < ...Index ScanSeq ScanSeq ScanIndex Scan
ILIKE 'the garden of river%'Seq ScanSeq ScanSeq ScanSeq Scan

Every cell held with enable_seqscan both on and off. The default index serves ordering and range queries in the database collation and nothing pattern-shaped. A text_pattern_ops index and a C-collated index serve prefix LIKE and the ^@ starts-with operator and nothing that needs the database's sort order. Adding COLLATE "C" to the query does not let it use a default-collation index; the index and the expression must agree. ILIKE uses none of them.

Reading the plans

Three details in the table are worth slowing down for.

The pattern indexes show up as a bitmap index scan feeding a bitmap heap scan, not a plain index scan. With 2,000 matching rows, about one percent of the table, the planner prefers to collect matching row locations from the index first and then read the heap pages in physical order. That is the plan you want for a prefix that matches many rows; for a very selective prefix it may switch to a plain index scan. Either way the index is doing the filtering.

The enable_seqscan off column is the diagnostic. Turning it off does not forbid sequential scans; it makes them look very expensive, so the planner picks any usable index instead. When the plan is still a sequential scan, there is no index the planner is allowed to use for that expression, and no amount of ANALYZE, statistics tuning or cost settings will change that. That turns "the planner is being stupid" into a precise statement: the index and the query do not match.

The ^@ operator is PostgreSQL's starts-with test (also available as the starts_with function). It behaved like LIKE 'prefix%' here: served by the pattern and C indexes, not by the default one. Using it avoids having to escape % and _ in user input, which you must otherwise do before building a LIKE pattern from a search box.

The fix: two indexes with two jobs

If the table needs both prefix search and ordered listing, keep the default index and add a pattern index:

CREATE INDEX book_title ON book (title);                         -- ORDER BY, ranges, equality
CREATE INDEX book_title_prefix ON book (title text_pattern_ops); -- LIKE 'prefix%', ^@

Choose between text_pattern_ops and a COLLATE "C" index by what else you need. A C-collated index also sorts byte-wise, so ORDER BY title COLLATE "C" can use it; text_pattern_ops exists only to serve pattern and equality comparisons. Either way the planner chooses the right index per query, and the probe's fourth column shows every query except ILIKE getting an index.

For case-insensitive prefix search, index the expression the query uses (this and the trigram option below are standard PostgreSQL features that the probe did not measure):

CREATE INDEX book_title_lower_prefix ON book (lower(title) text_pattern_ops);
SELECT id FROM book WHERE lower(title) LIKE lower('The Garden of River') || '%';

For substring or fuzzy search (LIKE '%river%'), no B-tree helps; the pg_trgm extension's GIN or GiST trigram indexes are the standard answer.

Why it passes in development

The laptop cluster was initialised with C or POSIX, often by a container image default, so the default index serves LIKE there. The production cluster was created with the operating system's locale. Both behaviours are correct; the tests just ran under a different collation from production. Check what you have:

SELECT datname, datlocprovider, datcollate, datlocale FROM pg_database WHERE datname = current_database();

and make development and CI clusters match production's locale provider and locale.

A migration path for a live table

  1. Run EXPLAIN for each search query in production and list the ones showing a sequential scan on a large table.
  2. Build the pattern index with CREATE INDEX CONCURRENTLY so writes continue. Check afterwards that it is valid in pg_index, since a failed concurrent build leaves an invalid index behind.
  3. Re-run EXPLAIN and compare plans and timings on production-sized data, not on a sample, because the planner's choice depends on statistics and row counts.
  4. Keep the default index if anything orders or ranges by the column. Dropping it to "replace" it with the pattern index is a common mistake that the fourth and fifth rows of the table expose.

Tradeoffs and failure modes

  • Two indexes cost writes and space. Every insert and update of title maintains both. For a write-heavy column, decide whether prefix search is worth it.
  • Collation changes outside your control. An operating system upgrade that changes glibc or ICU versions can change sort order and corrupt linguistic indexes until they are rebuilt. Pattern-ops and C indexes are byte-wise and not affected by that particular problem.
  • Non-deterministic collations. Case- or accent-insensitive ICU collations change what LIKE means; test patterns on them explicitly.
  • Parameterised patterns. A pattern passed as a parameter (LIKE $1) can only use the index if the planner can see a constant prefix, which with generic plans it may not. Check the plan for the prepared statement, not only for a literal.

Verification

The companion probe prints the full table above from a live cluster, and its offline tests assert every cell against the recording, including that only the two-index setup covers prefix search, ordering and ranges together. To check your own database, run the same EXPLAIN pairs with enable_seqscan on and off for each query your application sends. A plan that stays sequential with it off means no index can serve that query as written.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/like_prefix_index. Views are my own and do not represent any employer, past or present.