Sub topic 6
Operator classes: matching an index to your operators
An index can only answer a query condition if its operator class includes the operator in that condition. This chapter explains what an operator class is and how to list the ones available. It also covers the cases where you must pick a non-default class: prefix LIKE, trigram search, and jsonb containment.
This chapter assumes you can create B-tree and GIN indexes and read the output of EXPLAIN. It also assumes you know the basic jsonb and text operators.
What an operator class is
An index method such as B-tree, GIN, or GiST is a generic structure. It does not know what "less than" means for text, or what "contains" means for jsonb. An operator class supplies that knowledge. It does two things for one data type and one index method:
- It lists the operators the index can serve, such as
=,<,@>, or%. - It names the support functions the method calls internally, such as comparison, key extraction, or consistency checks.
Every indexed column has exactly one operator class. If you write nothing, PostgreSQL uses the default class for that data type and method. These two statements are equivalent:
CREATE INDEX t_a_idx ON t (a);
CREATE INDEX t_a_idx ON t (a int4_ops);The syntax puts the class after the column and before sort options:
CREATE INDEX accounts_handle_idx
ON accounts (handle text_pattern_ops DESC NULLS LAST);Operator classes belong to operator families. A family groups related classes so that cross-type comparisons work. For example, int2, int4, and int8 columns share the integer_ops family. That is why WHERE int4_col = 5::int8 can still use an index on an int4 column. You rarely need to think about families directly.
Why the planner needs a matching operator
The planner considers an index for a condition only when all of these hold:
- One side of the operator is the indexed column or expression.
- The operator belongs to the operator class of that index column.
- The other side does not depend on the row being scanned. A constant, parameter, or stable function qualifies.
If the operator is not in the class, the index is not considered, even if the column matches. No error or warning appears. You see a sequential scan in EXPLAIN and nothing else.
Listing available operator classes
The system catalogs describe every class. This query shows the classes available for text, grouped by index method:
SELECT am.amname AS method,
opc.opcname AS operator_class,
opc.opcdefault AS is_default
FROM pg_opclass opc
JOIN pg_am am ON am.oid = opc.opcmethod
WHERE opc.opcintype = 'text'::regtype
ORDER BY am.amname, opc.opcname;On a fresh database, expect text_ops (default) and text_pattern_ops for btree, text_ops (default) for hash, and text_ops for spgist. Classes from extensions appear after you run CREATE EXTENSION. With pg_trgm installed, gin_trgm_ops and gist_trgm_ops show up, and neither is the default.
To see which operators a class serves, join to pg_amop:
SELECT ao.amopstrategy AS strategy,
ao.amopopr::regoperator AS operator
FROM pg_opclass opc
JOIN pg_am am ON am.oid = opc.opcmethod
JOIN pg_amop ao ON ao.amopfamily = opc.opcfamily
WHERE am.amname = 'btree'
AND opc.opcname = 'text_pattern_ops'
ORDER BY ao.amopstrategy;The result is the operators ~<~, ~<=~, =, ~>=~, and ~>~. These compare strings byte by byte, ignoring locale rules. The next section shows why that matters.
Case 1: prefix LIKE on a B-tree
A default B-tree on a text column orders values by the database's collation. In a locale such as en_US.UTF-8, the sort order ignores case and punctuation in the early passes, so strings sharing a prefix are not guaranteed to be adjacent. PostgreSQL therefore cannot turn LIKE 'user12%' into a simple range scan on that index.
The text_pattern_ops class compares strings character by character. Strings with the same prefix then sit next to each other, and a left-anchored LIKE becomes a range scan.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
handle text NOT NULL
);
INSERT INTO accounts (handle)
SELECT 'user' || g
FROM generate_series(1, 200000) AS g;
CREATE INDEX accounts_handle_pattern_idx
ON accounts (handle text_pattern_ops);
ANALYZE accounts;
EXPLAIN
SELECT id FROM accounts WHERE handle LIKE 'user1234%';The plan should show an index or bitmap scan on accounts_handle_pattern_idx. Without the text_pattern_ops index, a database in a non-C locale shows a sequential scan for the same query.
The trade-off is that this index cannot serve ordinary comparisons such as handle < 'm' or ORDER BY handle. Those operators use the locale-aware ordering. If you need both, you have two options:
- Keep two indexes on the column, one with each class.
- Create one index with
COLLATE "C", for exampleCREATE INDEX ON accounts (handle COLLATE "C"). This serves prefixLIKEand byte-order comparisons, but queries must use the same collation, or the planner will not match the index.
If the whole database uses the C collation, the default class already handles prefix LIKE and you do not need text_pattern_ops.
Three limits apply:
- The pattern must be left-anchored.
LIKE '%1234'cannot use a B-tree. ILIKEand case-insensitive prefix searches need an expression index such as(lower(handle) text_pattern_ops). The query must then uselower(handle) LIKE 'user12%'.- For
varcharcolumns, usevarchar_pattern_ops. It behaves the same way.
Case 2: trigram matching with pg_trgm
Substring searches such as ILIKE '%smith%' have no fixed starting point, so no B-tree can help. The pg_trgm extension breaks text into trigrams, which are sequences of three characters. It provides operator classes that index those trigrams.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE people (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE INDEX people_name_trgm_idx
ON people USING gin (name gin_trgm_ops);
SELECT id FROM people WHERE name ILIKE '%smith%';gin_trgm_ops serves LIKE, ILIKE, ~, ~*, =, and the similarity operator %. The gist_trgm_ops class serves the same operators and also supports <-> distance ordering, so it can answer "the five names most similar to this one" directly. GIN is usually faster to search and slower to update. GiST is the reverse.
Trigram indexes have an edge case. A search term shorter than three characters yields no usable trigrams, so the planner falls back to a full scan of the index or table. Keep that in mind for search boxes that fire on one or two typed letters.
You cannot create a plain GIN index on text without naming a class. There is no default GIN class for text, and PostgreSQL reports data type text has no default operator class for access method "gin". The fix is to name a class such as gin_trgm_ops, or to wrap the column in an expression like to_tsvector('english', body) for full-text search.
Case 3: two classes for jsonb in GIN
GIN on jsonb has two built-in classes with different trade-offs.
| Class | Default | Operators served | Index size | Column |
|---|---|---|---|---|
| `jsonb_ops` | Yes | `@>`, `?`, `?\ | `, `?&`, `@?`, `@@` | Larger |
| `jsonb_path_ops` | No | `@>`, `@?`, `@@` | Smaller and faster for containment |
jsonb_ops indexes every key and every value separately, so it can answer "does this key exist" with ?. jsonb_path_ops indexes a hash of each path from the root to a value. That makes containment lookups more selective, but it cannot answer key-existence questions.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
CREATE INDEX events_payload_path_idx
ON events USING gin (payload jsonb_path_ops);
-- Can use the index
SELECT id FROM events WHERE payload @> '{"type": "login"}';
-- Cannot use the index: ? is not in jsonb_path_ops
SELECT id FROM events WHERE payload ? 'type';If your queries use only @>, choose jsonb_path_ops. If you also test for key existence, keep the default.
Other classes you will meet
Some classes are selected by workload and not by operator.
| Method | Class | When to choose it |
|---|---|---|
| BRIN | `minmax_ops` (default per type) | Values correlate with physical row order |
| BRIN | `*_minmax_multi_ops` (PostgreSQL 14+) | Mostly ordered data with outliers |
| BRIN | `*_bloom_ops` (PostgreSQL 14+) | Equality lookups on unordered columns |
| GiST | `range_ops`, `point_ops`, `box_ops` | Ranges and geometry, usually the default |
| GIN | `array_ops` | Array containment with `@>` and `&&` |
Some classes accept parameters. For example, gist_trgm_ops (siglen = 32) sets the signature size, and BRIN bloom classes accept n_distinct_per_range and false_positive_rate. These parameters trade index size against precision.
Common errors
- Index exists, but the plan shows a sequential scan. Compare the operator in your
WHEREclause with the class's operator list. For example,ILIKEagainst atext_pattern_opsindex never matches. - Wrong class for the workload. A
text_pattern_opsindex does not speed upORDER BY handle, and ajsonb_path_opsindex does not speed up?. - Missing extension.
gin_trgm_opsfails withoperator class "gin_trgm_ops" does not exist for access method "gin"until you runCREATE EXTENSION pg_trgm. Equality on a scalar column in GIN or GiST needsbtree_ginorbtree_gist. - Expression mismatch. An index on
lower(handle)only helps queries that writelower(handle)the same way. - Duplicate indexes. It is legal to have two indexes on one column with different classes. Check
pg_indexes.indexdefbefore adding a second one, so you do not pay write cost for an index that already covers the query.
Verifying your choice
After creating an index with a non-default class, check three things:
- Run
EXPLAINwith a representative query and confirm the index appears in the plan. - Run the same query with the operator changed, for example
LIKEagainstILIKE, to see which forms the index serves. - Check
pg_stat_user_indexes.idx_scanafter real traffic, to confirm the index is used in production and not only in your test.
For a quick experiment on a small table, SET enable_seqscan = off; in your session forces the planner to use an index if any usable one exists. If the plan still shows a sequential scan, the operator and class do not match. Reset the setting afterwards with RESET enable_seqscan;, because it only helps diagnose and is not a fix.
Exercise
A table accounts(handle text) lives in a database with the en_US.UTF-8 collation. You created CREATE INDEX ON accounts (handle);. The query SELECT id FROM accounts WHERE handle LIKE 'user12%'; still does a sequential scan. What index would fix it, and what ordinary query would that new index not help?
Show answer
Create CREATE INDEX ON accounts (handle text_pattern_ops);. The default text_ops class orders by locale, so a prefix LIKE cannot become a range scan. The new index does not help ORDER BY handle or comparisons like handle < 'm', because those use the locale-aware operators. It also does not help ILIKE.
Exercise
Your events.payload column has a GIN index created with jsonb_path_ops. Which of these queries can use it: payload @> '{"type": "login"}', or payload ? 'type'? What would you change if you needed both?
Show answer
Only payload @> '{"type": "login"}' can use it, because @> is in the jsonb_path_ops operator list and ? is not. To serve both, use the default jsonb_ops class, which supports @> and ?, at the cost of a larger index. Alternatively, keep jsonb_path_ops and add an expression index for the specific key you test.