Skip to content

Indexing: B-tree, Hash, GIN & GiST ​

"Once an index is created, no further intervention is required: the system will update the index when the table is modified, and it will use the index in queries when it thinks doing so would be more efficient than a sequential table scan." — PostgreSQL documentation, 11.1. Introduction (Indexes)

Summary: An index is a second, sorted (or hashed, or inverted) copy of some columns with pointers back to the rows; it makes some reads cheap and every write more expensive. Focus: Scan types, composite column order, covering and partial and expression indexes, every PostgreSQL index type with its operator classes, MySQL InnoDB, SQL Server and MongoDB differences, and the operations side (CONCURRENTLY, bloat, unused and hypothetical indexes). Learning goal: Design the smallest set of indexes that serves your real queries, prove it with EXPLAIN (ANALYZE, BUFFERS), build it on a live table without an outage, and remove what does not earn its write cost.

This page is the complete reference for index design. It covers what an index does to a query (with a before/after lab), every scan type you will see in a plan, the B-tree rules that decide whether a composite index is usable (left prefix, equality-then-range, skip scan), covering indexes and the visibility map, partial, expression and unique indexes, NULL handling, all PostgreSQL access methods (B-tree, Hash, GiST, SP-GiST, GIN, BRIN and the bloom extension) with operator classes and collations, the write cost, and the day-two operations: CREATE INDEX CONCURRENTLY, INVALID indexes, bloat and REINDEX CONCURRENTLY, unused and duplicate indexes, and hypothetical indexes with hypopg. Next to PostgreSQL it names what MySQL InnoDB, SQL Server, Oracle, SQLite, MongoDB, CockroachDB and Redis do. Neighbours own the rest: reading plans, statistics and join algorithms are in Query Planning; pages, heap tuples and the visibility map's storage are in Database Internals; B-tree vs B+tree node layout and page splits are in B-Tree vs B+Tree; Bloom filters as a data structure are in Bloom Filters; text search is in Full-Text Search; and index strategy for huge tables is in Billion-Row Tables.

Page map ​

If you are looking forGo to
Every concept in one tableEverything in one minute
Why indexes exist and what they costWhy indexes exist
What an index does to one query, measuredBefore and after: one query
Seq Scan, Index Scan, Index Only Scan, Bitmap scansScan types
Column order, left prefix, equality-then-range, skip scanComposite indexes
INCLUDE, covering, visibility map, Heap FetchesCovering indexes and index-only scans
WHERE in the index, lower(email), UNIQUE, NULLsPartial, Expression, Unique, NULLs
B-tree, Hash, GiST, SP-GiST, GIN, BRIN, bloomIndex types
text_pattern_ops, jsonb_path_ops, collationsOperator classes and collations
InnoDB clustered PK, ICP, invisible, descending, functionalMySQL InnoDB
SQL Server, Oracle, SQLite, MongoDB, CockroachDB, RedisOther products
Write amplification, HOT, fillfactor, bloatMechanics
Building, rebuilding, finding unused and missing indexesSolving the classic problems
Which index for which queryChoosing an index
Replicas, sharding, microservicesIn architecture
Reproduce everythingLab
Test yourself, wrong beliefs, termsSelf-check, Misconceptions, Cheat sheet, Glossary

Everything in one minute ​

Scan types (PostgreSQL plan node names).

Plan nodeIn plain wordsWhen the planner picks itCost shape
Seq ScanRead every page of the tableNo usable index, or most rows matchSequential I/O, proportional to table size
Index ScanWalk the index, fetch each matching row from the heapFew rows match, or rows needed in index orderOne random heap read per match
Index Only ScanAnswer from the index aloneAll needed columns in the index and pages all-visibleIndex pages + visibility map; heap only for Heap Fetches
Bitmap Index Scan + Bitmap Heap ScanCollect matching row locations, then read each heap page once in orderMedium selectivity, or combining indexes with BitmapAnd/BitmapOrFewer random reads; loses index order

Index design in one table.

ConceptRule of thumbExample
Composite orderEquality columns first, then one range or sort column(tenant_id, created_at) for tenant_id = ? AND created_at >= ?
Left prefixOnly leading columns narrow the scan(a, b) serves a and a, b, not b alone (except skip scan)
Covering / INCLUDEAdd the selected columns as payload to get an Index Only ScanON orders (tenant_id) INCLUDE (total_cents)
Partial indexIndex only the rows queries ask forON orders (created_at) WHERE status = 'pending'
Expression indexIndex the expression the query usesON users (lower(email))
Unique indexEnforces a rule; also an indexUNIQUE (tenant_id, external_ref)
Write costEvery index is updated on every insert and most updates8 indexes = 9 structures to change per INSERT

Which type for which operator, and when to use it (PostgreSQL).

TypeOperators / useOne-line reason
B-tree= < <= > >= BETWEEN IN IS NULL, anchored LIKE 'x%', ORDER BYSorted; the default and the only one that can be UNIQUE
Hash= onlyStores a 32-bit hash; smaller for long keys
GIN@>, ?, &&, @@ on jsonb, arrays, tsvector; trigram LIKE '%x%'Inverted: one entry per element
GiSTRanges, geometry, <-> nearest neighbour, exclusion constraintsGeneralized balanced tree for overlap/containment
SP-GiSTPoints, IP ranges, text prefixesSpace-partitioned, unbalanced (quad-tree, k-d tree, trie)
BRINRange filters on huge, naturally ordered tablesMin/max per block range; tiny
bloom (extension)= on any combination of many columnsLossy signature per row

Why indexes exist ​

Without an index, the only way to find rows matching a condition is to read the whole table. That is fine at ten thousand rows and fatal at a hundred million. An index trades space and write work for read speed: it keeps a structure ordered (or hashed, or inverted) by some key so that the database can jump to matching entries in a few page reads. The PostgreSQL manual puts the bargain plainly: with an index on the searched column the system "might only have to walk a few levels deep into a search tree" instead of scanning "the entire test1 table, row by row", and "After an index is created, the system has to keep it synchronized with the table. This adds overhead to data manipulation operations."

Fewer indexesMore indexes
Fast inserts and updates, more HOT updates in PostgreSQLEach write updates every index; HOT updates blocked if an indexed column changes
Smaller database, smaller backups, less cache pressureIndexes compete with table pages for shared_buffers / InnoDB buffer pool
Some queries scan the tableMore queries are cheap reads
Simpler planner choicesMore plans to consider; risk of a worse index being picked
Less vacuum and bloat workMore bloat to watch, more REINDEX

The analogy we reuse on this page: a library card catalogue. The books (the heap) stand on shelves in the order they arrived. A catalogue drawer sorted by author (a B-tree) lets you find "Tolstoy" quickly, then walk to the shelf for each card (heap fetch). A drawer sorted by author then title is a composite index: useless for "all books titled War" unless you open every author's section (skip scan). If the card itself carries the year of publication, you can answer "which years did Tolstoy publish?" without walking to the shelves (index-only scan), as long as the librarian's list says no shelf has books in transit (visibility map). A drawer just for books on loan is a partial index. Every new book means filing a card in every drawer: that is write amplification.

Three common misunderstandings, up front ​

  1. "Index every column in a WHERE clause." Each index costs every write and may never be chosen; a composite index in the right order usually beats three single-column ones, and a low-cardinality column alone is rarely worth an index.
  2. "If an index exists, the database uses it." The planner estimates costs from statistics: if a condition matches a large fraction of the table, a Seq Scan is cheaper than thousands of random heap reads, and it is right to ignore the index.
  3. "An index on (a, b) also helps WHERE b = ?." B-trees are sorted by a first; b alone is scattered over the whole index. PostgreSQL 18's skip scan and MySQL's Skip Scan help only when a has few distinct values.

Where it comes from ​

The B-tree, introduced by Rudolf Bayer and Edward McCreight, became the default index in essentially every relational database. Markus Winand's Use The Index, Luke explains why it stays fast as data grows: "That is primarily because of the tree balance, which allows accessing all elements with the same number of steps, and secondly because of the logarithmic growth of the tree depth." A PostgreSQL B-tree node is an 8 kB page holding hundreds of keys, so even a table of hundreds of millions of rows has a tree only a few levels deep (the fan-out figure is our arithmetic from the page size, not a quote). PostgreSQL then grew a family of access methods: GiST and GIN as frameworks for non-scalar data, SP-GiST for space partitioning, BRIN for very large tables, Hash (crash-safe since it became WAL-logged), and the bloom contrib module. The manual's own list: "PostgreSQL provides several index types: B-tree, Hash, GiST, SP-GiST, GIN, BRIN, and the extension bloom." PostgreSQL 18's release notes add one more capability to the B-tree: "Allow skip scans of btree indexes".

Before and after: one query ​

Index (B-tree, sorted by email)Table (heap, insertion order)root page< g | < p | restinternal: a..finternal: p..zleaf pageann@ → (0,2)bob@ → (2,1)cat@ → (1,3)leaf pagedan@ → (0,1)eve@ → (2,3)fay@ → (1,1)leaf pagepam@ → (1,2)sam@ → (0,3)zoe@ → (2,2)leaves are linked: a range scan walks right without going back upheap page 0 (all-visible)1: dan, 2: ann, 3: samTID (0,2) = page 0, item 2heap page 1 (recent writes)1: fay, 2: pam, 3: catnot all-visible: must be readheap page 2 (all-visible)1: bob, 2: zoe, 3: evevisibility map (2 bits per page)p0 = 1, p1 = 0, p2 = 1Index Scan: leaf → TID → heap page, for every match (random I/O)Index Only Scan: leaf → visibility map; heap only where bit = 0 (Heap Fetches)Bitmap scan: collect TIDs, sort by page, read each heap page onceInnoDB differs: secondary leaf stores the primary key, then a second B-tree lookup

The picture: the index is sorted by key and each leaf entry carries a TID (page, item) into the heap, which is in insertion order. An Index Scan follows a TID per match; an Index Only Scan asks the visibility map first; a bitmap scan collects TIDs and reads each heap page once. InnoDB differs at the last step: its secondary index stores the primary key, and the row is found by a second B-tree lookup in the clustered index.

A minimal before/after, in the style of the reference course: two million rows, one query, measured with EXPLAIN (ANALYZE, BUFFERS) (ANALYZE runs the query; BUFFERS shows how many 8 kB pages were hit in cache or read). Full setup is in the Lab; the plan shapes below are what PostgreSQL 18 prints, and we do not quote timings because they depend on the machine.

sql
CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id   int         NOT NULL,
  status      text        NOT NULL,
  total_cents int         NOT NULL,
  created_at  timestamptz NOT NULL,
  email       text        NOT NULL
);
INSERT INTO orders (tenant_id, status, total_cents, created_at, email)
SELECT 1 + (g % 1000),
       CASE WHEN g % 100 = 0 THEN 'pending' ELSE 'paid' END,
       (random() * 100000)::int,
       now() - (g || ' seconds')::interval,
       'user' || g || '@example.com'
FROM generate_series(1, 2000000) AS g;
ANALYZE orders;

-- BEFORE
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents FROM orders WHERE tenant_id = 42 AND created_at >= now() - interval '7 days';
--  Seq Scan on orders  (... rows=... loops=1)        <- reads every page
--    Filter: ((tenant_id = 42) AND (created_at >= ...))
--    Rows Removed by Filter: ~2000000                 <- almost all work wasted
--    Buffers: shared hit=... read=...                 <- roughly the table size in pages

CREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at);

-- AFTER
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents FROM orders WHERE tenant_id = 42 AND created_at >= now() - interval '7 days';
--  Index Scan using orders_tenant_created_idx on orders  (or Bitmap Heap Scan + Bitmap Index Scan)
--    Index Cond: ((tenant_id = 42) AND (created_at >= ...))   <- both columns narrow the scan
--    Buffers: shared hit=... read=...                 <- a handful of pages

How to read the difference: Filter + Rows Removed by Filter means rows were read and thrown away; Index Cond means the condition limited which part of the index was read. Buffers is the honest cost: pages touched. Reading plans in general belongs to Query Planning.

