Skip to content

Indexes

B-tree, partial, covering, and expression indexes: when to add them, how to structure them, and when to leave them out.

An index is a separate data structure that lets the database answer a query without scanning every row. The trade-off is always the same: faster reads, slower writes, more storage. Most applications are read-heavy, so indexes are almost always worth it, but only on columns the database actually uses to filter, join, or sort.

B-tree

The default index type. A B-tree maintains sorted key-value pairs and supports equality (=), range (<, >, BETWEEN), and prefix (LIKE 'foo%') lookups, as well as ordered scans. Use it for everything unless you have a specific reason not to.

CREATE INDEX idx_orders_user_id ON orders (user_id);
CREATE INDEX idx_orders_user_id ON orders (user_id);

The syntax is identical. The internal structure differs slightly but the behavior and query patterns are the same.

Composite indexes

A composite index covers multiple columns. The column order determines which queries can use it: the database can use the index for any query that filters on a left prefix of the indexed columns.

CREATE INDEX idx_orders_user_created ON orders (user_id, created_at);

This index serves:

  • WHERE user_id = $1
  • WHERE user_id = $1 AND created_at > $2
  • ORDER BY user_id, created_at

But not:

  • WHERE created_at > $1 alone: created_at is not the leftmost column

Put equality columns first, range columns last. A query with WHERE user_id = $1 AND created_at > $2 fixes user_id to one value and ranges over created_at, which is the correct order. Reversing them (created_at, user_id) means the index can only use created_at for the range and must then scan all matching rows to filter by user_id.

Partial indexes

A partial index only covers rows that satisfy a WHERE condition. The index is smaller, cheaper to maintain, and often faster to scan than a full index on the same column.

-- Only index unprocessed jobs, the common query target
CREATE INDEX idx_jobs_pending ON jobs (created_at) WHERE status = 'pending';

-- Only index live rows on a soft-delete table
CREATE INDEX idx_users_email_live ON users (email) WHERE deleted_at IS NULL;

Partial indexes shine when queries consistently filter on a low-cardinality column (status, deleted_at IS NULL) and then range or sort on another. The index stays small regardless of how many rows exist outside the condition.

The WHERE syntax is identical in Postgres and SQLite (3.8.9+).

Covering indexes

A covering index contains all the columns a query needs, so the database can answer it entirely from the index without touching the table. This eliminates the heap lookup, often the most expensive part of an index scan on a large table.

Use INCLUDE to add non-key columns that are needed by the query but should not be part of the sort key:

CREATE INDEX idx_users_email_cover ON users (email) INCLUDE (id, display_name);

The query SELECT id, display_name FROM users WHERE email = $1 is now answered entirely from the index with no table row read.

INCLUDE columns are stored in the leaf pages only and do not affect the sort order or key comparisons.

SQLite has no INCLUDE clause. A covering index is a regular index that happens to contain all the columns the query needs:

CREATE INDEX idx_users_email_cover ON users (email, id, display_name);

SQLite’s query planner will recognize that all columns are available in the index and skip the table lookup automatically.

Expression indexes

An index can be built on the result of an expression rather than a raw column value. The query must use the same expression for the planner to recognize it.

-- Case-insensitive email lookup
CREATE INDEX idx_users_email_lower ON users (lower(email));

-- Index on a jsonb field
CREATE INDEX idx_events_type ON events ((payload->>'type'));

-- Index on a date truncation
CREATE INDEX idx_orders_day ON orders (date_trunc('day', created_at));

Query must use the same expression:

SELECT * FROM users WHERE lower(email) = 'alice@example.com';
-- Case-insensitive email lookup
CREATE INDEX idx_users_email_lower ON users (lower(email));

Query must use the same expression:

SELECT * FROM users WHERE lower(email) = 'alice@example.com';

SQLite supports expression indexes (3.9+) but the range of supported functions is narrower than Postgres; complex or user-defined expressions may not be indexable.

Postgres-specific types

GIN (Generalized Inverted Index) indexes the individual elements of a composite value. Use it when a column contains multiple values that are queried independently: arrays, jsonb objects, and tsvector full-text search.

-- jsonb key existence and containment
CREATE INDEX idx_events_payload ON events USING gin (payload);

SELECT * FROM events WHERE payload @> '{"type": "login"}';
SELECT * FROM events WHERE payload ? 'user_id';

-- Array containment
CREATE INDEX idx_posts_tags ON posts USING gin (tags);

SELECT * FROM posts WHERE tags @> ARRAY['postgres', 'indexes'];

For querying a single jsonb key repeatedly, index that key alone to keep the index small:

CREATE INDEX idx_events_type ON events ((payload->>'type'));

GiST: ranges, geometry, nearest-neighbor

GiST (Generalized Search Tree) supports overlap, containment, and nearest-neighbor queries on range types and geometric data.

-- Range overlap: find bookings that overlap a given window
CREATE INDEX idx_bookings_period ON bookings USING gist (period);

SELECT * FROM bookings
WHERE period && tstzrange('2024-01-01', '2024-01-31');

BRIN: large append-only tables

BRIN (Block Range Index) stores the min/max value per range of physical pages. It is extremely small (a few kilobytes even on billion-row tables) and works well when the physical order of rows correlates with the query range (e.g. an append_only_events table where created_at increases monotonically).

CREATE INDEX idx_events_created_brin ON events USING brin (created_at);

When not to index

More indexes are not always better. Each index adds overhead on every INSERT, UPDATE, and DELETE, consumes storage, and can confuse the query planner when too many options exist.

Skip the index when:

  • The table is small. A sequential scan of a few thousand rows is fast; the planner will ignore the index anyway.
  • The column has very low selectivity. An index on a boolean or a three-value status column touches a large fraction of the table; a partial index (above) is usually the right answer instead.
  • The column is write-heavy and rarely filtered. Indexing updated_at on a high-update table pays write overhead on every row change for a query pattern that may rarely occur.
  • You already have a composite index with the column as a left prefix. A separate single-column index is redundant.

Verifying index usage

Always check that the planner actually uses the index you created.

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM users WHERE email = 'alice@example.com';

Look for Index Scan or Index Only Scan in the output. Seq Scan means the planner chose not to use the index. The table may be too small, the statistics stale (ANALYZE), or the query written in a way that prevents index use (e.g. wrapping the column in a function without a matching expression index).

EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = 'alice@example.com';

Look for SEARCH users USING INDEX in the output. SCAN users means a full table scan; the index is not being used.

Type to search…

↑↓ navigate↵ selectEsc close