Text Pattern Ops Prefix LIKE Index
Serve LIKE 'prefix%' queries from a btree index by declaring the text_pattern_ops operator class, because collation-ordered indexes cannot.
Code
-- 默认 collation 的 btree 按语言规则排序,无法服务 LIKE 'abc%';
-- text_pattern_ops 操作符类按逐字符序建索引,前缀匹配才能走索引
CREATE INDEX idx_products_name_pattern
ON products (name text_pattern_ops);
-- 前缀查询走该索引:LIKE 模式以常量开头
EXPLAIN
SELECT product_id, name FROM products WHERE name LIKE 'Widget%';
-- 代价:逐字符序不等于 collation 序,该索引服务不了 ORDER BY name
-- 需要按 name 排序时另建常规索引,两者各司其职
SELECT product_id, name FROM products WHERE name LIKE 'Widget%' ORDER BY product_id;
-- 局限:'%Widget'(前导通配)与 ILIKE 都用不上这个索引
SELECT product_id, name FROM products WHERE name ILIKE 'widget%';How it works
Several statements share this file — SELECT / CREATE / EXPLAIN, with products among the objects involved.
What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.
Applying it
Run it in the products database context.
Statements that matter
SELECT product_id, name FROM products WHERE name LIKE 'Widget%' ORDER BY product_id;
EXPLAIN
SELECT product_id, name FROM products WHERE name LIKE 'Widget%';
SELECT product_id, name FROM products WHERE name ILIKE 'widget%';
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables or CTEs does it reference?
- `products` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.