Scan types ​

Seq Scan Must-know ​

In plain words: read the table from the first page to the last and test every row.

Common misunderstanding: "A Seq Scan in a plan is always a bug." For a query returning a large fraction of a table, or a table of a few pages, it is the cheapest plan; sequential reads are much cheaper per page than random ones (PostgreSQL's planner defaults: seq_page_cost 1.0, random_page_cost 4.0).

Definition: a full scan of the heap (PostgreSQL) or of the clustered index (InnoDB type: ALL, SQL Server "Clustered Index Scan"/"Table Scan"), with the WHERE applied as a filter. PostgreSQL can split it across workers (Parallel Seq Scan).

text
1  planner: estimated rows matching = 40% of table
2  cost(Seq Scan)   = pages * seq_page_cost + rows * cpu_tuple_cost
3  cost(Index Scan) = matching rows * ~random_page_cost + index pages
4  Seq Scan wins -> plan: Seq Scan on orders, Filter: (status = 'paid')

Real scenarios: monthly reports over most rows; small lookup tables (countries, currencies); a filter on a column with two values; a query wrapped in a function the index cannot match (WHERE date(created_at) = ... against an index on created_at).

What changes it: a selective condition plus a matching index; correct statistics (ANALYZE); on SSDs a lower random_page_cost, since "Reducing this value relative to seq_page_cost will cause the system to prefer index scans". To test whether an index could be used, SET enable_seqscan = off in a session; the manual's advice for index experiments starts with "Always run ANALYZE first."

Index Scan Must-know ​

In plain words: walk down the tree to the first match, then read matches in key order, fetching each row from the table.

Common misunderstanding: "An Index Scan reads only the index." In PostgreSQL every index is secondary: "each row retrieval requires fetching data from both the index and the heap". For 100,000 matches that can be 100,000 random heap page reads.

Definition: B-tree (or other access method) descent using Index Cond; for each matching entry, fetch the heap tuple by TID and check visibility and any remaining Filter. Output is in index order, so it can satisfy ORDER BY ... LIMIT without a sort. MySQL shows type: ref/range/eq_ref; SQL Server shows "Index Seek" plus "Key Lookup" (or "RID Lookup" on a heap).

text
1  descend root -> internal -> leaf for (tenant_id=42, created_at >= X)
2  leaf entry (42, 2026-11-19 10:00) -> TID (8120, 3) -> read heap page 8120
3  next entry (42, 2026-11-19 10:01) -> TID (77, 12)  -> read heap page 77
4  ... until the key leaves the range; rows come out sorted by created_at

Real scenarios: WHERE id = ?; a user's last 20 orders (ORDER BY created_at DESC LIMIT 20); a foreign-key lookup during a join (nested loop inner side); WHERE email = ? at login.

Index Only Scan Must-know ​

In plain words: answer the query from the index alone, skipping the table, when every needed column is in the index and the table page is known to be visible to everyone.

Common misunderstanding: "If all columns are in the index, the heap is never touched." PostgreSQL indexes have no visibility information, so for each entry it checks the visibility map; only pages marked all-visible skip the heap. On a table that VACUUM has not processed recently, an "Index Only Scan" can read as many heap pages as an Index Scan. The plan tells you with Heap Fetches: N.

Definition: PostgreSQL requires two things: the index type supports it (B-tree always; GiST and SP-GiST for some operator classes; GIN and BRIN never), and the query references only columns stored in the index. Details and the INCLUDE clause are in Covering indexes.

text
1  leaf entry (tenant_id=42, total_cents=1999) -> TID (500, 4)
2  visibility map bit for heap page 500 = 1 (all-visible) -> return row, no heap read
3  next entry -> TID (9001, 2) -> bit = 0 (recently updated) -> read heap page 9001
4  EXPLAIN shows: Index Only Scan ... Heap Fetches: 1

Real scenarios: counting a tenant's orders (SELECT count(*) WHERE tenant_id = ?); dashboards over append-mostly tables; EXISTS checks; sums of a column carried in INCLUDE. MySQL InnoDB calls this a covering index and shows Using index in Extra.

Bitmap Index Scan and Bitmap Heap Scan Must-know ​

In plain words: first collect the addresses of all matching rows from one or more indexes, sort them by table page, then read each needed page once.

Common misunderstanding: "A bitmap scan is a degraded index scan." It is the plan of choice for medium selectivity (too many rows for one random read each, too few for a Seq Scan), and the only way PostgreSQL combines two indexes in one query.

Definition:

"To combine multiple indexes, the system scans each needed index and prepares a bitmap in memory giving the locations of table rows that are reported as matching that index's conditions." — PostgreSQL documentation, 11.5. Combining Multiple Indexes

The bitmaps are then combined (bitmap AND via BitmapAnd, bitmap OR via BitmapOr), and the Bitmap Heap Scan reads the heap in physical order. Consequences from the same page: "any ordering of the original indexes is lost, and so a separate sort step will be needed if the query has an ORDER BY clause." If the bitmap does not fit in work_mem it becomes lossy (whole pages instead of rows), and the plan shows Recheck Cond plus Heap Blocks: exact=... lossy=....

WHERE status = 'pending' AND country = 'DE' (two single-column indexes)Bitmap Index Scanon orders_status_idxBitmap Index Scanon orders_country_idxbitmap A (pages)1 0 1 1 0 0 1 0bitmap B (pages)0 0 1 1 1 0 0 0BitmapAnd0 0 1 1 0 0 0 0Bitmap Heap ScanRecheck Cond(if lossy)Heap pages, read in physical order, each at most oncep0p1p2 readp3 readp4p5p6p7• OR instead of AND → BitmapOr (union). MySQL calls this Index Merge: intersect / union / sort_union.• The bitmap is ordered by page, so index order is lost: ORDER BY needs a separate Sort.• If the bitmap outgrows work_mem it keeps whole pages (lossy) and every row is rechecked.• Chosen for medium selectivity: too many rows for an Index Scan, too few for a Seq Scan.
text
1  Bitmap Index Scan on orders_status_idx   (status = 'pending')  -> bitmap A
2  Bitmap Index Scan on orders_country_idx  (country = 'DE')      -> bitmap B
3  BitmapAnd(A, B)                                                 -> pages {2, 3}
4  Bitmap Heap Scan: read page 2, page 3; Recheck Cond on each row

Real scenarios: an admin search with optional filters on separate columns; WHERE a = 1 OR b = 2; IN lists with hundreds of values; GIN indexes (GIN always produces bitmap scans). MySQL's equivalent is Index Merge, shown as type: index_merge with Using intersect(...), Using union(...) or Using sort_union(...).

What each product does:

ProductName in the planNotes
PostgreSQLBitmap Index Scan, BitmapAnd, BitmapOr, Bitmap Heap ScanIn-memory bitmaps per query; lossy beyond work_mem
MySQL InnoDBindex_merge with intersect / union / sort_unionOften worse than one composite index; tune via optimizer_switch
SQL ServerIndex intersection (two seeks + hash/merge join)No persistent bitmap index
OracleBITMAP AND / BITMAP CONVERSION; real bitmap indexes exist"In a bitmap index, the database stores a bitmap for each index key." Suited to data warehouses, not OLTP
MongoDBAND_SORTED / AND_HASH index intersectionRarely chosen; a compound index ordered by the ESR guideline is the normal answer

Designing B-tree indexes ​

Composite indexes: column order, left prefix, equality-then-range Must-know ​

In plain words: a composite (multicolumn, concatenated) index is sorted like a phone book: by the first column, then by the second within equal first values, and so on. You can look up by surname, or surname plus first name, but not by first name alone.

Common misunderstanding: "Column order does not matter; the optimizer will figure it out." The order decides which queries can narrow the scan. (created_at, tenant_id) and (tenant_id, created_at) contain the same data and serve different queries.

Definition: the PostgreSQL rule for B-tree:

"The exact rule is that equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will always be used to limit the portion of the index that is scanned." — PostgreSQL documentation, 11.3. Multicolumn Indexes

Winand states the left-prefix consequence: "a database can use a concatenated index when searching with the leading (leftmost) columns." MySQL says the same for InnoDB: "MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index." So: put columns compared with = (or short IN lists) first, then at most one range or sort column. Columns after the first range column can still be checked inside the index, but they do not narrow the slice. The manual also warns that "indexes with more than three columns are unlikely to be helpful unless the usage of the table is extremely stylized."

INDEX ON orders (tenant_id, status, created_at): leaf entries in key ordertenant_id | status | created_at6 | paid | 2026-11-027 | paid | 2026-01-107 | paid | 2026-11-207 | paid | 2026-11-247 | pending | 2026-11-217 | refunded | 2026-03-058 | paid | 2026-11-229 | pending | 2026-11-23Which WHERE clauses read a contiguous slice?tenant_id = 7 AND status = 'paid'AND created_at >= '2026-11-01' → 2 rows, one slicetenant_id = 7 → one slice (left prefix)status / created_at then filter inside ittenant_id = 7 AND created_at >= X → slice by tenant,created_at checked per entry (status gap)created_at >= X alone → matches scattered everywhere:Seq Scan, or a skip scan when tenant_id has few valuesRules the picture shows1. Sorted by col1, then col2 within equal col1, then col3: like a phone book (surname, first name).2. Left prefix: (a), (a,b), (a,b,c) narrow the scan; (b) or (c) alone do not.3. Equality first, then ONE range: after the first range column, later columns only filter.4. ORDER BY created_at is free only after equality on every column before it.5. Skip scan (PostgreSQL 18+, MySQL Skip Scan) re-enters the index once per leading value.
text
INDEX (tenant_id, status, created_at)
1  WHERE tenant_id = 7 AND status = 'paid' AND created_at >= X   -> one slice, all three in Index Cond
2  WHERE tenant_id = 7 AND created_at >= X                       -> slice by tenant_id; created_at checked per entry
3  WHERE tenant_id = 7 ORDER BY status, created_at LIMIT 20      -> no Sort node, reads 20 entries
4  WHERE status = 'paid'                                          -> not a prefix: Seq Scan, or skip scan if tenant_id has few values
5  WHERE tenant_id = 7 AND created_at >= X ORDER BY created_at    -> status sits between: Sort needed (or reorder the index)

Real scenarios: multi-tenant SaaS (tenant_id first in almost every index); "my last N orders" ((user_id, created_at DESC)); a job queue ((queue, available_at) WHERE reserved_at IS NULL); audit log lookups by (entity_type, entity_id, created_at).

ORDER BY and sort direction. "Of the index types currently supported by PostgreSQL, only B-tree can produce sorted output". A B-tree can be read backwards, so (a, b) serves ORDER BY a, b and ORDER BY a DESC, b DESC, but not ORDER BY a ASC, b DESC; for that, declare (a ASC, b DESC). PostgreSQL also lets you place NULLs: CREATE INDEX ... (info NULLS FIRST). Older MySQL versions parsed and ignored DESC; the 8.4 manual says "DESC in an index definition is no longer ignored but causes storage of key values in descending order."

Fix in SQL, Go and Laravel:

sql
-- equality first, then the range/sort column
CREATE INDEX CONCURRENTLY orders_tenant_created_idx ON orders (tenant_id, created_at DESC);
-- mixed directions for ORDER BY priority DESC, created_at ASC
CREATE INDEX CONCURRENTLY jobs_queue_prio_idx ON jobs (queue, priority DESC, created_at);
go
// Keyset pagination that the (tenant_id, created_at DESC) index serves without a Sort.
rows, err := db.QueryContext(ctx, `
	SELECT id, created_at FROM orders
	 WHERE tenant_id = $1 AND created_at < $2
	 ORDER BY created_at DESC
	 LIMIT 50`, tenantID, cursor)
php
Schema::table('orders', function (Blueprint $table) {
    $table->index(['tenant_id', 'created_at'], 'orders_tenant_created_idx')->online();
});

Skip scan Important ​

In plain words: when the leading column of a composite index has only a few distinct values, the database can jump to each of those values in turn and search the rest of the key there, instead of scanning the whole index.

Common misunderstanding: "Skip scan makes column order irrelevant." It costs one index descent per distinct leading value; with thousands of values it loses to a correctly ordered index.

Definition: PostgreSQL 18 release notes: "Allow skip scans of btree indexes", which "allows multi-column btree indexes to be used in more cases such as when there are no restrictions on the first or early indexed columns". The 11.3 page explains when the planner tries it: "This approach is generally only taken when there are so few distinct x values that the planner expects the scan to skip over most of the index". PostgreSQL 19 keeps the feature (its release notes add no change to it). MySQL 8.4 has its own Skip Scan range access, shown as Using index for skip scan in EXPLAIN's Extra column. SQL Server, SQLite ("skip-scan" with ANALYZE statistics) and Oracle ("index skip scan") have similar ideas.

text
INDEX (region, created_at), region has 4 values; WHERE created_at >= X
1  descend to (region='af', created_at >= X), read until region changes
2  descend to (region='eu', created_at >= X), read ...
3  descend to (region='na', ...), 4  descend to (region='sa', ...)   -> 4 descents instead of a full scan

When to rely on it: low-cardinality leading columns you need first for other queries (is_deleted, region, kind). Otherwise build the index for the query.

Covering indexes, INCLUDE and the visibility map Must-know ​

In plain words: if the index already holds every column a query needs, the database can skip the table, but in PostgreSQL only for table pages that VACUUM has marked as visible to everyone.

Common misunderstanding: "Adding columns to the key and adding them to INCLUDE are the same." Key columns are sorted and searchable and make the tree deeper and wider at every level; INCLUDE columns live only in the leaf pages, cannot be searched, and do not count for uniqueness. The CREATE INDEX page: "A non-key column cannot be used in an index scan search qualification, and it is disregarded for purposes of any uniqueness or exclusion constraint enforced by the index."

Definition: a covering index contains all columns the query reads. INCLUDE (PostgreSQL, SQL Server; CockroachDB calls it STORING) adds non-key payload: CREATE INDEX tab_x_y ON tab(x) INCLUDE (y). Only B-tree, GiST and SP-GiST support included columns. Keep them few: "non-key columns duplicate data from the index's table and bloat the size of the index". The visibility map keeps a bit per heap page; "The first bit, if set, indicates that the page is all-visible". Whether the index-only scan pays off depends on that bit:

"In short, while an index-only scan is possible given the two fundamental requirements, it will be a win only if a significant fraction of the table's heap pages have their all-visible map bits set." — PostgreSQL documentation, 11.9. Index-Only Scans and Covering Indexes

text
     Writer session                              Reader: SELECT sum(total_cents) WHERE tenant_id=42
1    UPDATE orders SET status='paid' WHERE id=9  -- heap page 9001 bit cleared
2                                                Index Only Scan ... Heap Fetches: 1 (page 9001)
3    VACUUM orders;                              -- (or autovacuum) sets the bit again
4                                                Index Only Scan ... Heap Fetches: 0

Real scenarios: a "count by status" dashboard; EXISTS (SELECT 1 FROM memberships WHERE user_id = ? AND org_id = ?); an API listing that only returns id, title, updated_at; analytics over a partition that no longer changes.

Per product:

ProductHow a covering index worksVisibility caveat
PostgreSQLKey columns or INCLUDE; plan node Index Only ScanVisibility map; Heap Fetches shows misses; VACUUM sets bits
MySQL InnoDBAny secondary index already contains the PK; Extra: Using indexUndo-based MVCC; no visibility map needed
SQL ServerINCLUDE on nonclustered indexesAvoids Key Lookup; no visibility caveat
CockroachDBSTORING (...): "columns which are not part of the index key but should be stored in the index"Avoids an index join
MongoDB"Covered query" when filter and projection use only index fields (and _id excluded)totalDocsExamined: 0 in explain
sql
CREATE INDEX CONCURRENTLY orders_tenant_cover_idx ON orders (tenant_id) INCLUDE (total_cents);
VACUUM (ANALYZE) orders;  -- sets all-visible bits so the index-only scan avoids the heap

Partial indexes Must-know ​

In plain words: index only the rows your queries care about, such as pending jobs or non-deleted users.

Common misunderstanding: "The planner will use a partial index for any query on that column." It uses it only if it can prove the query's WHERE implies the index predicate; WHERE status = $1 with a parameter may not match WHERE status = 'pending' in a generic plan.

Definition: a partial index "contains entries only for those table rows that satisfy the predicate". The manual's main reason: "One major reason for using a partial index is to avoid indexing common values." With WHERE plus UNIQUE it enforces uniqueness on a subset ("use WHERE with UNIQUE to enforce uniqueness over a subset of a table"). SQLite uses the same words ("A partial index is an index over a subset of the rows of a table"); SQL Server calls it a filtered index: "an optimized disk-based rowstore nonclustered index especially suited to cover queries that select from a well-defined subset of data". MySQL has no partial index; emulate with a generated column that is NULL for excluded rows. MongoDB has partialFilterExpression.

text
orders: 2,000,000 rows, 20,000 with status = 'pending' (1%)
1  full index ON (status, created_at): 2,000,000 entries, every INSERT and status change maintains it
2  partial ON (created_at) WHERE status = 'pending': 20,000 entries, ~1% of the size
3  rows leave the index when status changes away from 'pending'

Real scenarios: job and outbox tables (WHERE processed_at IS NULL); soft deletes (UNIQUE (email) WHERE deleted_at IS NULL); one active subscription per user (UNIQUE (user_id) WHERE status = 'active'); hot "unread notifications".

sql
CREATE INDEX CONCURRENTLY orders_pending_idx ON orders (created_at) WHERE status = 'pending';
CREATE UNIQUE INDEX CONCURRENTLY users_email_live_uq ON users (lower(email)) WHERE deleted_at IS NULL;

Expression (functional) indexes Must-know ​

In plain words: index the result of a function so a query that filters on the same expression can use it.

Common misunderstanding: "An index on email serves WHERE lower(email) = ?." It does not: the index stores email, the query compares lower(email). The expression in the query must match the indexed expression.

Definition: PostgreSQL: CREATE INDEX ON users (lower(email)); the function must be IMMUTABLE, and the expression is computed on every insert and non-HOT update. MySQL 8 calls them functional key parts, written in double parentheses: CREATE INDEX idx1 ON t1 ((col1 + col2)); the manual: "Use of functional key parts enables indexing of values not stored directly in the table." Oracle calls them function-based indexes; SQL Server needs an indexed computed column.

text
1  query: WHERE lower(email) = 'ann@x.io'
2  index ON (email)          -> not usable (different expression) -> Seq Scan
3  index ON (lower(email))   -> Index Cond: (lower(email) = 'ann@x.io')

Real scenarios: case-insensitive login and uniqueness; date_trunc('day', created_at) for daily rollups (only with timestamp, since the timestamptz version is not immutable); a JSON field ((payload->>'customer_id')); a normalized phone number.

sql
CREATE UNIQUE INDEX CONCURRENTLY users_email_lower_uq ON users (lower(email));
-- MySQL 8.4
CREATE INDEX users_email_lower_idx ON users ((lower(email)));

Unique indexes vs unique constraints Important ​

In plain words: a unique constraint is the rule; a unique index is how the database enforces it. Declaring the constraint creates the index.

Common misunderstanding: "Checking for duplicates in code is enough." Two concurrent requests both see "no row" and both insert; only the unique index stops the second (see Isolation Levels).

Definition: "PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table", and the index "is the mechanism that enforces the constraint". "Currently, only B-tree indexes can be declared unique." Differences: a constraint can be referenced by a foreign key and by ON CONFLICT ON CONSTRAINT, and can be DEFERRABLE; a unique index can be partial or on an expression, which a constraint cannot. You can promote an index with ALTER TABLE ... ADD CONSTRAINT ... UNIQUE USING INDEX, which is exactly what Laravel's unique()->online() compiles to on PostgreSQL (verified in PostgresGrammar::compileUnique). Violations raise SQLSTATE 23505 (PostgreSQL) or error 1062 ER_DUP_ENTRY (MySQL).

text
     Request A                                  Request B
1    SELECT 1 FROM users WHERE email='a@x' -- none
2                                               SELECT 1 FROM users WHERE email='a@x' -- none
3    INSERT INTO users(email) VALUES ('a@x')    -- takes the unique index entry
4                                               INSERT ... ('a@x') -- waits for A, then 23505

NULLs in indexes Important ​

In plain words: most databases store NULLs in B-tree indexes; what differs is whether IS NULL can use them and whether two NULLs count as duplicates.

Common misunderstanding: "A unique column allows only one NULL." In PostgreSQL, MySQL and SQLite, NULLs are distinct by default, so many rows may have NULL. PostgreSQL offers NULLS NOT DISTINCT: "The NULLS NOT DISTINCT option modifies this and causes the index to treat nulls as equal." SQL Server treats NULLs as equal in unique indexes (only one allowed) unless you use a filtered index WHERE col IS NOT NULL. Oracle does not store entirely-NULL keys in a B-tree index, so WHERE col IS NULL cannot use a single-column index there.

ProductNULLs stored in B-tree?IS NULL uses index?Unique with several NULLs
PostgreSQLYes; NULLS FIRST/LAST placementYesAllowed; NULLS NOT DISTINCT forbids
MySQL InnoDBYesYes (ref_or_null)Allowed
SQL ServerYesYesOne NULL only; use filtered index
OracleNot when all key columns are NULLOnly via composite or function trickAllowed
SQLiteYesYesAllowed
php
// Laravel 13: IndexDefinition::nullsNotDistinct() is PostgreSQL-only.
$table->unique(['tenant_id', 'external_ref'])->nullsNotDistinct();

Index types (PostgreSQL access methods) ​

By default CREATE INDEX builds a B-tree; USING method picks another. The manual: each type "uses a different algorithm that is best suited to different types of indexable clauses." Multicolumn support differs: "A multicolumn B-tree index can be used with query conditions that involve any subset of the index's columns, but the index is most efficient when there are constraints on the leading (leftmost) columns", while GiST, GIN and BRIN multicolumn indexes can use any subset of columns.

B-tree Must-know ​

In plain words: the sorted tree that answers equality, ranges, prefix LIKE and ORDER BY; use it unless you have a reason not to.

Common misunderstanding: "B-tree only helps =." It serves < <= = >= >, BETWEEN, IN, IS NULL, IS NOT NULL, and "the pattern matching operators LIKE and ~ if the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar'."

Definition: a balanced B+tree of 8 kB pages (node layout, splits and fan-out are in B-Tree vs B+Tree). PostgreSQL adds deduplication (equal keys stored once with a posting list, controlled by deduplicate_items) and bottom-up index deletion, which removes "version churn index tuples" before a page split. Parallel builds are supported for B-tree, GIN and BRIN.

Hash Good to know ​

In plain words: stores a 32-bit hash of the value, so it answers only =.

Common misunderstanding: "Hash is always faster than B-tree for equality." For short keys a B-tree is about as fast and also supports ranges, sorting and uniqueness. Hash wins mainly on long keys (URLs, tokens) where the index stays small. The manual: "Hash indexes are best optimized for SELECT and UPDATE-heavy workloads that use equality scans on larger tables." Hash cannot be UNIQUE ("Currently, only B-tree indexes can be declared unique"), cannot be multicolumn ("only the B-tree, GiST, GIN, and BRIN index types support multiple-key-column indexes") and supports no index-only scans. MySQL InnoDB has no user-visible hash index (it builds an internal adaptive hash index); USING HASH applies to the MEMORY engine.

GIN (Generalized Inverted Index) Must-know ​

In plain words: like the index at the back of a book: for every word (array element, JSON key/value, trigram) a list of rows that contain it.

Common misunderstanding: "GIN is free on writes." One row with 50 array elements produces 50 index entries. GIN buffers new entries in a pending list (fastupdate = on, flushed by VACUUM or when it exceeds gin_pending_list_limit), so inserts are cheaper but some searches slow down until the list is cleaned. The manual: "If consistent response time is more important than update speed, use of pending entries can be disabled by turning off the fastupdate storage parameter for a GIN index."

Definition: "GIN stands for Generalized Inverted Index." Operators depend on the operator class: @>, <@, &&, = for arrays; @>, ?, ?|, ?&, @?, @@ for jsonb; @@ for tsvector; LIKE/ILIKE/% with pg_trgm's gin_trgm_ops. GIN always answers through bitmap scans and never through index-only scans.

JSONB. The default jsonb_ops indexes every key and value separately; jsonb_path_ops hashes each path-to-value: "A jsonb_path_ops index is usually much smaller than a jsonb_ops index over the same data, and the specificity of searches is better, particularly when queries contain keys that appear frequently in the data." The trade: jsonb_path_ops "does not support the key-exists operators", so ? cannot use it. When you always query one field, a B-tree expression index on (payload->>'customer_id') is smaller and supports ranges.

sql
CREATE INDEX CONCURRENTLY events_payload_gin ON events USING gin (payload jsonb_path_ops);
SELECT id FROM events WHERE payload @> '{"type": "order.paid", "tenant": 42}';
-- trigram GIN for LIKE '%foo%' (extension pg_trgm)
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX CONCURRENTLY products_name_trgm ON products USING gin (name gin_trgm_ops);

Full text. CREATE INDEX ... USING gin (to_tsvector('english', body)) and WHERE to_tsvector('english', body) @@ to_tsquery(...); ranking, dictionaries and the comparison with Elasticsearch are in Full-Text Search.

GiST (Generalized Search Tree) Important ​

In plain words: a balanced tree whose nodes hold "bounding" summaries (boxes, ranges), good for "overlaps", "contains" and "nearest to".

Common misunderstanding: "GiST is only for PostGIS." It also powers range types, exclusion constraints (no two bookings overlap), inet, nearest-neighbour ORDER BY location <-> point LIMIT 10, and btree_gist for mixing scalar equality into exclusion constraints. The manual calls it "an infrastructure within which many different indexing strategies can be implemented."

sql
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE bookings ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (room_id WITH =, during WITH &&);

PostgreSQL 19 made the core GiST operator class the default for inet/cidr indexes instead of the btree_gist one, because, in the release notes' words, "The btree_gist inet/cidr opclasses are broken because they can exclude rows that should be returned."

SP-GiST Good to know ​

"SP-GiST supports partitioned search trees, which facilitate development of a wide range of different non-balanced data structures, such as quad-trees, k-d trees, and radix trees (tries)." Use it for points with a skewed distribution, IP ranges and text prefix searches (^@). Like GiST it supports nearest-neighbour searches.

BRIN (Block Range Index) Important ​

In plain words: for each group of adjacent table pages, remember only the minimum and maximum value; skip groups that cannot match.

Common misunderstanding: "BRIN is a tiny B-tree." It is lossy and only useful when values follow physical order: "BRIN is designed for handling very large tables in which certain columns have some natural correlation with their physical location within the table." On a randomly ordered column every range overlaps every query and BRIN reads everything.

Definition: "A block range is a group of pages that are physically adjacent in the table; for each block range, some summary info is stored by the index." The range size is the pages_per_range storage parameter, set at creation time. New ranges are summarized by VACUUM, by brin_summarize_new_values(), or automatically with autosummarize = on. Plans are always bitmap scans with Rows Removed by Index Recheck.

sql
CREATE INDEX events_created_brin ON events USING brin (created_at) WITH (pages_per_range = 64, autosummarize = on);

Real scenarios: append-only logs, IoT readings, ledger entries by time; a few kB of index for a table of hundreds of GB. Strategy for such tables is in Billion-Row Tables.

bloom (extension) Good to know ​

In plain words: one small fingerprint per row covering many columns, so any combination of equality filters can be checked without a separate index per combination.

Definition: "bloom provides an index access method based on Bloom filters." The catch is in the next sentences: "A signature is a lossy representation of the indexed attribute(s), and as such is prone to reporting false positives". It supports only =, needs a recheck on the heap, and the signature length (length, bits per column col1 to col32) trades size against false positives. Good for wide tables queried by arbitrary column subsets (product filters, test-result matrices). The data structure itself is explained in Bloom Filters.

sql
CREATE EXTENSION IF NOT EXISTS bloom;
CREATE INDEX CONCURRENTLY items_bloom ON items USING bloom (c1, c2, c3, c4, c5, c6) WITH (length = 80);

Operator classes and collations Important ​

In plain words: an operator class tells an index which operators it can answer and how to compare values; a collation tells text comparison how to sort. Pick the wrong one and the index exists but cannot be used.

Common misunderstanding: "An index on a text column serves LIKE 'abc%'." Only if the column's collation is C (byte order) or the index uses text_pattern_ops. In a linguistic collation like en_US.UTF-8, prefix order is not byte order, so the default B-tree cannot answer LIKE. The manual: "If you do use the C locale, you do not need the xxx_pattern_ops operator classes, because an index with the default operator class is usable for pattern-matching queries in the C locale." A text_pattern_ops index, in turn, cannot serve ordinary <, > or ORDER BY in the column's collation, so you may need both.

Collations. "An index can support only one collation per index column. If multiple collations are of interest, multiple indexes may be needed." A query with COLLATE "de-x-icu" cannot use an index built on the default collation. After an OS or ICU library upgrade that changes sort order, text indexes must be rebuilt (REINDEX), or they silently return wrong results; PostgreSQL warns with a collation version mismatch.

sql
CREATE INDEX CONCURRENTLY users_name_pattern_idx ON users (name text_pattern_ops);   -- LIKE 'abc%'
CREATE INDEX CONCURRENTLY users_name_idx ON users (name);                            -- ORDER BY name, <, >
SELECT am.amname, opc.opcname FROM pg_opclass opc JOIN pg_am am ON am.oid = opc.opcmethod
 WHERE opc.opcintype = 'jsonb'::regtype;   -- list jsonb opclasses: jsonb_ops, jsonb_path_ops, ...

MySQL InnoDB ​

Clustered primary key and secondary indexes Must-know ​

In plain words: in InnoDB the table is a B-tree sorted by primary key; every other index stores the primary key as its pointer.

Common misunderstanding: "Index design is the same in MySQL and PostgreSQL." In InnoDB a secondary-index lookup is two B-tree descents (secondary, then clustered), the primary key is part of every secondary index (so a wide PK bloats them all), and every secondary index is implicitly "covering" for the PK columns.

Definition:

"Each InnoDB table has a special index called the clustered index that stores row data. Typically, the clustered index is synonymous with the primary key." — MySQL 8.4 Reference Manual, 17.6.2.1 Clustered and Secondary Indexes

Without a PK, InnoDB uses the first UNIQUE NOT NULL index, else a hidden GEN_CLUST_INDEX on a synthetic row ID. "If the primary key is long, the secondary indexes use more space". Random UUID primary keys scatter inserts across the clustered index and cause page splits; time-ordered keys (auto-increment, UUIDv7) append at the right edge (see ID Generation).

text
SELECT * FROM orders WHERE email = 'a@x'   (secondary index on email, PK id)
1  descend idx_email -> leaf ('a@x', id=812)
2  descend PRIMARY   -> leaf id=812 -> full row
   PostgreSQL: descend index -> TID -> heap page (no second tree)

Index Condition Pushdown (ICP) Important ​

InnoDB can evaluate parts of the WHERE that use index columns before fetching the full row. The manual's example: "With Index Condition Pushdown, MySQL checks the lastname LIKE '%etrunia%' part before reading the full table row." EXPLAIN shows Using index condition. It applies to the range, ref, eq_ref and ref_or_null access methods. PostgreSQL does the equivalent check on index columns inside an index scan and reports it as part of Index Cond or Filter.

Invisible, descending and functional indexes Important ​

FeatureMySQL 8.4 syntaxWhat it is forPostgreSQL equivalent
Invisible indexALTER TABLE t ALTER INDEX i_idx INVISIBLE"test the effect of removing an index on query performance, without making a destructive change"None built in; hypopg_hide_index() hides one in your session
Descending indexINDEX (c1 ASC, c2 DESC)Mixed-direction ORDER BY without a filesort(c1, c2 DESC)
Functional key partINDEX ((lower(email)))Index an expressionExpression index
Prefix indexINDEX (col(10))Index first N chars of long stringsExpression left(col, 10)
Multi-valued indexINDEX ((CAST(j->'$.tags' AS CHAR(32) ARRAY)))Index JSON arraysGIN on jsonb
Index Mergetype: index_mergeCombine indexesBitmapAnd / BitmapOr
Skip ScanUsing index for skip scanNon-prefix lookupsB-tree skip scan (18+)

The manual is explicit that "an index continues to be updated per changes to table rows, and a unique index prevents insertion of duplicates into a column, regardless of whether the index is visible or invisible", and a primary key cannot be made invisible (ERROR 3522 (HY000): A primary key index cannot be invisible.). optimizer_switch='use_invisible_indexes=on' lets one session test with them.

Other products ​

ProductDefault indexTable layoutNotable features
PostgreSQLB-treeHeap + secondary indexesGIN, GiST, SP-GiST, BRIN, bloom, INCLUDE, partial, expression, CONCURRENTLY
MySQL InnoDBB+treeClustered by PKICP, invisible, descending, functional, multi-valued, Index Merge
SQL ServerB+tree rowstoreClustered index or heapClustered/nonclustered, filtered, INCLUDE, columnstore, ONLINE = ON
OracleB-treeHeap, or index-organized tableBitmap indexes, function-based, invisible indexes, IOT
SQLiteB-treeRowid B-tree (or WITHOUT ROWID)Partial, expression indexes; covering indexes
MongoDBB-tree (WiredTiger)Collection + _id indexCompound, multikey, partial, TTL, wildcard; ESR guideline
CockroachDBSorted KV rangesPrimary index holds the rowSTORING, partial, inverted, hash-sharded indexes
RedisNone automaticKey-valueSorted sets as hand-built secondary indexes; Redis Query Engine FT.CREATE

SQL Server. "Clustered indexes sort and store the data rows in the table or view based on their key values", and "You can have only one clustered index per table, because the data rows themselves can be stored in only one order." Nonclustered indexes point to the clustered key (or a RID on a heap), as in InnoDB; filtered indexes are SQL Server's partial indexes and "reduce index maintenance and storage costs". Laravel's ->online() emits WITH (online = on) there.

Oracle. "Index-organized tables are tables stored in an index structure", equivalent to a clustered table. Oracle's bitmap indexes ("the database stores a bitmap for each index key") are for low-cardinality columns in warehouses and lock badly under concurrent DML.

MongoDB. For compound indexes MongoDB documents the ESR (Equality, Sort, Range) guideline: "Ensure that equality fields always come first", then sort fields, then range fields, or range before sort when the range is very selective (ERS). It is the same idea as PostgreSQL's equality-then-range, with sort placement made explicit. More in MongoDB.

Mechanics ​

Write amplification and index maintenance cost Must-know ​

In plain words: one logical write becomes many physical writes: the table row, one entry per index, and the WAL (or redo log) for all of them.

Common misunderstanding: "Indexes only cost disk space." They cost CPU, WAL volume, replication bandwidth, buffer-cache space, vacuum work and lock time on every write. The MySQL manual: "Indexes also add to the cost of inserts, updates, and deletes because each index must be updated."

Definition: in PostgreSQL an INSERT writes the heap tuple plus one entry per index. An UPDATE writes a new tuple version; if no indexed column changed and the page has room, it is a HOT (heap-only tuple) update and no index is touched; otherwise every index gets a new entry, even indexes on unchanged columns. The manual on indexes: they "can also prevent the creation of heap-only tuples". InnoDB updates only the secondary indexes whose columns changed, but a PK change rewrites every secondary index entry.

text
UPDATE orders SET status = 'paid' WHERE id = 9;   table has 6 indexes, one on status
1  HOT possible?  status is indexed -> no
2  write new heap tuple                       (1 heap write)
3  insert new entry into all 6 indexes        (6 index writes, even unchanged columns)
4  WAL records for 7 page changes; replicas replay all 7
   Without the status index and with free space on the page: 1 heap write, HOT, 0 index writes

Monitor with pg_stat_user_tables.n_tup_hot_upd vs n_tup_upd. To increase HOT updates: drop indexes on frequently updated columns that queries do not need, and lower the table's fillfactor; the manual: "You can increase the likelihood of sufficient page space for HOT updates by decreasing a table's fillfactor." Storage-level details are in Database Internals and B-tree vs LSM write amplification in Storage Engines.

Fillfactor for indexes Good to know ​

"B-trees use a default fillfactor of 90, but any integer value from 10 to 100 can be selected." Lower values leave room for inserts in the middle of the key space and "can usefully “smooth out” the rate of page splits during the early life of the B-tree index"; 100 suits read-only or append-only indexes. Set it at build time: CREATE INDEX ... WITH (fillfactor = 70). InnoDB has a similar server setting, innodb_fill_factor, for sorted index builds.

Index bloat Important ​

In plain words: an index that has grown larger than its live data, full of empty or half-empty pages after many updates and deletes.

Common misunderstanding: "VACUUM shrinks indexes." VACUUM removes dead entries and makes their space reusable inside the index, but rarely returns pages to the OS; B-tree pages are deleted only when completely empty. The REINDEX page lists the cases: "An index has become “bloated”, that is it contains many empty or nearly-empty pages."

Definition: measure with pgstattuple's pgstatindex() (avg_leaf_density, leaf_fragmentation) or compare pg_relation_size(index) with an estimate. Fix with REINDEX INDEX CONCURRENTLY, which builds a new copy (named ..._ccnew while in progress) and swaps it in "without taking any locks that prevent concurrent inserts, updates, or deletes on the table". Deduplication and bottom-up deletion reduce bloat in PostgreSQL B-trees; long-running transactions increase it because VACUUM cannot remove entries they might still see (see MVCC & VACUUM).

Building indexes concurrently and INVALID indexes Must-know ​

In plain words: CREATE INDEX blocks writes until it finishes; CREATE INDEX CONCURRENTLY lets writes continue but takes longer and can fail half way.

Common misunderstanding: "If CONCURRENTLY fails, nothing is left behind." A failed build leaves an index marked INVALID. The manual: "This index will be ignored for querying purposes because it might be incomplete; however it will still consume update overhead." A unique one that failed in the second scan "continues to enforce its uniqueness constraint afterwards".

Definition: a standard build "locks out writes (but not reads) on the table until it's done". With CONCURRENTLY, "PostgreSQL must perform two scans of the table, and in addition it must wait for all existing transactions that could potentially modify or use the index to terminate." It cannot run inside a transaction block. On failure:

"If a problem arises while scanning the table, such as a deadlock or a uniqueness violation in a unique index, the CREATE INDEX command will fail but leave behind an “invalid” index." — PostgreSQL documentation, CREATE INDEX

"The recommended recovery method in such cases is to drop the index and try again to perform CREATE INDEX CONCURRENTLY. (Another possibility is to rebuild the index with REINDEX INDEX CONCURRENTLY)." Find leftovers with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid. Build speed depends on maintenance_work_mem and max_parallel_maintenance_workers.

text
     Migration (CREATE UNIQUE INDEX CONCURRENTLY)    App traffic
1    catalog entry created, indisvalid = false
2    wait for older transactions                       long report still running -> migration waits
3    scan 1: build index                               INSERTs continue, also write to new index
4    wait again; scan 2: add rows inserted meanwhile
5    duplicate found -> ERROR 23505                    index stays INVALID, still maintained, still unique
6    DROP INDEX CONCURRENTLY ...; fix data; retry
ProductOnline buildFailure leftover
PostgreSQLCREATE INDEX CONCURRENTLY, REINDEX ... CONCURRENTLYINVALID index (indisvalid = false), _ccnew for reindex
MySQL InnoDBOnline DDL: ALGORITHM=INPLACE, LOCK=NONE (Laravel ->inplace()->lock('none'))Rolled back; metadata lock waits can stall the table
SQL ServerWITH (ONLINE = ON) (Enterprise/Azure), resumable index operationsPaused resumable operation
OracleCREATE INDEX ... ONLINECheck USER_INDEXES.STATUS after an interrupted build
MongoDBIndex builds run while reads and writes continueBuild aborted and cleaned up

How the optimizer chooses an index Good to know ​

The planner estimates how many rows each condition returns (selectivity, from pg_statistic histograms, most-common values and correlation gathered by ANALYZE), prices each access path with seq_page_cost, random_page_cost, cpu_index_tuple_cost and effective_cache_size, and picks the cheapest. That is why a low-cardinality column (few distinct values) or a common value is answered with a Seq Scan, why correlation between index order and heap order favours Index Scans, and why stale statistics produce bad choices. Hints do not exist in core PostgreSQL (pg_hint_plan is an extension); MySQL has FORCE INDEX/USE INDEX and index hints; SQL Server has WITH (INDEX(...)). The full story, including join algorithms and reading EXPLAIN, is in Query Planning.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Slow filter + sortComposite index, equality then range/sort(tenant_id, created_at DESC)No Sort, few pagesOne more index to maintain
Query reads a small subsetPartial indexWHERE status = 'pending'Tiny, cheap to maintainQuery must imply the predicate
Case-insensitive lookupExpression index(lower(email))Index matches the queryQuery must use the same expression
Heap reads dominateCovering indexINCLUDE (...) + VACUUMIndex Only ScanBigger index; needs all-visible pages
Adding an index in productionCREATE INDEX CONCURRENTLYOne statement, outside a transactionWrites continueSlower; may leave INVALID
Too many indexesDrop unused and redundant onespg_stat_user_indexes, prefix checkFaster writes, more HOTCheck every replica first
Unsure an index will helpHypothetical indexhypopg_create_index + EXPLAINZero build costPlanner estimate only, no ANALYZE timing
Index grew hugeREINDEX INDEX CONCURRENTLYRebuild + swapReclaims spaceExtra disk during rebuild

Adding an index to a live table ​

Go, before: two queries no index can serve (lower(email) against a plain-column index, and tenant_id plus a time range on an unindexed table), and a migration that sends three plain CREATE INDEX statements in one string.

go
// Package before shows queries that no index can serve, and a migration
// written as one hand-made SQL string.
package before

import (
	"context"
	"database/sql"
	"time"
)

// FindByEmail filters on lower(email). A plain index on email cannot be used
// for this predicate, so Postgres reads the whole table.
func FindByEmail(ctx context.Context, db *sql.DB, email string) (int64, error) {
	var id int64
	err := db.QueryRowContext(ctx,
		`SELECT id FROM users WHERE lower(email) = lower($1)`, email).Scan(&id)
	return id, err
}

// RecentForTenant filters on tenant_id and sorts on created_at, with no index
// on either column.
func RecentForTenant(ctx context.Context, db *sql.DB, tenantID int64, since time.Time) (*sql.Rows, error) {
	return db.QueryContext(ctx,
		`SELECT id, status, created_at FROM orders
		  WHERE tenant_id = $1 AND created_at >= $2
		  ORDER BY created_at DESC LIMIT 50`, tenantID, since)
}

// Migrate sends several statements in one string. Postgres runs a multi-
// statement simple query as one implicit transaction, and a plain CREATE INDEX
// blocks writes on the table until it finishes.
func Migrate(ctx context.Context, db *sql.DB) error {
	_, err := db.ExecContext(ctx, `
		CREATE INDEX orders_created_at_idx ON orders (created_at);
		CREATE INDEX orders_tenant_id_idx ON orders (tenant_id);
		CREATE INDEX orders_status_idx ON orders (status);
	`)
	return err
}

Go, after: each index matches a query shape and is built CONCURRENTLY. The statements run one per ExecContext call on the pool and never inside BeginTx, because PostgreSQL refuses CREATE INDEX CONCURRENTLY in a transaction block and wraps a multi-statement string in one. The same file has the pg_stat_user_indexes query for unused indexes and a check for INVALID leftovers.

go
// Package after builds indexes that match the queries, without blocking
// writers, and reports indexes that nothing reads.
package after

import (
	"context"
	"database/sql"
	"fmt"
)

// One statement per entry. CREATE INDEX CONCURRENTLY cannot run inside a
// transaction block, and Postgres wraps a multi-statement string in one.
var statements = []string{
	// Expression index: serves WHERE lower(email) = lower($1). UNIQUE makes
	// it a case-insensitive uniqueness rule too.
	`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS users_email_lower_uq
	   ON users (lower(email))`,

	// Composite index: equality column first, range/sort column second.
	`CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_tenant_created_idx
	   ON orders (tenant_id, created_at DESC)`,

	// Partial index: only the small pending subset is indexed.
	`CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_pending_idx
	   ON orders (created_at) WHERE status = 'pending'`,

	// Covering index: id and total ride along as non-key payload so the
	// query can be an index-only scan.
	`CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_tenant_status_cover_idx
	   ON orders (tenant_id, status) INCLUDE (id, total_cents)`,
}

// Migrate runs each statement on its own, with db.ExecContext and never
// inside db.BeginTx. A failed concurrent build leaves an INVALID index behind,
// so the caller must check InvalidIndexes afterwards.
func Migrate(ctx context.Context, db *sql.DB) error {
	for _, stmt := range statements {
		if _, err := db.ExecContext(ctx, stmt); err != nil {
			return fmt.Errorf("migrate: %w", err)
		}
	}
	return nil
}

// InvalidIndexes lists indexes left INVALID by a failed concurrent build.
// Drop them and run the statement again.
func InvalidIndexes(ctx context.Context, db *sql.DB) ([]string, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT c.relname
		  FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
		 WHERE NOT i.indisvalid`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var names []string
	for rows.Next() {
		var n string
		if err := rows.Scan(&n); err != nil {
			return nil, err
		}
		names = append(names, n)
	}
	return names, rows.Err()
}

// UnusedIndexes returns indexes never scanned since statistics were last
// reset. Unique indexes are skipped because they enforce a rule even when no
// query reads them. Check every replica before dropping anything.
func UnusedIndexes(ctx context.Context, db *sql.DB) ([]string, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT s.schemaname || '.' || s.indexrelname,
		       pg_size_pretty(pg_relation_size(s.indexrelid))
		  FROM pg_stat_user_indexes s
		  JOIN pg_index i ON i.indexrelid = s.indexrelid
		 WHERE s.idx_scan = 0
		   AND NOT i.indisunique
		 ORDER BY pg_relation_size(s.indexrelid) DESC`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var name, size string
		if err := rows.Scan(&name, &size); err != nil {
			return nil, err
		}
		out = append(out, name+" ("+size+")")
	}
	return out, rows.Err()
}

