Sub topic 4
Multicolumn, Partial, Expression, and Covering B-tree Indexes
This chapter assumes you know basic SQL, including SELECT, WHERE, ORDER BY, and JOIN. You should also know how to create PostgreSQL tables and use common types such as integer, text, and timestamptz.
A B-tree index does more than speed up a simple equality lookup. You can shape one for a common query pattern by combining columns, indexing only selected rows, indexing a calculated value, or storing extra columns in the index.
Multicolumn B-tree indexes
A multicolumn index stores keys in the order you specify:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);This index is useful for a query that selects one customer’s newest orders:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The first index column, customer_id, narrows the search. The second column, created_at, provides the ordering within that customer’s rows. PostgreSQL may be able to find the first ten matching entries without scanning all of the customer’s orders and sorting them.
Column order matters. An index on (customer_id, created_at) is usually useful for:
WHERE customer_id = 42WHERE customer_id = 42 ORDER BY created_atWHERE customer_id = 42 AND created_at >= ...
It is usually less useful for a query that filters only on created_at. This behavior is often called the leftmost-prefix rule: the leading index columns should match the important equality conditions in the query.
A multicolumn index is not automatically better than several single-column indexes. It is designed for particular query shapes. Use EXPLAIN to check the actual plan.
Partial indexes
A partial index contains only rows that satisfy a predicate. This can make the index smaller and cheaper to maintain:
CREATE INDEX orders_open_created_idx
ON orders (created_at)
WHERE status = 'open';This index can help the following query:
SELECT id, customer_id, total
FROM orders
WHERE status = 'open'
ORDER BY created_at DESC
LIMIT 50;PostgreSQL can use the index because the query’s condition implies the index predicate. The query must be specific enough for PostgreSQL to establish that relationship. A parameterized condition such as status = $1 may not prove that the value will always be 'open' when the plan is created.
Partial indexes are useful for hot subsets, such as:
- Open support tickets
- Unprocessed jobs
- Active accounts
- Recent or non-archived records
They do not enforce uniqueness across the entire table. If you need one active row per user, a partial unique index can enforce that rule only for rows matching its predicate:
CREATE UNIQUE INDEX one_active_profile_idx
ON profiles (user_id)
WHERE deleted_at IS NULL;Expression indexes
An expression index stores the result of a calculation instead of storing a column value directly:
CREATE INDEX users_lower_email_idx
ON users (lower(email));It supports a query that uses the same expression:
SELECT id
FROM users
WHERE lower(email) = '[email protected]';Without this index, PostgreSQL may need to apply lower to many table rows before it can compare the results. The expression in the query should match the indexed expression. An index on email does not generally replace an index on lower(email).
The expression must use functions whose results are stable enough for indexing. PostgreSQL commonly requires functions used in index expressions to be immutable, meaning their result depends only on their input and not on changing database or session state.
Covering indexes with `INCLUDE`
An index can store extra, non-key columns with INCLUDE:
CREATE INDEX orders_customer_incl_idx
ON orders (customer_id) INCLUDE (total);customer_id is the search key. total is payload stored in the index but is not part of the B-tree ordering. This can support an index-only scan for:
SELECT total
FROM orders
WHERE customer_id = 42;An index-only scan can return selected columns from the index without fetching the table row. However, PostgreSQL still checks whether the table page is visible to the transaction. The visibility map records pages known to contain no recently changed rows. If that information is incomplete, PostgreSQL must visit the table even though the index contains the requested columns.
INCLUDE increases index size. Include only columns that remove meaningful table lookups, and remember that included columns cannot help with filtering or ordering.
Exercise
You frequently run SELECT total FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10. Which index is a strong starting point, and why?
Show answer
CREATE INDEX ON orders (customer_id, created_at DESC) INCLUDE (total); uses customer_id to find the customer’s rows, supplies the requested order, and stores total so an index-only scan may be possible.