Composite, partial, expression, GIN & BRIN indexes
Choose an index type and column order for a real query workload.
By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.
In short
Beyond plain B-trees, Postgres offers composite, partial and expression indexes to match specific queries, and other index types: GIN for JSONB, arrays and full-text search, and BRIN for huge, naturally ordered tables.
Explained simply
A plain index on one column is only the start. Real queries filter on several columns, look for words inside text, search inside JSON documents, or scan billions of log rows by date. Postgres has a special kind of index for each of these.
A composite index covers several columns at once, like a phone book sorted by last name and then first name. A partial index covers only some rows, for example only orders that are still pending. An expression index stores the result of a calculation, such as lower(email).
GIN is an index for values that contain many parts: the words in a document, the keys in a JSON object, the items in an array. It works like the index at the back of a book, listing each word and every page it appears on.
BRIN is a tiny index for huge tables where rows are stored roughly in order, like log events arriving over time. It only remembers the smallest and largest value in each block of pages, so it can skip blocks that cannot match.
Press Play on a diagram to walk through it one step at a time.
- Default, sorted keys
- =, <, >, BETWEEN, ORDER BY
- Medium size
- Most columns
- Inverted index of elements
- JSONB @>, arrays, full text
- Larger, slower to update
- Many values per row
- Min/max per block range
- Tiny index
- Needs physically ordered data
- Huge append-only time series
- =, <, >, ORDER BY
- B-tree
- Composite if several columns
- Only a small subset of rows
- Partial index with WHERE
- Function of a column
- Expression index, e.g. lower(email)
- Contains: JSONB, arrays, words
- GIN
- pg_trgm for LIKE '%x%'
- Range on a huge append-only table
- BRIN on the time column
- Overlaps, geometry, nearest
- GiST (ranges, PostGIS)
In depth
Choosing column order in a composite index
A composite B-tree is sorted by its first column, then the second, and so on. The rule that works almost every time: columns compared with = go first, then the one column used for a range (<, >, BETWEEN) or for ORDER BY. After a range column, later columns can no longer narrow the search; they can only be checked one by one.
Example: WHERE tenant_id = ? AND status = ? AND created_at > ? ORDER BY created_at. The index (tenant_id, status, created_at) jumps straight to the right tenant and status and reads created_at in order. The index (created_at, tenant_id, status) would have to scan every recent row of every tenant.
Among equality columns, order matters less for that query, but it decides which other queries can share the index. An index on (tenant_id, status) also serves WHERE tenant_id = ? alone, so the column used on its own most often should lead.
- 1List equality filters
tenant_id = ?, status = ?
- 2Add one range or sort column
created_at > ?, ORDER BY created_at
- 3Optional INCLUDE
Extra selected columns for index-only scans
- 4Check reuse
Can other queries use its leading columns?
- 5Verify
EXPLAIN shows no Sort and few rows removed
Partial and expression indexes
A partial index has a WHERE clause: CREATE INDEX ON jobs (run_at) WHERE status = 'pending'. If 99 percent of jobs are done, this index is a tiny fraction of the full one, stays in memory, and is cheap to maintain, because rows outside the condition never touch it. The planner uses it only when it can prove the query's WHERE implies the index's WHERE, so write the same condition with a literal value. A prepared statement with status = $1 may not match. A partial unique index also enforces rules on some rows only, such as one active subscription per user.
An expression index stores a computed value: ON users (lower(email)), ON events ((payload->>'type')), ON products (upper(sku)). The query must use exactly the same expression. Functions in it must be IMMUTABLE (same input, same output), so date() on a timestamptz is not allowed because the answer depends on the time zone. Run ANALYZE after creating one so the planner gets statistics on the expression.
- Partial: query condition must match the index WHERE
- Partial unique: rules that apply to some rows
- Expression: query must repeat the exact expression
- Only IMMUTABLE functions are allowed
GIN for JSONB, arrays and full-text search
GIN (Generalized Inverted Index) splits each value into elements and stores, for every element, the list of rows that contain it. That makes "which rows contain X?" fast.
JSONB: the default jsonb_ops operator class supports @> (contains), ? (has key), ?| and ?& as well as jsonpath operators @? and @@. jsonb_path_ops supports only @> and the jsonpath operators, but is smaller and usually faster for containment. Neither helps payload->>'type' = 'click'; use attrs @> '{"type":"click"}' or an expression B-tree instead.
Arrays: && (overlap), @> and <@ (contains, contained by).
Full text: store a tsvector (for example a generated column from to_tsvector('english', title || ' ' || body)), index it with GIN and query with @@ to_tsquery(...). For LIKE '%abc%' or fuzzy matches, the pg_trgm extension adds gin_trgm_ops.
The cost is write speed: one new row can add many GIN entries. GIN buffers them in a pending list (fastupdate) that vacuum later merges.
- jsonb_ops: @>, ?, ?|, ?&, @?, @@
- jsonb_path_ops: @>, @?, @@ only, smaller
- Full text: GIN on a tsvector, query with @@
- pg_trgm + gin_trgm_ops for LIKE '%x%'
BRIN for huge, naturally ordered tables
BRIN (Block Range Index) divides the table into ranges of pages, 128 pages by default (pages_per_range), and stores one small summary per range: the minimum and maximum value. For a WHERE created_at between two dates, Postgres reads the summaries, skips every range that cannot match, and scans only the rest, rechecking each row.
Because it stores so little, a BRIN index on a billion-row table can be a few megabytes where a B-tree would be tens of gigabytes. It only works if values follow the physical order of rows, which is true for append-only data like logs, events or sensor readings. Check pg_stats.correlation for the column: values near 1 or -1 are good; near 0 means every range covers everything and BRIN skips nothing.
New page ranges are summarised by vacuum, or immediately if you create the index WITH (autosummarize = on). PostgreSQL 14 added minmax_multi operator classes that cope better with a few out-of-order rows.
- Step 1Read range summaries
Min and max created_at per 128 pages
- Step 2Skip ranges
Max before the day or min after it
- Step 3Bitmap of candidate pages
Only ranges that might match
- Step 4Scan those pages
Recheck each row against the condition
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Order columns in composite indexes~45m
- 2Create partial and expression indexes~45m
- 3Use GIN for JSONB and full text~45m
- 4Use BRIN for large time series~45m
Key points
- Composite index column order: equality columns first, then range or sort columns.
- Partial index: WHERE status = 'pending' indexes only the rows you query.
- Expression index: ON users (lower(email)) serves WHERE lower(email) = ...
- Hash indexes support only equality; B-tree is usually just as good.
Key terms
Tap a card to flip it. 0/5 known
Examples
-- WHERE customer_id = ? ORDER BY created_at DESC
CREATE INDEX ON orders (customer_id, created_at DESC);
-- only the small set of rows the job queue reads
CREATE INDEX ON jobs (run_at) WHERE status = 'pending';
-- case-insensitive email lookup
CREATE UNIQUE INDEX ON users (lower(email));
CREATE INDEX ON products USING gin (attrs);
CREATE INDEX ON events USING brin (created_at);Searching product attributes stored as JSONB
products.attrs holds documents like {"color": "red", "size": "M"}. Shoppers filter by any combination of attributes. Step 1: create a GIN index with jsonb_path_ops, since only containment is needed. Step 2: write filters with @>, which the index supports. Step 3: confirm with EXPLAIN that you get a Bitmap Index Scan on the GIN index. Note that attrs->>'color' = 'red' would not use this index.
CREATE INDEX products_attrs_gin
ON products USING gin (attrs jsonb_path_ops);
EXPLAIN ANALYZE
SELECT id, name FROM products
WHERE attrs @> '{"color": "red", "size": "M"}';
-- Bitmap Heap Scan on products
-- -> Bitmap Index Scan on products_attrs_ginFull-text search on articles
Users search blog articles by words. LIKE '%index%' is slow and finds 'reindexing' too. Step 1: add a stored generated column holding the tsvector, so it stays in sync automatically. Step 2: index it with GIN. Step 3: query with websearch_to_tsquery, which understands input like "postgres index -mysql", and rank the matches with ts_rank.
ALTER TABLE articles ADD COLUMN search tsvector
GENERATED ALWAYS AS (
to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, ''))
) STORED;
CREATE INDEX articles_search_gin ON articles USING gin (search);
SELECT id, title, ts_rank(search, q) AS rank
FROM articles, websearch_to_tsquery('english', 'postgres index -mysql') AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 10;Quick reference
- Composite order: equality columns, then one range or sort column, then INCLUDE extras
- CREATE INDEX ON jobs (run_at) WHERE status = 'pending'; partial index
- CREATE INDEX ON events ((payload->>'type')); expression needs double brackets
- USING gin (doc jsonb_path_ops) is smaller and serves @> containment
- CREATE EXTENSION pg_trgm; USING gin (name gin_trgm_ops) speeds LIKE '%x%'
- USING brin (created_at) for huge append-only tables; check pg_stats.correlation
- USING gist for ranges, exclusion constraints and PostGIS geometry
Common mistakes
- Composite index with the range column first, so the equality filter cannot narrow it.
- Partial index whose WHERE does not match the query's condition exactly.
- BRIN on randomly ordered data, where every range overlaps and nothing is skipped.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create an index so WHERE lower(email) = lower($1) on users can use an index, and verify it.
- Exercise 2medium
A worker polls SELECT * FROM jobs WHERE status = 'pending' ORDER BY run_at LIMIT 10. 99 percent of jobs are done. Create the smallest index that serves this query.
- Exercise 3hard
Make WHERE name ILIKE '%phone%' fast on a 5 million row products table, and compare the plan before and after.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I create one index per column or one composite index?
- For a query that filters on several columns together, one well-ordered composite index is usually better. Postgres can combine single-column indexes with a bitmap AND, but that is slower and cannot provide sort order.
- When should I use a hash index?
- Rarely. Hash indexes support only equality and are crash-safe since PostgreSQL 10, but a B-tree does equality almost as well and also supports ranges, sorting and uniqueness.
- What is the difference between GIN and GiST?
- GIN is an inverted index, best for exact contains queries on JSONB, arrays and full text. GiST is a balanced tree of bounding shapes, used for ranges, overlap and exclusion constraints, geometry and nearest-neighbour search.