The Go angle. database/sql has no schema layer, so indexes are SQL strings you own. db.ExecContext on a *sql.DB checks out one connection and runs the statement outside any transaction, which is what CONCURRENTLY needs; db.BeginTx would break it. Keep the migration list small and idempotent (IF NOT EXISTS), and after a failure run the invalid-index query before retrying, because IF NOT EXISTS happily skips an INVALID index with the same name. Set a lock_timeout on the migration connection so the brief lock at the start does not queue behind a long transaction and block all traffic behind it. Whether your migration tool (goose, golang-migrate, atlas) can run a file outside a transaction is tool-specific; check before shipping a CONCURRENTLY file.

Laravel, before: a composite index with the range column first, a separate index on every column, and a plain build inside the default migration transaction.

php
<?php

// database/migrations/2026_01_10_000000_add_order_indexes.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            // The hot query is WHERE tenant_id = ? AND created_at >= ?.
            // With created_at first, the index cannot narrow by tenant.
            $table->index(['created_at', 'tenant_id']);

            // One index per column "just in case". Each one is extra work
            // on every INSERT and UPDATE and is rarely chosen by the planner.
            $table->index('tenant_id');
            $table->index('status');
            $table->index('total_cents');
            $table->index('created_at');
        });

        // Runs inside the migration transaction and locks out writers while
        // the indexes build, on a table that is serving traffic.
    }

    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropIndex(['created_at', 'tenant_id']);
            $table->dropIndex(['tenant_id']);
            $table->dropIndex(['status']);
            $table->dropIndex(['total_cents']);
            $table->dropIndex(['created_at']);
        });
    }
};

Laravel, after: the schema builder covers index([...]) and unique(...). The Laravel 13 migrations page says that on PostgreSQL the online() modifier "adds the CONCURRENTLY option to the index creation statement". Partial, INCLUDE and expression-unique indexes have no builder method, so they use DB::statement(). The migration sets public $withinTransaction = false;.

php
<?php

// database/migrations/2026_01_10_000000_add_order_indexes.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    // CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so
    // opt this migration out of the transaction Laravel wraps around it.
    public $withinTransaction = false;

    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            // Equality column first, range/sort column second.
            // online() adds CONCURRENTLY on PostgreSQL.
            $table->index(['tenant_id', 'created_at'], 'orders_tenant_created_idx')->online();

            // A unique index, also built concurrently.
            $table->unique(['tenant_id', 'external_ref'], 'orders_tenant_ref_uq')->online();
        });

        // The schema builder has no API for partial, INCLUDE or unique
        // expression indexes. Blueprint::rawIndex('lower(email)', 'name')
        // covers a plain expression index, but writing the SQL keeps
        // UNIQUE, WHERE, INCLUDE and CONCURRENTLY visible in one place.
        DB::statement(
            'CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS users_email_lower_uq
               ON users (lower(email))'
        );

        DB::statement(
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_pending_idx
               ON orders (created_at) WHERE status = 'pending'"
        );

        DB::statement(
            'CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_tenant_status_cover_idx
               ON orders (tenant_id, status) INCLUDE (id, total_cents)'
        );
    }

    public function down(): void
    {
        // unique()->online() created a UNIQUE *constraint* backed by the index,
        // so it must be dropped as a constraint, not with DROP INDEX.
        DB::statement('ALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_tenant_ref_uq');

        foreach ([
            'orders_tenant_status_cover_idx',
            'orders_pending_idx',
            'users_email_lower_uq',
            'orders_tenant_created_idx',
        ] as $index) {
            DB::statement("DROP INDEX CONCURRENTLY IF EXISTS {$index}");
        }
    }
};

The Laravel angle. The migrations documentation lists primary, unique, index, fullText, spatialIndex and vectorIndex, and the modifiers online() (PostgreSQL CONCURRENTLY, SQL Server WITH (online = on)) and, for MySQL, inplace() with lock('none'). The framework's IndexDefinition also declares algorithm() (e.g. gin), nullsNotDistinct() and deferrable() for PostgreSQL. Blueprint::rawIndex($expression, $name) exists for expression indexes. On PostgreSQL unique(...)->online() compiles to create unique index concurrently ... followed by alter table ... add constraint ... unique using index ..., so the result is a constraint and is dropped as one. The withinTransaction property is not on the 13.x migrations page; it is declared in Illuminate\Database\Migrations\Migration ("Enables, if supported, wrapping the migration within a transaction.") and read by the Migrator. A migration with several statements that fails half way is not rolled back, so keep concurrent-index migrations small and idempotent.

Finding unused indexes ​

pg_stat_user_indexes.idx_scan counts "index scans initiated on this index"; last_idx_scan records when the last one happened. An index with idx_scan = 0 over a long, representative window is a candidate, with three caveats: statistics are per server, so check every replica that serves reads; a reset (pg_stat_reset(), crash, or major upgrade) zeroes them; and unique, primary-key and exclusion indexes enforce rules even when never scanned.

sql
SELECT s.schemaname, s.relname, s.indexrelname, s.idx_scan, s.last_idx_scan,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
  FROM pg_stat_user_indexes s
  JOIN pg_index i ON i.indexrelid = s.indexrelid
 WHERE s.idx_scan = 0 AND NOT i.indisunique AND NOT i.indisprimary
 ORDER BY pg_relation_size(s.indexrelid) DESC;

MySQL: sys.schema_unused_indexes (from performance_schema), then make the index invisible for a week before dropping it. SQL Server: sys.dm_db_index_usage_stats (reset on restart). MongoDB: $indexStats.

Finding duplicate and redundant indexes ​

A duplicate index has the same columns, expressions, predicate and opclass as another. A redundant one is a left prefix of another B-tree: (tenant_id) is redundant next to (tenant_id, created_at), unless it is unique, much smaller and hot, or has a different opclass or collation.

sql
-- B-tree indexes whose key columns are a prefix of another index on the same table
SELECT a.indexrelid::regclass AS redundant, b.indexrelid::regclass AS covered_by
  FROM pg_index a
  JOIN pg_index b ON a.indrelid = b.indrelid AND a.indexrelid <> b.indexrelid
 WHERE (b.indkey::text || ' ') LIKE (a.indkey::text || ' %')
   AND a.indpred IS NULL AND b.indpred IS NULL
   AND a.indexprs IS NULL AND b.indexprs IS NULL
   AND NOT a.indisunique;

MySQL: sys.schema_redundant_indexes reports the same and prints a ready ALTER TABLE ... DROP INDEX.

Testing an index before building it: hypopg and invisible indexes ​

"A hypothetical -- or virtual -- index is an index that doesn't really exist, and thus doesn't cost CPU, disk or any resource to create." — HypoPG README

hypopg lets EXPLAIN (without ANALYZE) see an index that does not exist; it lives only in your backend ("The hypothetical indexes are contained in a single backend"), so other sessions are unaffected. hypopg_hide_index(oid) does the reverse: hides a real index from the planner in your session, a per-session version of MySQL's invisible index.

sql
CREATE EXTENSION IF NOT EXISTS hypopg;
SELECT * FROM hypopg_create_index('CREATE INDEX ON orders (tenant_id, created_at)');
EXPLAIN SELECT id FROM orders WHERE tenant_id = 42 AND created_at >= now() - interval '7 days';
--  Index Scan using <NNNNN>btree_orders_tenant_id_created_at on orders ...   (hypothetical name: <oid>btree_...)
SELECT hypopg_reset();
go
// Ask the planner, inside one connection, whether a candidate index would be chosen.
func WouldUseIndex(ctx context.Context, db *sql.DB, ddl, query string) (bool, error) {
	conn, err := db.Conn(ctx) // hypothetical indexes live in one backend
	if err != nil {
		return false, err
	}
	defer conn.Close()
	if _, err := conn.ExecContext(ctx, `SELECT * FROM hypopg_create_index($1)`, ddl); err != nil {
		return false, err
	}
	defer conn.ExecContext(ctx, `SELECT hypopg_reset()`)
	var plan string
	if err := conn.QueryRowContext(ctx, `EXPLAIN (FORMAT JSON) `+query).Scan(&plan); err != nil {
		return false, err
	}
	return strings.Contains(plan, `"Index Name": "<`), nil // hypothetical index names start with "<oid>"
}
sql
-- MySQL 8.4: the reversible way to "drop" an index
ALTER TABLE orders ALTER INDEX orders_status_idx INVISIBLE;
-- watch latency for a week; then DROP or make it VISIBLE again

Rebuilding a bloated or corrupt index ​

sql
SELECT * FROM pgstatindex('orders_tenant_created_idx');     -- extension pgstattuple: avg_leaf_density
REINDEX INDEX CONCURRENTLY orders_tenant_created_idx;
-- if interrupted: \d orders shows "orders_tenant_created_idx_ccnew" INVALID -> DROP INDEX it and retry

After an OS/glibc or ICU upgrade that changes collation order, rebuild text indexes; amcheck's bt_index_check() verifies B-tree ordering.

Guarding index usage in tests ​

go
// A test helper: fail if a hot query plans a Seq Scan on a large table.
func AssertNoSeqScan(ctx context.Context, db *sql.DB, query string, args ...any) error {
	var plan string
	if err := db.QueryRowContext(ctx, "EXPLAIN (FORMAT JSON) "+query, args...).Scan(&plan); err != nil {
		return err
	}
	if strings.Contains(plan, `"Node Type": "Seq Scan"`) {
		return fmt.Errorf("seq scan in plan for %q", query)
	}
	return nil
}
php
// Laravel: the query builder can print the plan in a test or tinker session.
DB::table('orders')
    ->where('tenant_id', 42)
    ->where('created_at', '>=', now()->subDays(7))
    ->explain()
    ->dd();

Run such guards against a database with realistic statistics; on an empty test table the planner rightly prefers a Seq Scan.

Choosing an index ​

Query shape / workloadIndexExtra techniqueReason
WHERE a = ? AND b = ?B-tree (a, b) (most selective or most reused first)INCLUDE the selected columnsOne slice; may become index-only
WHERE a = ? AND t >= ? ORDER BY tB-tree (a, t)DESC if you read newest firstEquality then range; no Sort
WHERE t >= ? on an append-only logBRIN (t)Partition by timeTiny index, correlated with physical order
WHERE status = 'pending' (1%)Partial B-treeWHERE predicate equals querySmall, cheap writes
WHERE lower(email) = ?Expression B-tree, UNIQUEcitext or nondeterministic collation alternativesMatches the expression
LIKE 'abc%' in a non-C collationB-tree text_pattern_opsKeep a default index for ORDER BYByte-order comparison
LIKE '%abc%', fuzzy searchGIN gin_trgm_opsOr full-text searchTrigram inverted index
jsonb @> '{...}'GIN jsonb_path_opsExpression B-tree for one hot fieldSmall, precise
Arrays tags && '{a,b}'GINInverted index
Ranges, overlaps, no double bookingGiST + EXCLUDEbtree_gistOverlap operators
Nearest locationGiST or SP-GiST (PostGIS)ORDER BY geom <-> point LIMIT kKNN search
Equality on any of 10 columnsbloomRecheck costOne index for all combinations
Long key, = onlyHashSmaller than B-tree
a = ? OR b = ?Two B-treesBitmapOr / Index MergeCombine indexes
Write-heavy table, many indexesFewer, wider composite indexesDrop unused, lower fillfactor, HOTWrite amplification
MySQL InnoDB secondary lookupsShort PK; secondary indexes include PK implicitlyICPPK copied into every secondary
MongoDB compoundESR orderPartial, covered queriesSame rule, sort placement explicit

In architecture: from a single process to a distributed system ​

Indexes are part of the contract between code and database: a query that is fast in review can be a full scan at ten times the data. Treat the index list as code, reviewed with the queries that need it.

Monolith: one process, one database ​

How it shows up: every endpoint's main query should have an index designed for it, and the ORM hides which queries exist. Simplest correct usage: list the top queries from pg_stat_statements, design composite indexes for them, add them with CONCURRENTLY in their own migration, verify with EXPLAIN (ANALYZE, BUFFERS), and review pg_stat_user_indexes quarterly.

Example (simple): a shop's GET /orders?status=pending gets a partial index; login gets UNIQUE (lower(email)).

Example (complex): an admin search with ten optional filters. Instead of ten single-column indexes (each one slowing checkout writes), build two composite indexes for the 90% shapes, a bloom or GIN index for the long tail, and route the rest to a replica or search engine.

Modular monolith and multiple databases ​

Modules that own tables also own their indexes; a module that queries another module's table by a column the owner never indexed creates hidden coupling. Expose a query API (or a read model) instead, and let the owner index for it. When modules move to separate databases, joins become application-side lookups, and each lookup needs an index on its key in the owning database.

Microservices: per-service indexes and read models ​

What survives: each service indexes its own store for its own queries. What does not: cross-service joins. A "search orders by customer email" screen in an order service cannot use the customer service's index. The usual flow is a read model:

text
Customer service          Broker                  Order service (read model)
1  UPDATE customers SET email=...; INSERT outbox(CustomerEmailChanged); COMMIT
2                         CustomerEmailChanged ->
3                                                 UPSERT order_customers(customer_id, email)
                                                  -- indexed: UNIQUE(customer_id), (lower(email))
4  GET /orders?email=...  -> Order service queries its own indexed read model

The read model's indexes are designed for the screen, and the unique index on the event key gives idempotent upserts (see Outbox, Idempotent Consumers).

Distributed data: replicas, caches, sharding and distributed SQL ​

Read replicas. Physical replicas have exactly the primary's indexes; you cannot add a reporting index only on a replica (logical replicas can have their own). Index usage statistics are per node, so an index unused on the primary may be the replica's busiest. Every index adds WAL volume and therefore replication lag.

Caches. A cache in front of a query hides a missing index until the cache is cold (deploy, eviction, new tenant); then the database takes the full scan at peak. Index the query anyway.

Sharding and partitioning. In PostgreSQL partitioning, an index on the parent creates one index per partition; a unique index must include the partition key. In sharded systems (Citus, Vitess), queries that include the shard key hit one shard's index; queries without it fan out to every shard, so global uniqueness on a non-shard column needs a separate lookup table. See Partitioning & Sharding.

Distributed SQL. CockroachDB stores each index as its own sorted key range, so a secondary-index write is a distributed write to another range, and its docs recommend STORING to avoid an "index join". Sequential keys create hot ranges; hash-sharded indexes spread them.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesIndex consequence
1× (one primary, < 10 GB)Everything fits in memoryPrimary keys, foreign-key indexes, unique constraints, a few composite indexes; most mistakes are invisible
10× (100 GB, replicas, hot tables)Data exceeds RAM; writes competeComposite and covering indexes for top queries; partial indexes on queues; CONCURRENTLY only; drop unused indexes to recover write throughput and HOT updates; monitor bloat
100× (TB, partitions/shards)Index builds take hours; one bad plan hurts everyoneBRIN for time-ordered data, partition-local indexes, shard key in every hot index, hypothetical-index testing, plan guards in CI; see Billion-Row Tables

Lab ​

One PostgreSQL 18 container (skip scan needs 18 or later). The expected plan shapes are in comments; we show node names and counters, not timings, because those depend on your machine. A MySQL experiment closes the lab.

Setup.

bash
docker run -d --name pgidx -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:18
docker exec -it pgidx psql -U postgres          # terminal A
docker exec -it pgidx psql -U postgres          # terminal B (experiment 4)
sql
CREATE TABLE orders (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id    int         NOT NULL,
  status       text        NOT NULL,
  total_cents  int         NOT NULL,
  created_at   timestamptz NOT NULL,
  email        text        NOT NULL,
  external_ref text
) WITH (autovacuum_enabled = false);           -- so the lab controls when VACUUM runs
INSERT INTO orders (tenant_id, status, total_cents, created_at, email, external_ref)
SELECT 1 + (g % 1000),
       CASE WHEN g % 100 = 0 THEN 'pending' ELSE 'paid' END,      -- 1% pending
       (random() * 100000)::int,
       now() - (g || ' seconds')::interval,
       'User' || g || '@Example.com',
       'ref-' || (g % 1999990)                                    -- 10 duplicate refs, on purpose
FROM generate_series(1, 2000000) AS g;
ANALYZE orders;

Experiment 1: before/after one index.

sql
EXPLAIN (ANALYZE, BUFFERS) SELECT id, total_cents FROM orders
 WHERE tenant_id = 42 AND created_at >= now() - interval '7 days';
-- Seq Scan on orders (or Parallel Seq Scan under Gather)
--   Filter: ((tenant_id = 42) AND ...)  Rows Removed by Filter: ~2000000
--   Buffers: shared hit/read ≈ every page of the table
CREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at);
-- run the same EXPLAIN again
-- Index Scan using orders_tenant_created_idx (or Bitmap Heap Scan on top of a Bitmap Index Scan)
--   Index Cond: ((tenant_id = 42) AND (created_at >= ...))
--   Buffers: a few dozen pages
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM orders WHERE created_at >= now() - interval '1 hour';
-- not a left prefix: Seq Scan, or on 18+ possibly an Index Scan using the skip scan
-- (1000 tenant values is many; try an index on (status, created_at) for a clear skip scan: 2 values)

Experiment 2: index-only scan with and without VACUUM.

sql
CREATE INDEX orders_tenant_cover_idx ON orders (tenant_id) INCLUDE (total_cents);
SET enable_bitmapscan = off;   -- before VACUUM the planner may otherwise prefer a bitmap scan
EXPLAIN (ANALYZE, BUFFERS) SELECT sum(total_cents) FROM orders WHERE tenant_id = 42;
-- Index Only Scan using orders_tenant_cover_idx
--   Heap Fetches: ~2000        <- visibility map not set yet: every row checked in the heap
VACUUM orders;
EXPLAIN (ANALYZE, BUFFERS) SELECT sum(total_cents) FROM orders WHERE tenant_id = 42;
--   Heap Fetches: 0            <- all pages all-visible; buffers drop sharply
UPDATE orders SET total_cents = total_cents + 1 WHERE tenant_id = 42;
EXPLAIN (ANALYZE, BUFFERS) SELECT sum(total_cents) FROM orders WHERE tenant_id = 42;
--   Heap Fetches: back up      <- updated pages lost their all-visible bit until the next VACUUM

Experiment 3: partial index selectivity.

sql
CREATE INDEX orders_status_full_idx    ON orders (status, created_at);
CREATE INDEX orders_pending_partial_idx ON orders (created_at) WHERE status = 'pending';
SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid))
  FROM pg_stat_user_indexes WHERE relname = 'orders';
-- orders_status_full_idx      tens of MB
-- orders_pending_partial_idx  ~1% of that
EXPLAIN SELECT id FROM orders WHERE status = 'pending' ORDER BY created_at LIMIT 20;
-- Index Scan using orders_pending_partial_idx   <- the query implies the predicate
EXPLAIN SELECT id FROM orders WHERE status = 'paid' ORDER BY created_at LIMIT 20;
-- uses orders_status_full_idx (or a Seq Scan + Sort): 99% of rows match; the partial index cannot answer
PREPARE q(text) AS SELECT id FROM orders WHERE status = $1 ORDER BY created_at LIMIT 20;
SET plan_cache_mode = force_generic_plan;
EXPLAIN EXECUTE q('pending');
-- the generic plan cannot prove status = 'pending', so it does not use orders_pending_partial_idx
RESET plan_cache_mode;

Experiment 4: CONCURRENTLY failure leaves an INVALID index.

sql
-- terminal A
CREATE UNIQUE INDEX CONCURRENTLY orders_ref_uq ON orders (external_ref);
-- fails: unique violation on a duplicated 'ref-...' value (SQLSTATE 23505)
\d orders
--   "orders_ref_uq" UNIQUE, btree (external_ref) INVALID
SELECT indexrelid::regclass, indisvalid, indisready FROM pg_index WHERE NOT indisvalid;
-- orders_ref_uq | f | ?     <- indisvalid = f: ignored by queries; note what indisready shows on your run
-- The manual: an invalid index "will still consume update overhead"; one that failed in the SECOND scan
-- (a duplicate inserted while it was building) "continues to enforce its uniqueness constraint afterwards".
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS orders_ref_uq ON orders (external_ref);
-- only a NOTICE that the relation exists: IF NOT EXISTS skips the INVALID index and hides the problem
DROP INDEX CONCURRENTLY orders_ref_uq;
UPDATE orders SET external_ref = external_ref || '-' || id
 WHERE external_ref IN (SELECT external_ref FROM orders GROUP BY 1 HAVING count(*) > 1);
CREATE UNIQUE INDEX CONCURRENTLY orders_ref_uq ON orders (external_ref);   -- succeeds

-- waiting on old transactions: terminal B
BEGIN; SELECT count(*) FROM orders;              -- leave open
-- terminal A
CREATE INDEX CONCURRENTLY orders_email_idx ON orders (email);   -- waits until B commits
-- terminal B
COMMIT;                                          -- A finishes

Experiment 5: expression index, opclass and hypothetical index.

sql
EXPLAIN SELECT id FROM orders WHERE lower(email) = 'user42@example.com';     -- Seq Scan (orders_email_idx stores email, not lower(email))
CREATE INDEX orders_email_lower_idx ON orders (lower(email));
EXPLAIN SELECT id FROM orders WHERE lower(email) = 'user42@example.com';     -- Index Scan / Bitmap on orders_email_lower_idx
EXPLAIN SELECT id FROM orders WHERE email LIKE 'User42%';                   -- in en_US.UTF-8: no index use for LIKE
CREATE INDEX orders_email_pattern_idx ON orders (email text_pattern_ops);
EXPLAIN SELECT id FROM orders WHERE email LIKE 'User42%';                   -- Index Cond: (email ~>=~ 'User42') AND (email ~<~ 'User43')
-- hypopg is not in the official image; install it (e.g. apt-get install postgresql-18-hypopg) to try:
-- SELECT * FROM hypopg_create_index('CREATE INDEX ON orders (total_cents)'); EXPLAIN SELECT ... WHERE total_cents = 5;

Experiment 6 (MySQL 8.4): clustered PK, covering and invisible indexes.

sql
-- docker run -d --name myidx -e MYSQL_ROOT_PASSWORD=my -e MYSQL_DATABASE=lab mysql:8.4
CREATE TABLE orders (id BIGINT AUTO_INCREMENT PRIMARY KEY, tenant_id INT NOT NULL,
  created_at DATETIME NOT NULL, total_cents INT NOT NULL, INDEX tenant_created (tenant_id, created_at));
SET SESSION cte_max_recursion_depth = 200000;
INSERT INTO orders (tenant_id, created_at, total_cents)
WITH RECURSIVE g(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM g WHERE n < 200000)
SELECT n % 1000, NOW() - INTERVAL n MINUTE, n FROM g;
ANALYZE TABLE orders;
EXPLAIN SELECT id, created_at FROM orders WHERE tenant_id = 42;
-- type: ref, key: tenant_created, Extra: Using index     <- covering: id (PK) is inside every secondary index
EXPLAIN SELECT total_cents FROM orders WHERE tenant_id = 42 AND created_at > NOW() - INTERVAL 1 DAY;
-- Extra: Using index condition                           <- ICP, then a clustered-index lookup per row
ALTER TABLE orders ALTER INDEX tenant_created INVISIBLE;
EXPLAIN SELECT id FROM orders WHERE tenant_id = 42;      -- type: ALL (full scan)
ALTER TABLE orders ALTER INDEX tenant_created VISIBLE;

Common misconceptions ​

BeliefReality
"Index every column used in a WHERE."Every index slows every write and blocks HOT updates; design composite indexes for real query shapes.
"An index on (a, b) helps WHERE b = ?."Only the left prefix narrows the scan; skip scan helps only when a has few distinct values.
"If an index exists, it will be used."The planner picks the cheapest plan; for common values a Seq Scan is correct.
"Index Only Scan never touches the table."PostgreSQL checks the visibility map; non-all-visible pages cost Heap Fetches.
"Indexes only cost disk."They cost WAL, replication, cache, vacuum and write latency.
"VACUUM keeps indexes small."It makes space reusable; bloated indexes need REINDEX CONCURRENTLY.
"CONCURRENTLY is free and safe."Two scans, waits for old transactions, cannot run in a transaction, can leave an INVALID index.
"An INVALID index is harmless."It "will still consume update overhead", and a unique one that failed in the second scan still rejects duplicates.
"Unique index and unique constraint are identical."The constraint can be referenced by FKs and be deferrable; only an index can be partial or on an expression.
"Hash is faster than B-tree for equality."Usually similar; hash cannot do ranges, sorting, uniqueness or index-only scans.
"GIN is just a bigger B-tree."It is inverted (one entry per element), always bitmap-scanned, and has a pending list.
"BRIN works on any column."Only on columns correlated with physical row order.
"An index on email serves lower(email)."Only an expression index on lower(email) matches.
"LIKE 'abc%' always uses a B-tree."Only with C collation or text_pattern_ops; LIKE '%abc' never does (use trigrams).
"idx_scan = 0 means safe to drop."Check replicas, stats resets, and constraint-backing indexes first.
"MySQL and PostgreSQL indexes behave the same."InnoDB clusters by PK and stores the PK in every secondary index.

Cheat sheet ​

TopicWhat to remember
MeasureEXPLAIN (ANALYZE, BUFFERS); compare Rows Removed by Filter, Index Cond, buffers
Scan typesSeq Scan, Index Scan, Index Only Scan (Heap Fetches), Bitmap Index/Heap Scan (Recheck Cond)
Composite orderEquality columns first, then one range/sort column; left prefix only
Skip scanPostgreSQL 18+ B-tree, MySQL Using index for skip scan; only for few leading values
CoveringINCLUDE payload; index-only needs all-visible pages (VACUUM)
PartialWHERE in the index; query must imply it; great for queues and soft deletes
ExpressionIndex exactly the expression the query uses; function must be immutable
UniqueConstraint = rule, index = mechanism; NULLS NOT DISTINCT; 23505 / 1062
TypesB-tree default; Hash =; GIN jsonb/arrays/FTS/trigram; GiST ranges/geo/KNN/EXCLUDE; SP-GiST tries/points; BRIN correlated huge; bloom many-column =
Opclassestext_pattern_ops for LIKE 'x%' in non-C collations; jsonb_path_ops for @>; gin_trgm_ops for %x%
Write costEach index on each insert; non-HOT updates touch all indexes; watch n_tup_hot_upd
BuildCREATE INDEX CONCURRENTLY outside a transaction; check indisvalid; lock_timeout
Maintainidx_scan, last_idx_scan, redundant prefixes, pgstatindex, REINDEX CONCURRENTLY, fillfactor
Testhypopg_create_index, hypopg_hide_index; MySQL INVISIBLE
InnoDBClustered PK, PK in secondaries, Using index, Using index condition (ICP), descending, functional ((expr))
OthersSQL Server clustered/nonclustered/filtered/INCLUDE; Oracle IOT/bitmap; MongoDB ESR; CockroachDB STORING

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A query WHERE tenant_id = ? AND created_at >= ? ORDER BY created_at is slow. Which index do you build and why that column order? Must-know ​

Answer

Answer: (tenant_id, created_at): equality column first so the scan is one slice per tenant, then the range column, which also delivers the ORDER BY without a Sort. See Composite indexes.

2 — The plan says Index Only Scan ... Heap Fetches: 48210. What is wrong and how do you fix it? Important ​

Answer

Answer: Many heap pages are not marked all-visible in the visibility map, so PostgreSQL checks the heap. Run VACUUM (or tune autovacuum for the table); on a write-heavy table an index-only scan may never pay off. See Covering indexes.

3 — When does PostgreSQL choose a Bitmap Heap Scan over an Index Scan? Important ​

Answer

Answer: For medium selectivity, where one random heap read per row would be too many, and when combining indexes with BitmapAnd/BitmapOr. It reads each heap page once in physical order and loses index order. See Bitmap scans.

4 — You have an index on (a, b). Will WHERE b = 5 use it on PostgreSQL 18? Important ​

Answer

Answer: Only through a skip scan, which the planner considers when a has few distinct values; otherwise it is not a left prefix and a Seq Scan (or another index) is used. See Skip scan.

5 — Why does WHERE email LIKE 'ann%' not use the index on email in an en_US.UTF-8 database? Important ​

Answer

Answer: Linguistic collation order is not byte order, so the default operator class cannot turn a prefix into a range. Build the index with text_pattern_ops (or use the C collation). See Operator classes.

6 — CREATE UNIQUE INDEX CONCURRENTLY failed. What state is the database in, and what do you do? Important ​

Answer

Answer: An INVALID index remains: ignored by queries but still costing write overhead, and, if it failed in the second scan, still enforcing uniqueness. Fix the data, DROP INDEX CONCURRENTLY, and rebuild; IF NOT EXISTS would silently skip it. See CONCURRENTLY.

7 — Which index type for payload @> '{"type":"paid"}' on a jsonb column, and which operator class? Good to know ​

Answer

Answer: GIN with jsonb_path_ops: smaller and more precise than the default jsonb_ops, but it does not support the key-exists operators like ?. See GIN.

8 — Why does a long VARCHAR(36) UUID primary key hurt InnoDB more than PostgreSQL? Important ​

Answer

Answer: InnoDB stores the primary key in every secondary index entry and clusters the table by it, so a long random key widens every index and causes page splits. PostgreSQL indexes point to heap TIDs. See InnoDB.

9 — idx_scan = 0 for an index on the primary. Can you drop it? Must-know ​

Answer

Answer: Not yet: check every read replica (statistics are per node), when statistics were last reset, and whether the index backs a unique or primary-key constraint. In MySQL make it invisible first. See Unused indexes.

10 — When is BRIN the right choice, and when is it useless? Important ​

Answer

Answer: Right for huge tables whose column correlates with physical order (append-only timestamps); useless on randomly ordered values, where every block range overlaps the query. See BRIN.

11 — How can you know whether an index would help before spending an hour building it? Must-know ​

Answer

Answer: Create it as a hypothetical index with hypopg_create_index and run EXPLAIN (not ANALYZE) in the same session. See hypopg.

12 — What is the difference between a key column and an INCLUDE column? Important ​

Answer

Answer: Key columns are sorted, searchable and count for uniqueness; INCLUDE columns are stored only in leaf entries so an index-only scan can return them. See Covering indexes.

Glossary ​

TermMeaning
IndexA separate structure, ordered by a key, that points to table rows
HeapPostgreSQL's unordered table storage; rows addressed by TID
TID / ctidTuple identifier: (heap page, item number)
Seq ScanPlan node that reads every table page
Index ScanPlan node that walks an index and fetches each row from the heap
Index Only ScanPlan node that answers from the index, visiting the heap only for non-all-visible pages
Heap FetchesEXPLAIN ANALYZE counter of heap visits during an Index Only Scan
Bitmap Index ScanBuilds an in-memory bitmap of matching row locations from one index
Bitmap Heap ScanReads heap pages listed in a bitmap, in physical order
BitmapAnd / BitmapOrPlan nodes that intersect / union bitmaps from several indexes
Recheck CondCondition re-evaluated on heap rows when a bitmap is lossy or the index is lossy
EXPLAIN (ANALYZE, BUFFERS)Runs the query and shows actual rows and pages hit/read per node
generate_seriesPostgreSQL set-returning function used to create test rows
SelectivityFraction of rows a condition returns; a small fraction (a highly selective condition) favours an index
CardinalityNumber of distinct values in a column (or rows estimated by a plan node)
Composite (multicolumn, concatenated) indexIndex on several columns, sorted by the first, then the next
Left prefix / leftmost prefixThe leading columns of a composite index; only they narrow a B-tree scan
Equality-then-rangeColumn-order rule: = columns first, then one range/sort column
Skip scanRepeated index descents per distinct leading value (PostgreSQL 18+, MySQL, Oracle, SQLite)
Covering indexAn index containing every column a query needs
INCLUDENon-key payload columns stored in B-tree/GiST/SP-GiST leaf entries
Key columnSorted, searchable index column that counts for uniqueness
Visibility mapPer-page bits (all-visible, all-frozen) maintained by VACUUM
All-visiblePage state meaning every tuple is visible to all transactions
Partial indexIndex over rows satisfying a WHERE predicate
Filtered indexSQL Server's name for a partial nonclustered index
Expression indexIndex on the result of an expression, e.g. lower(email)
Functional key partMySQL 8 expression index syntax ((expr))
Unique indexIndex that rejects duplicate keys; the mechanism behind unique constraints
Unique constraintDeclarative rule, enforced by a unique index; can be FK target and deferrable
NULLS NOT DISTINCTPostgreSQL option to treat NULLs as equal in a unique index
B-treeBalanced sorted tree; default index type
Hash indexIndex of 32-bit hash codes; equality only
GINGeneralized Inverted Index: one entry per element (jsonb, arrays, tsvector, trigrams)
fastupdate / gin_pending_list_limitGIN pending-list settings trading insert speed for search consistency
GiSTGeneralized Search Tree for ranges, geometry, nearest neighbour, exclusion constraints
SP-GiSTSpace-partitioned GiST: quad-trees, k-d trees, tries
BRINBlock Range Index: summary (min/max) per range of adjacent pages
pages_per_rangeBRIN storage parameter: pages per summarized range
bloomContrib index access method using per-row Bloom signatures; equality on many columns
Operator class (opclass)Defines which operators an index supports and how values compare
text_pattern_opsB-tree opclass comparing text byte-wise so LIKE 'x%' can use it
CollationRules for text ordering; an index supports one collation per column
jsonb_ops / jsonb_path_opsDefault vs path-hash GIN opclasses for jsonb
pg_trgm / gin_trgm_opsTrigram extension and opclass for LIKE '%x%' and similarity
btree_gistExtension giving GiST opclasses for scalar types, used in exclusion constraints
Exclusion constraintEXCLUDE USING gist (...): no two rows may satisfy the operators together
Full-text searchtsvector/tsquery search, indexed with GIN; see the full-text page
Write amplificationOne logical write causing many physical writes (heap, each index, WAL)
HOT (heap-only tuple)PostgreSQL update that touches no index because no indexed column changed
fillfactorHow full pages are packed at build time; B-tree default 90
DeduplicationB-tree storing equal keys once with a posting list (deduplicate_items)
Bottom-up index deletionB-tree removal of old versions' entries before a page split
Index bloatIndex much larger than its live data (empty/sparse pages)
REINDEX CONCURRENTLYRebuilds an index without blocking writes; leftover _ccnew on failure
CREATE INDEX CONCURRENTLYBuilds an index with two table scans, without blocking writes
INVALID indexIndex left by a failed concurrent build; pg_index.indisvalid = false
indisvalid / indisreadyCatalog flags: usable by queries / maintained by writes
maintenance_work_memMemory for index builds and VACUUM
pg_stat_user_indexesPer-index statistics view: idx_scan, last_idx_scan, idx_tup_read, idx_tup_fetch
idx_scanNumber of index scans initiated on an index
Duplicate indexIndex identical to another on the same table
Redundant indexIndex whose columns are a left prefix of another B-tree
hypopgExtension for hypothetical (virtual) indexes seen only by EXPLAIN
hypopg_create_index / hypopg_hide_indexCreate a hypothetical index / hide a real one in the session
pgstattuple / pgstatindexExtension and function reporting index density and fragmentation
amcheckExtension verifying B-tree structure and ordering
random_page_costPlanner cost of a random page read (default 4); lower on SSDs
Clustered indexIndex that stores the table rows in key order (InnoDB PK, SQL Server)
Secondary indexAny non-clustered index; in InnoDB its entries hold the primary key
Nonclustered indexSQL Server secondary index pointing to the clustered key or RID
GEN_CLUST_INDEXHidden InnoDB clustered index when a table has no PK or suitable unique key
Index Condition Pushdown (ICP)InnoDB check of index columns before reading the full row (Using index condition)
Using indexMySQL EXPLAIN note for a covering index
Index MergeMySQL combination of several indexes (intersect, union, sort_union)
Invisible indexMySQL index ignored by the optimizer but still maintained
Descending indexIndex stored in descending key order (MySQL 8, PostgreSQL DESC)
Index-organized table (IOT)Oracle table stored in its primary-key B-tree
Bitmap indexOracle index storing a bitmap per key value; for warehouses
STORINGCockroachDB's equivalent of INCLUDE
ESR guidelineMongoDB compound index order: Equality, Sort, Range
Online index buildBuilding without blocking writes: CONCURRENTLY, ONLINE = ON, ALGORITHM=INPLACE, LOCK=NONE
online() / inplace()Laravel 13 index modifiers for PostgreSQL/SQL Server and MySQL online builds
$withinTransactionLaravel migration property; false lets CONCURRENTLY run
rawIndexLaravel Blueprint method for an index on a raw expression

References ​

Built by Morteza Negahi