Summary#
An index is an extra data structure that lets the database find rows without scanning the whole table, turning a query over 100 million rows from seconds into about a millisecond. The default is the B-tree, which supports equality, ranges and sorting. Hash indexes do only equality. Composite indexes cover several columns, and their column order decides which queries they help. A covering index contains every column a query needs, so the table is never touched. Clustered indexes store the rows themselves in key order; secondary indexes point to them. Special indexes handle full-text (inverted index) and geospatial data. Every index slows writes and uses storage, so index for your real queries and check with EXPLAIN.
Why It Exists#
Without an index, finding WHERE email = 'a@b.com' means reading every row: a full table scan. On a 50 GB table, that is gigabytes of I/O per query. With a B-tree index, the database reads 3-4 pages to find the row. Indexes are usually the single biggest performance lever in a database, and missing indexes are the most common cause of slow queries. This page builds on Data Modeling: the access patterns you listed there decide which indexes you need.
How It Works#
B-tree index#
A B-tree (in practice a B+ tree) is a balanced tree of fixed-size pages (8 KB in PostgreSQL, 16 KB in MySQL InnoDB). Each internal page holds hundreds of sorted keys pointing to child pages; leaf pages hold keys with pointers to rows (or the rows themselves) and are linked to their neighbours.
Because each page fans out to hundreds of children, a tree only 3-4 levels deep covers hundreds of millions of keys, and the top levels usually sit in memory. A lookup reads one page per level: O(log n). Since keys are sorted and leaves are linked, B-trees also serve range queries (created_at > '2026-11-01'), prefix matches (LIKE 'abc%') and ORDER BY without a separate sort.
B-tree index in depth#
Where rows live without an index. In many databases the table itself is a heap file: rows are written into pages in roughly the order they arrive, with no sorting, like a notebook where each new entry goes on the next free line. Finding a row by any value other than its physical position means reading the whole notebook. An index is a second, sorted structure built on the side that says where to look.
The rules that keep a B-tree balanced. A B-tree of order m follows a few strict rules:
- All leaf pages sit at the same depth, so every lookup takes the same number of steps.
- Each node (except the root) holds between m/2 and m keys, so pages stay at least half full.
- A node with k keys has exactly k + 1 children. The keys are the dividing lines between the children's ranges.
- Keys inside a node stay sorted, so the database can binary-search inside a page.
Rudolf Bayer and Edward McCreight introduced the structure in "Organization and Maintenance of Large Ordered Indexes" (Acta Informatica, 1972). Douglas Comer's 1979 survey "The Ubiquitous B-Tree" showed how quickly it had become the standard. Real databases use the B+ tree variant. Internal pages hold only keys and child pointers, and all entries live in the leaves, which are linked left to right. Keeping internal pages lean raises the fan-out, and the linked leaves make range scans a simple walk along one level.
Fan-out math: why 3 or 4 levels are enough. Suppose an 8 KB page and an index on a bigint column. Each internal entry is roughly the key (8 bytes) plus a child pointer and some overhead, about 16 to 20 bytes in total. So one page holds about 400 entries. With a fan-out of 400:
| Levels | Keys reachable |
|---|---|
| 1 (root only) | about 400 |
| 2 | 400 × 400 = 160,000 |
| 3 | 64 million |
| 4 | about 25 billion |
A table of a few hundred million rows needs a 4-level index. The root and the second level together are only a few hundred pages, a few megabytes, so they stay in memory permanently. A lookup therefore costs about one or two real page reads, the lower internal page and the leaf, plus one more read for the row itself if the index does not cover the query. This is why a lookup by indexed key takes well under a millisecond on a warm cache and only a few milliseconds when the pages must come from SSD. Wider keys lower the fan-out. A 100-byte text key fits about 70 entries per page, so the tree gets one level deeper sooner. That is one concrete reason to prefer compact keys.
What happens on insert: page splits. A new key goes into its sorted position in a leaf. If the leaf is full, the database splits it. It allocates a new page, moves about half the entries there, and adds a separator key to the parent. If the parent is full too, the split moves upward. A split at the root is the only way the tree grows taller, which is how it stays balanced. Two insert patterns behave very differently:
- Increasing keys (auto-increment, time-ordered IDs, timestamps) always land in the rightmost leaf. Databases detect this and split "at the end", leaving the old page full. Pages stay densely packed, and only one leaf is hot.
- Random keys (UUID v4, hashes, emails) land in random leaves. Splits happen all over the tree and leave pages about half full, so the index ends up larger, and its working set is the whole tree rather than one edge.
Fill factor sets how full pages are packed when an index is built or rebuilt, for example WITH (fillfactor = 90) in PostgreSQL. Leaving some free space means later inserts and updates into the middle of the key range cause fewer splits. Deletes leave gaps that the database reclaims slowly. Over months, a heavily updated index can become bloated, much larger than its live data, and REINDEX CONCURRENTLY (PostgreSQL 12+) rebuilds it online.
Concurrency inside the tree. Many sessions read and write the same index at once. Holding a lock on the whole tree would serialise everything. Lehman and Yao's 1981 paper "Efficient Locking for Concurrent Operations on B-Trees" (ACM Transactions on Database Systems) added a "right-link" pointer from each node to its sibling, plus a high key. A reader that arrives during a split can follow the right-link to find keys that just moved. PostgreSQL's B-tree implementation is based on this design. Other engines use short-lived page latches taken top-down, called latch coupling. Either way, contention mostly appears on hot pages, such as the rightmost leaf under very high insert rates.
B-trees in real databases. PostgreSQL uses B-trees for primary keys, UNIQUE constraints and every CREATE INDEX that does not name another type. A table defined as users(id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE) gets two B-trees automatically, one per constraint. The uniqueness check itself is a B-tree lookup: before inserting, the database searches for the key and fails if it is there. MySQL InnoDB stores both the table and its secondary indexes as B+ trees. MongoDB indexes are B-trees too: db.users.createIndex({ "email": 1 }) builds a sorted tree from email values to document locations, where 1 means ascending. In DynamoDB, items in a partition are kept in sort-key order, which is what makes sort-key range queries cheap. AWS does not document its storage engine in detail, so treat any claim about it as informed guesswork.
Why B-trees are the default. They handle almost everything an application asks:
- Equality (
email = 'x') and ranges (age > 25,created_at BETWEEN ...) with the same structure. - Sorted output for
ORDER BYandLIMITwithout a separate sort step. - Prefix matches such as
LIKE 'abc%', given the right collation or operator class. - Predictable performance at any size, because the tree stays balanced under random inserts and deletes.
- A good match to disk, because each node is one page.
If you need an index in an interview and nothing special is going on, say "a B-tree on these columns".
When B-trees are not enough: LSM-tree indexes#
Consider a metrics platform ingesting millions of data points per second from thousands of servers: CPU readings, memory stats, error counts. Every write must be stored right away. A B-tree index would turn that stream into random page updates all over the tree, each needing a read-modify-write of an 8 KB or 16 KB page. The log-structured merge tree (LSM tree) avoids this. It was described by O'Neil, Cheng, Gawlick and O'Neil in "The Log-Structured Merge-Tree (LSM-Tree)" (Acta Informatica, 1996).
- Writes go to an append-only log (for durability) and to a sorted in-memory table, the memtable.
- When the memtable reaches a size limit (tens of megabytes), it is written to disk as an immutable sorted file, an SSTable (sorted string table), in one sequential write.
- Background compaction merges SSTables, dropping overwritten and deleted entries, so the number of files stays manageable.
Writes become sequential and cheap, which is why Cassandra, ScyllaDB, HBase, RocksDB and many time-series engines are built this way. The cost lands on reads. A key may live in the memtable or in any of several SSTables, so a lookup may check multiple files. Bloom filters (a compact probabilistic "definitely not here / maybe here" check per file) let most files be skipped, and compaction keeps the file count down. Range scans must merge results from several files. Compaction also uses disk bandwidth that competes with foreground traffic. The rough rule is: B-trees for read-heavy, mixed workloads; LSM trees when write throughput dominates. See Storage Engines for the full comparison.
Hash index#
A hash index stores a hash of each key in buckets. It answers only equality (WHERE token = ?) in O(1), with no ranges or sorting. PostgreSQL supports hash indexes, but B-trees are nearly as fast for equality and more flexible, so B-trees remain the default. Hash indexing matters more in key-value stores and in-memory engines.
Hash index in depth#
How it works. A hash index runs each key through a hash function that turns it into a number, then uses that number to pick a bucket. Each bucket holds entries pointing to the rows whose keys hashed there. A lookup hashes the search value, goes straight to one bucket and checks the few entries in it, so the cost is constant however large the table gets. When buckets fill up, entries spill into overflow pages, or the index grows by splitting buckets. PostgreSQL uses a form of linear hashing that splits one bucket at a time, so the index never has to rebuild everything at once.
What it cannot do. Hashing destroys order by design. user_1001 and user_1002 land in unrelated buckets. So a hash index cannot answer ranges (> 100), prefixes (LIKE 'ab%'), ORDER BY or MIN and MAX, and it cannot enforce uniqueness across a composite key in most engines. It cannot combine columns either: a hash of (a, b) is useless for a query on a alone.
Where hash indexes really matter.
- In-memory key-value stores. Redis keeps its whole keyspace in an in-memory hash table. To avoid a long pause when the table must grow, it rehashes incrementally. It keeps both the old and the new table and moves a few buckets on each operation until the move is done.
- Log-structured stores with an in-memory index. Bitcask, the storage engine behind Riak, keeps every key in an in-memory hash map that points to the key's latest position in an append-only file. Reads cost one disk seek, and writes are pure appends. The catch is that all keys must fit in RAM.
- Inside relational engines. MySQL's MEMORY engine uses hash indexes by default. InnoDB builds an adaptive hash index automatically: it watches for B-tree pages that are searched repeatedly by equality and adds an in-memory hash shortcut for them. Hash joins build a temporary hash table on the join key at query time, a different use of the same idea.
- PostgreSQL hash indexes. They exist, but before PostgreSQL 10 they were not written to the write-ahead log, so they were not crash-safe and were not replicated. Since version 10 they are safe. They can be smaller and slightly faster than a B-tree for equality on long keys, such as long URLs or tokens, because they store a 4-byte hash instead of the full value. In most cases a B-tree is still the practical choice, because it is nearly as fast and supports far more query types.
When to choose a hash index. All of these should hold: the only query is exact equality; the keys are long or the lookup rate is extreme; and you will never need ranges or sorting on the column. Session tokens, API keys, cache keys and content hashes fit. Timestamps, prices and names do not.
Composite indexes and column order#
A composite (multi-column) index sorts by the first column, then by the second within equal first values, and so on, like a phone book sorted by last name, then first name.
CREATE INDEX idx_orders_cust_status_created
ON orders (customer_id, status, created_at DESC);
-- Uses the index fully: equality on leading columns, then the sort column
SELECT * FROM orders WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC LIMIT 20;
-- Uses only the first column (customer_id)
SELECT * FROM orders WHERE customer_id = 42 AND created_at > now() - interval '7 days';
-- Cannot use it efficiently: the leading column is missing
SELECT * FROM orders WHERE status = 'paid';Rules for column order:
- Leftmost prefix: an index on (A, B, C) helps queries on A, A+B and A+B+C, not B or C alone.
- Equality columns first, then range or sort columns. A range on a middle column stops later columns being used for seeking.
- Among equality columns, put the one used by more queries first.
Composite indexes in depth#
A worked example. An events site needs "events in San Francisco on 25 December". With separate single-column indexes on city and date, the database has two poor options. It can use the city index, fetch all San Francisco events (perhaps 200,000 rows over the years), and filter by date. Or it can use the date index, fetch every event worldwide on that day (perhaps 30,000), and filter by city. PostgreSQL has a third option. It can scan both indexes into in-memory bitmaps of matching row positions and AND them together (a BitmapAnd), then fetch only the rows in both. That is better, but it still reads two large index ranges. A composite index on (city, date) jumps straight to the tiny slice where both match: maybe 40 rows, read from one contiguous range of leaf pages.
Why order matters, with numbers. Think of the composite index as sorted by city, and by date within each city.
| Query | Index (city, date) | Index (date, city) |
|---|---|---|
city = 'SF' AND date = '2026-12-25' | Seek, about 40 entries | Seek, about 40 entries |
city = 'SF' AND date BETWEEN '2026-12-01' AND '2026-12-31' | Seek, one range of about 1,200 entries | Reads every city's entries for 31 days (about 900,000) and filters |
city = 'SF' | Seek, one range | Cannot seek. Full index scan or another index |
date = '2026-12-25' | Cannot seek | Seek |
The second row shows the key rule. Once a column is compared by range, the columns after it can no longer be used for seeking, only for filtering. With (date, city), the date range pulls in every city on those dates, and the city check happens entry by entry. Put equality columns first and the range column last.
Sort direction and ORDER BY. An index can serve ORDER BY a, b read forwards, or ORDER BY a DESC, b DESC read backwards. A mixed order such as ORDER BY a ASC, b DESC needs the index to be declared with those directions: (a ASC, b DESC). For "a user's newest orders", (user_id, created_at DESC) returns rows in exactly the order the query wants, so LIMIT 20 stops after 20 entries.
Common myths.
- "Put the most selective column first." That helps only when the columns are compared with equality and the queries use both. What really matters is which queries need to seek on which prefix. A less selective column that every query filters on usually belongs first.
- "Many single-column indexes are as good as one composite index." Combining indexes with bitmaps or index merges works, but it reads more, cannot return rows already sorted, and cannot cover the query.
- "A composite index replaces the single-column one." Yes for the leading column:
(a, b)serves queries ona, so a separate index on(a)is usually redundant. No forb.
Skip scan. Some engines can use an index whose leading column is missing, when that column has few distinct values. Oracle and MySQL (from 8.0.13) can do this. The engine jumps to each distinct leading value in turn and seeks on the second column within it. On (gender, birth_date) with two genders, a query on birth_date becomes two seeks. It is a useful fallback, not a design goal: with thousands of leading values, it is slower than a proper index.
How many columns? Every extra column makes each entry wider, lowering fan-out and raising write cost. Two or three key columns is typical. Columns needed only in the output belong in INCLUDE, not in the key. A good habit is to write the five most frequent queries next to each other and find the fewest indexes whose leftmost prefixes serve them all.
Covering index#
If an index contains every column the query reads, the database answers from the index alone (an index-only scan) without fetching table rows, saving one random read per row.
-- PostgreSQL 11+ / SQL Server: INCLUDE adds non-key columns to the leaf pages
CREATE INDEX idx_orders_cust_created_cover
ON orders (customer_id, created_at DESC) INCLUDE (status, total_cents);Covering indexes are a strong tool for hot list queries, at the cost of a larger index.
Covering indexes in depth#
What a covering index saves. For a list of 20 orders, a normal index scan finds 20 index entries, then makes 20 separate trips to the table to fetch each row. Those trips are random reads. On a cold cache, at about 0.1 ms each on a fast NVMe SSD, that is 2 ms of I/O on top of the index read. On network-attached cloud disks at 0.5 to 1 ms each, it is 10 to 20 ms. If the index already holds every column the query selects, filters and sorts on, those trips disappear.
Key columns vs included columns. There are two ways to make an index cover a query:
- Add the extra columns to the key:
(customer_id, created_at, status, total_cents). They are then sorted and stored at every level of the tree, including internal pages, which makes those pages fatter. - Include them:
(customer_id, created_at) INCLUDE (status, total_cents). Included columns are stored only in leaf pages and are not sorted, so internal pages stay lean. They cannot be used to seek or sort, only to return values. PostgreSQL 11+ and SQL Server supportINCLUDE. In MySQL you add the columns to the key.
InnoDB covers more than you might think. Every InnoDB secondary index entry already stores the row's primary key. So an index on (email) covers SELECT id FROM users WHERE email = ? without any extra columns.
PostgreSQL's catch: the visibility map. PostgreSQL index entries carry no transaction visibility information. The planner can only skip the table if the visibility map marks the page as "all rows visible to everyone". On a table with heavy recent updates, many pages are not yet marked, so an "Index Only Scan" still visits the heap. EXPLAIN ANALYZE shows this as Heap Fetches. VACUUM sets the visibility bits, so covering indexes work best on tables that autovacuum keeps up with.
When not to cover. Covering wide text columns makes the index nearly as large as the table, and it adds write cost on every update of those columns. Cover the narrow columns of a hot list query: IDs, status, amounts, timestamps. Fetch large fields only for the one row a user clicks.
Clustered vs secondary indexes#
- A clustered index stores the table's rows inside the index, in key order. A table has at most one. In MySQL InnoDB, the primary key is always the clustered index; rows with nearby keys sit on the same pages, so primary-key ranges are fast.
- A secondary index stores keys plus a pointer to the row. In InnoDB that pointer is the primary key, so a secondary lookup is two B-tree searches (secondary, then clustered). In PostgreSQL, all indexes are secondary: rows live in an unordered heap and every index points to a physical row location.
Consequences: in InnoDB, keep primary keys small (they are copied into every secondary index) and roughly increasing (random UUIDv4 keys cause page splits and scattered writes; time-ordered IDs such as UUIDv7 or Snowflake IDs avoid this). See Unique ID Generation.
Clustered vs secondary indexes in depth#
Two lookups vs one. In InnoDB, a query by a secondary index such as WHERE email = ? first searches the email B-tree, which yields a primary key, then searches the clustered primary-key B-tree to reach the row. Each search is 3 or 4 levels, mostly cached. In PostgreSQL, every index entry holds a tuple ID (ctid, a page number plus slot), so the second step is a direct page read rather than a tree search. Each design has a cost:
| InnoDB (clustered primary key) | PostgreSQL (heap + secondary indexes) | |
|---|---|---|
| Primary-key range scan | Very fast: rows are physically adjacent | Rows are scattered unless the table was loaded in key order |
| Secondary lookup | Two tree searches | One tree search + one heap page |
| Row moves on update | Secondary indexes unaffected, because they store the primary key | A new row version gets a new ctid. Every index needs a new entry unless the update is HOT. |
| Primary-key width matters | A lot: it is copied into every secondary index | Less |
Why primary-key width matters in InnoDB. Each secondary index entry stores the full primary key. Take a table with 1 billion rows and 5 secondary indexes. Using a 16-byte UUID instead of an 8-byte bigint adds 8 bytes × 5 indexes × 1 billion rows, about 40 GB of extra index data, before counting the clustered index itself. Extra index size means more memory needed to keep the hot parts cached.
PostgreSQL HOT updates. When an update changes no indexed column and the new row version fits on the same page, PostgreSQL makes a heap-only tuple (HOT) update. The new version is chained from the old one on the page, and no index is touched. This is why adding an index on a frequently updated column, such as last_seen_at, can suddenly multiply write cost: those updates stop being HOT. Leaving free space with a lower table fill factor makes HOT updates more likely.
Getting clustering benefits elsewhere. PostgreSQL's CLUSTER command rewrites a table once in index order, but it takes a heavy lock, and the order decays as new rows arrive. The planner tracks a per-column correlation statistic, which measures how closely physical order follows column order, and uses it to cost index scans. Oracle offers index-organized tables. SQL Server lets you pick which index is clustered, usually the primary key. In LSM-based stores such as Cassandra, rows inside a partition are always stored sorted by clustering key, which is clustering by design.
Secondary indexes in a key-value store: DynamoDB. Without SQL, the same distinction appears as two index types.
- A global secondary index (GSI) has its own partition key and is stored on its own partitions, effectively a separate table that DynamoDB maintains for you. It is updated asynchronously, so reads from it are eventually consistent. It has its own throughput, can be added or removed at any time, and a table can have up to 20.
- A local secondary index (LSI) keeps the table's partition key but adds a different sort key. It is stored alongside the base items and updated synchronously, so strongly consistent reads are possible. It shares the table's throughput, limits each partition key's data to 10 GB, must be defined when the table is created, and a table can have at most 5.
A chat table keyed by chat_id and message_id would add a GSI on (user_id, message_id) for "all messages a user sent". It could add an LSI on num_attachments for "messages with the most attachments in this chat". See Amazon DynamoDB in Practice.
Full-text and inverted indexes#
B-trees cannot efficiently answer "documents containing the word latency" because the word may be anywhere in the text. An inverted index maps each term to the list of documents (and positions) containing it, after tokenising (splitting into words), lowercasing and stemming ("caching" to "cach"). Search engines add relevance scoring such as BM25.
-- PostgreSQL full-text search with a GIN (inverted) index
CREATE INDEX idx_posts_fts ON posts USING GIN (to_tsvector('english', body));
SELECT id FROM posts WHERE to_tsvector('english', body) @@ to_tsquery('cache & invalidation');Built-in full-text search suits moderate needs; for large-scale search with ranking, facets and typo tolerance, use a search engine. See Elasticsearch.
Full-text and inverted indexes in depth#
From text to terms. Before anything is indexed, an analyzer turns raw text into terms:
- Tokenise: split on spaces and punctuation, so "Caching at scale, explained" becomes
caching,at,scale,explained. - Normalise: lowercase the terms and strip accents.
- Remove stop words (optional): drop very common words such as "at" and "the".
- Stem or lemmatise: reduce words to a root, so "caching", "cached" and "caches" all become
cach.
The query text goes through the same analyzer, so a search for "Cached" matches a document containing "caching". Most "why doesn't search find this?" bugs come from the document and the query being analysed differently.
Posting lists. The index maps each term to a posting list: the sorted IDs of documents containing it, often with term counts and word positions.
A query for "cache AND scale" fetches two posting lists and intersects them. Because both are sorted, this is a merge in one pass. Search engines also store skip pointers so a list of millions of IDs can be jumped through rather than read entry by entry. Posting lists are compressed by storing the gaps between IDs (5, 12, 13 becomes 5, 7, 1) in variable-length bytes, so frequent terms take up little space. Storing positions allows phrase queries ("cache invalidation" as adjacent words) and proximity scoring.
Ranking. Matching is not enough; users want the best results first. The classic scoring idea is that a term counts for more when it appears often in this document (term frequency) and rarely across all documents (inverse document frequency). A match on "invalidation" says more than a match on "data". BM25, the default in Lucene, Elasticsearch and OpenSearch, refines this. Extra occurrences of a term give diminishing returns, and matches in short documents score higher than the same match in a long one.
How search engines keep the index fresh. Lucene, the library under Elasticsearch, OpenSearch and Solr, writes new documents into small immutable segments and merges them in the background, much like LSM compaction. A document becomes searchable after a refresh that opens a new segment, by default about once a second in Elasticsearch. That is why search is called "near real time".
Full-text inside PostgreSQL. A GIN (generalised inverted index) over a tsvector column gives real inverted-index search with stemming and ranking via ts_rank. GIN updates are expensive, so PostgreSQL buffers new entries in a pending list (the fastupdate option) and merges them in bulk. For substring and fuzzy matching (LIKE '%nation%', typo-tolerant search), the pg_trgm extension indexes three-character fragments, called trigrams, with GIN or GiST. A plain B-tree cannot help with a leading wildcard.
When to move search out of the main database. Built-in full-text search is fine for a few million documents with simple ranking. For large corpora, rich relevance tuning, facets, typo tolerance, autocomplete or many languages, use Elasticsearch or OpenSearch. The usual design keeps the main database as the source of truth and streams changes into the search index with change data capture. The index lags the database by a second or a few, so a just-edited post may briefly show its old text in search results. For search this small staleness is almost always acceptable, and in return users can search in ways the main database cannot support.
Geospatial index#
"Find restaurants within 2 km" needs two-dimensional proximity, which a B-tree on latitude alone handles poorly. Options:
- R-tree (PostGIS uses GiST indexes for this): groups nearby shapes into nested bounding boxes.
- Geohash: encodes a location as a string where a shared prefix means nearby, so a normal B-tree can search prefixes.
- Cell systems (Google S2, Uber H3): divide the earth into cells with IDs that can be indexed and compared.
See Geospatial Indexing.
Geospatial indexes in depth#
Why two B-trees do not solve it. "Restaurants within 2 km of me" is a condition on two dimensions at once. With a B-tree on lat and another on lng, the database can find everything in a latitude band (a strip around the whole planet) or a longitude band (a strip from pole to pole). Then it must intersect two huge sets to find the small square where they cross. A composite index on (lat, lng) does not help much either, because a range on lat stops lng from being used for seeking. What is needed is an ordering where points close on the map are close in the index.
Geohash: turning 2D into a sortable string. A geohash repeatedly halves the world. The first bit says east or west of the prime meridian, the next says north or south of the equator, then east or west within that half, and so on, alternating. The interleaved bits are written in base-32, so each character adds 5 more halvings. Two places that share a long prefix are inside the same small cell. Approximate cell sizes:
| Geohash length | Cell size (approx.) |
|---|---|
| 4 | 39 km × 20 km |
| 5 | 4.9 km × 4.9 km |
| 6 | 1.2 km × 0.6 km |
| 7 | 153 m × 153 m |
Because a geohash is a string, an ordinary B-tree, or a sorted set in Redis, can index it, and "all points in this cell" becomes a prefix range scan. The weak spot is edges. Two restaurants 20 metres apart can sit on opposite sides of a cell boundary and share no prefix. So a radius search looks up the user's cell plus its 8 neighbours, then computes the true distance for each candidate and drops those outside the radius. Redis's GEOADD and GEOSEARCH store 52-bit geohash scores in a sorted set and work in exactly this way.
Quadtree: cells that adapt to density. A quadtree starts with one square covering the map and splits any square holding more than N points (say 100) into four quarters, recursively. Dense downtown areas end up with many tiny cells, and empty desert stays as a few large ones. A query walks down to the cells that overlap the search circle. Quadtrees are usually built in memory by a location service and rebuilt or patched as points move. They suit read-heavy data, such as business listings, more than fast-moving data.
R-tree: nested bounding boxes. An R-tree, introduced by Antonin Guttman in "R-Trees: A Dynamic Index Structure for Spatial Searching" (SIGMOD 1984), works like a B-tree for rectangles. Each leaf holds shapes, or points, along with their bounding boxes. Each internal node stores the smallest rectangle enclosing all its children. A search descends only into nodes whose rectangles overlap the query area. Unlike geohashes, R-trees handle shapes as well as points, such as delivery zones, parcels and road segments. They answer "which polygon contains this point" and "what intersects this line". PostGIS builds R-tree-like indexes on GiST in PostgreSQL. Its ST_DWithin function uses the index to fetch candidates and then checks exact distances.
Cell systems: S2 and H3. Google's S2 projects the sphere onto the six faces of a cube and orders cells along a space-filling (Hilbert) curve. Uber's H3 tiles the globe with hexagons at 16 resolutions. Hexagons have a useful property: all 6 neighbours are the same distance from the centre, which makes "nearby" and smoothing calculations more even. Both give each cell a 64-bit ID that any key-value store or B-tree can index.
Choosing.
| Need | Good fit |
|---|---|
| Points near a location, inside an existing database | PostGIS (GiST) or a geohash column with a B-tree |
| Very high-rate updates of moving points (drivers) | Redis GEO, or in-memory geohash or H3 buckets |
| Shapes and polygons: zones, parcels | PostGIS R-tree (GiST) |
| Uneven density, read-mostly | Quadtree in a location service |
| Analytics over regions, even neighbour distances | H3 or S2 cell IDs |
See Geospatial Indexing for full designs, such as proximity search for a ride-hailing app.
Write and storage cost#
Each index is another structure to update on every insert, update of an indexed column, and delete. A table with 8 indexes writes about 9 structures per insert, adding latency and I/O, and each B-tree update can split pages. Indexes also take space (often 10-30% of the table each, more for covering indexes), compete for memory in the buffer pool, and slow bulk loads. Unused indexes cost writes for no benefit.
Write and storage cost in depth#
What one insert really writes. Take an orders table with a primary key and 6 secondary indexes. One insert writes the row, 7 index entries (each a leaf page that may split), and a write-ahead log record for every one of those changes. On a busy table doing 5,000 inserts a second, the indexes, not the row, are most of the I/O. Updates are cheaper only when they avoid indexed columns. In PostgreSQL, an update that touches an indexed column writes a new entry in every index on the table, not just the changed one, unless the update qualifies as HOT.
Storage. A B-tree on one bigint column is roughly 20 to 30 bytes per row once page overhead and free space are included. At 1 billion rows that is 20 to 30 GB per index. A composite or covering index with text columns can approach the size of the table. It is common to find tables whose indexes take more space than the data itself.
Memory. Indexes compete with table data for the buffer pool. Fears about this are often overblown. Databases cache pages, not whole indexes, and only the hot parts of an index stay in memory. An index on recent timestamps keeps only its right edge hot. A random-key index, or one scanned broadly, keeps far more pages hot. Watch the cache hit ratio and index usage rather than guessing.
The classic case where indexes hurt. A logging or audit table that takes 20,000 inserts a second and is read only by occasional bulk exports gains almost nothing from secondary indexes, but pays for them on every insert. Keep the primary key (often time-ordered), partition by day, and add a cheap BRIN index on the timestamp (see below) instead of a B-tree. Small lookup tables of a few hundred rows also rarely need secondary indexes. Scanning one or two pages costs less than walking a tree.
Finding indexes to drop. In PostgreSQL, pg_stat_user_indexes.idx_scan counts how often each index has been used since statistics were last reset. An index with zero scans over a full business cycle (including month-end jobs) is a candidate for removal. Also look for duplicates: two indexes with the same leading columns, or an index on (a) next to one on (a, b). MySQL's sys.schema_unused_indexes view gives a similar list.
When not to index#
- Small tables (a few thousand rows): a scan is already fast.
- Low-selectivity columns on their own: a boolean or a status with 3 values matches too many rows; the database will often scan anyway. (A partial index such as
WHERE status = 'pending'can still help when the filtered subset is small.) - Write-heavy tables where the column is rarely queried.
- Columns wrapped in functions in queries (
WHERE lower(email) = ...) unless you create an expression index on that function.
When not to index, in depth#
Selectivity in numbers. Selectivity is the fraction of rows a condition matches. The planner compares two costs. An index scan reads a few index pages plus one random table read per matching row. A sequential scan reads every table page in order. PostgreSQL's default cost settings price a random page read at 4 times a sequential one (random_page_cost = 4, seq_page_cost = 1). On SSDs, many teams lower random_page_cost to about 1.1 to 1.5. Take a 1-million-row table on 25,000 pages. A condition matching 1% (10,000 rows) costs up to 10,000 random reads through the index, against 25,000 sequential reads for the scan, so the index wins. At 10% (100,000 rows), the index path costs far more than the scan, and the planner correctly ignores the index. This is why an index on a boolean column is usually useless for the common value.
Partial indexes: index only the rows you query. If only 0.5% of orders are pending and a worker polls for them constantly, CREATE INDEX ON orders (created_at) WHERE status = 'pending' gives a tiny index that only covers rows in that state. It is cheap to maintain, because rows leave the index when they change state. The query must include the same condition for the planner to use it.
Expression indexes. WHERE lower(email) = ? cannot use an index on email, because the index stores the original values. Create the index on the expression instead: CREATE INDEX ON users (lower(email)). The same applies to date truncation, JSON field extraction and type casts. A hidden cast, such as comparing a text column to a number, is a classic reason an index is "mysteriously" not used.
BRIN: tiny indexes for naturally ordered data. A block range index (BRIN) in PostgreSQL stores only the minimum and maximum value for each range of pages, 128 by default. On an append-only table where created_at grows with physical position, a BRIN index of a few hundred kilobytes can replace a B-tree of many gigabytes for time-range queries. The planner reads only the page ranges whose min-max bounds overlap the query. BRIN is useless when values are not correlated with physical order.
Reading EXPLAIN#
EXPLAIN shows the plan the optimizer chose; EXPLAIN ANALYZE runs the query and shows real timings and row counts (careful: it executes writes too).
-- Before indexing: scans the whole table
Seq Scan on orders (cost=0.00..412000.00 rows=1200 width=24) (actual time=0.02..2150.4 rows=1187)
Filter: (customer_id = 42)
Rows Removed by Filter: 19998813
-- After CREATE INDEX on (customer_id, created_at DESC)
Limit (actual time=0.031..0.058 rows=20)
-> Index Scan using idx_orders_cust_created on orders (actual time=0.030..0.054 rows=20)
Index Cond: (customer_id = 42)
Execution Time: 0.075 msWhat to look for:
- Seq Scan on a large table with a selective filter: a missing index.
- Rows Removed by Filter much larger than rows returned: the index does not match the filter.
- Estimated vs actual rows far apart: stale statistics; run
ANALYZE. - Sort steps on large inputs: an index in the right order could avoid them.
- Index Only Scan with low heap fetches: a covering index working as intended.
Reading EXPLAIN in depth#
Plans are trees, read inside out. Each line of a PostgreSQL plan is a node. Indented child nodes run first and feed their rows to the parent. The innermost nodes are access methods, which say how rows are fetched from a table. The outer ones combine rows: joins, sorts, aggregates and limits.
| Node | What it means | Usually good or bad? |
|---|---|---|
| Seq Scan | Read every page of the table | Fine for small tables or large result shares. Suspicious for a selective filter on a big table. |
| Index Scan | Walk the index, fetch each matching row from the table | Good for few rows |
| Index Only Scan | Answer from the index, with Heap Fetches showing table visits | Best for hot lists |
| Bitmap Index Scan + Bitmap Heap Scan | Collect matching row positions, then read table pages in physical order | Good for medium result sets or for combining indexes |
| Nested Loop | For each outer row, look up matching inner rows | Great when the outer side is small and the inner side is indexed |
| Hash Join | Build a hash table on one side, probe with the other | Good for large unsorted joins. Needs memory (work_mem). |
| Merge Join | Walk two inputs sorted on the join key | Good when both sides come pre-sorted from indexes |
| Sort | Sort rows in memory, or on disk if too big | Watch for "external merge Disk" lines |
Cost numbers. cost=0.43..8.45 shows the startup cost (before the first row) and the total cost, in arbitrary units based on seq_page_cost = 1. These are estimates for comparing plans, not milliseconds. rows= is the planner's estimate. With EXPLAIN ANALYZE, each node also shows actual time in milliseconds, actual rows, and loops, the number of times the node ran. A node's real total is roughly the per-loop time multiplied by loops, which is how an innocent-looking inner index scan inside a nested loop turns into seconds.
Add BUFFERS. EXPLAIN (ANALYZE, BUFFERS) reports page reads per node. shared hit counts pages found in memory and read counts pages fetched from disk or the OS cache. A query that is fast only when warm shows mostly hits on the second run and many reads on the first. That is the difference between a 2 ms benchmark and a 200 ms production request.
A diagnostic walk-through. A list endpoint has slowed down. The plan shows:
Limit (actual time=812.4..812.5 rows=20 loops=1)
-> Sort (actual time=812.4..812.4 rows=20 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 27kB
-> Bitmap Heap Scan on orders (actual time=35.1..790.2 rows=48210 loops=1)
Recheck Cond: (customer_id = 7)
Heap Blocks: exact=41877
Buffers: shared hit=1204 read=40890
-> Bitmap Index Scan on idx_orders_customer (rows=48210 loops=1)Reading it: the index on customer_id alone finds all 48,210 orders of a big customer. The database reads about 41,000 table pages, mostly from disk, sorts the rows, and keeps 20. The fix is the composite (customer_id, created_at DESC) index. The plan then becomes Limit over Index Scan, reading about 25 pages, and the time drops from about 800 ms to under 1 ms. For a big customer, the scan does not grow with order history, because only the first 20 entries are read.
Estimates far from reality. If the estimated rows=12 meets actual rows=480000, the planner chose its plan on false information. Common causes:
- Stale statistics after a bulk load. Run
ANALYZE. - Correlated columns, such as
cityandzip, that the planner assumes are independent. UseCREATE STATISTICSfor extended statistics. - Skewed values beyond the tracked most-common-values list. Raise the statistics target for that column.
MySQL's EXPLAIN, briefly. MySQL prints one row per table. The type column runs from best to worst: const or eq_ref (single row by unique key), ref (index equality), range, index (full index scan) and ALL (full table scan). key shows the chosen index. In Extra, "Using index" means covering, "Using filesort" means an extra sort step, and "Using temporary" means a temporary table. EXPLAIN ANALYZE (MySQL 8.0.18+) and EXPLAIN FORMAT=TREE give a plan tree close to PostgreSQL's.
Safety. EXPLAIN ANALYZE really runs the statement. To profile an UPDATE or DELETE, wrap it in BEGIN; ... ROLLBACK;. Run heavy diagnostics on a replica with production-like data, because plans on a 1,000-row development table say little about a 1-billion-row production one. See Database Performance and SQL Tuning for the wider tuning process.
When to Use It#
- Every column used to look up, join or filter frequently queried data, especially foreign keys.
- Columns in
ORDER BY ... LIMITon large tables (list pages, feeds). - Uniqueness rules (
UNIQUEindexes double as constraints). - Any query on a table over roughly 10,000 rows that runs often.
When NOT to Use It#
- Small or rarely queried tables.
- Write-heavy logging or event tables read only in bulk.
- Duplicate or overlapping indexes: (A) is redundant if (A, B) exists.
How to Implement It#
- List top queries by frequency and latency (from
pg_stat_statements, slow query logs or APM). - Design indexes per query: equality columns first, then range or sort; add INCLUDE columns for hot lists.
- Build online on large tables (
CREATE INDEX CONCURRENTLYin PostgreSQL; online DDL in MySQL). - Verify with EXPLAIN ANALYZE that the plan uses the index.
- Remove unused indexes periodically (
pg_stat_user_indexesshows scan counts).
| Technology | Fits when |
|---|---|
| B-tree (default in Postgres, MySQL) | Equality, ranges, sorting |
| PostgreSQL GIN | Full-text, JSONB containment, arrays |
| PostgreSQL GiST / PostGIS | Geospatial and range types |
| BRIN (PostgreSQL) | Huge append-only tables ordered by time; tiny index |
| Elasticsearch / OpenSearch | Large-scale text search and facets |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| More indexes | Faster reads for more queries | Slower writes, more storage and memory | Read-heavy tables |
| Composite index | One index serves several queries | Order-sensitive; larger | Common multi-column filters |
| Covering index | Index-only reads | Bigger index, more write cost | Hot list queries |
| Partial index | Small, targeted | Only helps queries matching its condition | Small hot subsets ("pending") |
| No index | Fastest writes | Full scans | Small or write-only tables |
| Hash index | O(1) equality, small for long keys | No ranges, sorting or prefixes | Tokens, cache keys, exact-match only |
| Clustered primary key (InnoDB) | Fast primary-key ranges, one-step primary lookups | Secondary lookups need two searches, wide keys copied everywhere | Primary-key range access dominates |
| BRIN index | Tiny, nearly free to maintain | Only works when values follow physical order | Append-only time-ordered tables |
| External search index (Elasticsearch) | Ranking, facets, typo tolerance | Second system to run, seconds of lag | Large-scale text search |
| LSM-based store | Cheap sequential writes | Reads check several files, compaction cost | Write-heavy ingestion |
Common Pitfalls#
- No index on foreign keys, making joins and cascading deletes scan.
- Composite indexes in the wrong column order.
- Functions or type casts on indexed columns in
WHERE, preventing index use. - Random UUIDv4 primary keys in InnoDB, causing page splits.
- Creating indexes on a live large table without the online option, locking writes.
- Indexing a frequently updated column in PostgreSQL and losing HOT updates for the whole table.
- Expecting
LIKE '%term%'to use a B-tree; it needs a trigram or full-text index. - Running a geohash search on one cell only and missing nearby points across the cell edge.
- Trusting
EXPLAINestimates withoutANALYZE, or benchmarking only on a warm cache. - Leaving an
INVALIDindex behind after a failed concurrent build.
Real-World Examples#
PostgreSQL's documentation explains multicolumn B-tree indexes as most efficient when there are constraints on the leading (leftmost) columns, the same rule used across relational databases.
MySQL InnoDB stores each table as a clustered index on the primary key, with secondary indexes referencing rows by primary key, as described in the MySQL reference manual.
Redis implements its GEO commands on top of sorted sets, storing a geohash-derived score per member. Uber open-sourced H3, its hexagonal grid system, for geospatial indexing and analytics.
Elasticsearch and OpenSearch are built on Apache Lucene's inverted indexes and use BM25 as their default relevance scoring.
In the Interview#
Handling indexing questions in an interview#
Name the index with the query. Do not stop at "we add an index". Say the query, the columns, the order and the result: "Login is WHERE email = ?, so a unique B-tree on email. The order list is WHERE user_id = ? ORDER BY created_at DESC LIMIT 20, so a composite on (user_id, created_at DESC). That gives one index range read of about 20 entries, whatever the table size."
Match the depth to the role. For product or full-stack roles, the expectation is to propose sensible indexes on the fields you query and know the read-write trade-off. For infrastructure roles and staff level, expect questions on B-tree vs LSM, clustered vs heap layout, local vs global indexes in sharded systems, and why the planner might ignore an index.
Know when the main database is the wrong place. For text search, propose Elasticsearch fed by CDC and accept a second or so of lag. For "near me" queries, propose PostGIS or geohash or H3 cells, and name the 9-cell lookup for geohash edges. For very high-rate writes with simple key reads, an LSM store such as Cassandra keeps writes cheap.
Follow-ups to expect.
- "Your table gets 50,000 writes a second. How many indexes?" As few as possible. Each one adds a structure write, so move heavy query patterns to a derived store.
- "Why is the database not using my index?" Low selectivity, a function or cast on the column, a wrong column order, or stale statistics.
- "How do you add an index to a 2 TB table without downtime?" Build it concurrently or online, watch replica lag, and drop any invalid leftovers if the build fails.
Deep Dive: Selectivity, statistics and indexes in distributed databasesShow
Selectivity and the optimizer. The optimizer uses an index only if it expects to read a small share of rows; above roughly 5-20% of the table (it varies), a sequential scan is cheaper, because index lookups cause random reads. That is why a "missing" index use is sometimes correct. Data skew matters: an index on country is useful for small countries and useless for the largest one; per-value statistics let the planner choose differently for each.
Local vs global secondary indexes. In sharded databases, a local index lives on each shard and indexes only that shard's rows: cheap to maintain, but a query not filtered by the shard key must ask every shard (scatter-gather). A global index is partitioned by the indexed column itself: queries go to one index partition, but every write may update a different node, so global indexes are often updated asynchronously (DynamoDB global secondary indexes are eventually consistent). See Partitioning and Sharding.
LSM-based indexes. Databases built on LSM trees (Cassandra, RocksDB) handle index writes as cheap appends, but reads may check several files, helped by bloom filters. See Storage Engines.
Deep Dive: Index maintenance over time and multi-version effectsShow
Index bloat and its causes. In PostgreSQL, MVCC means an updated row leaves its old version behind until VACUUM removes it. Index entries for dead versions linger too. A table with constant updates, such as a job queue where rows move through states, can grow an index to many times its live size. Long-running transactions make this worse, because VACUUM cannot remove versions that an old transaction might still see. Watch the age of the oldest open transaction and the ratio of index size to live rows. Rebuild with REINDEX CONCURRENTLY when an index's size runs far ahead of its live rows.
Bottom-up deletion and deduplication. PostgreSQL 13 added deduplication to B-tree leaves: many entries with the same key value are stored as one key with a list of row pointers, which shrinks low-cardinality indexes a lot. PostgreSQL 14 added bottom-up index deletion. When a page is about to split because of new versions of the same logical rows, the engine first tries to remove dead entries from it, which avoids version-driven splits. Both make upgrades a real win for write-heavy tables.
The right edge under extreme insert rates. With time-ordered keys, the rightmost leaf is the only hot page, which is great for caching but can become a contention point on very high-core machines, where many sessions want the same page latch. Approaches include hash-partitioning the table so that each partition has its own right edge. Some systems also use a key whose leading bits are slightly scattered, which trades some locality for less contention. Distributed SQL systems such as CockroachDB and Spanner face this at cluster scale: sequential keys send every insert to the one range holding the end of the key space. That is why their documentation recommends UUIDs or hash-sharded indexes for high-rate inserts.
Building an index on a live table. CREATE INDEX CONCURRENTLY scans the table twice and waits for in-flight transactions between phases, so it takes longer but never blocks writes. If it fails, an INVALID index remains. It still slows writes, so drop it and retry. On replicas, a large build produces a burst of WAL that can raise replication lag, so build during quieter hours and watch the lag. In MySQL, InnoDB online DDL builds secondary indexes while allowing concurrent writes. For the largest tables, teams use gh-ost to rebuild the table in the background.
Key Takeaways#
- Indexes turn full scans into a few page reads; B-trees support equality, ranges and sorting.
- Composite indexes follow the leftmost-prefix rule: equality columns first, then range or sort columns.
- Covering indexes enable index-only scans; clustered indexes store rows in key order (InnoDB primary key).
- Inverted indexes power full-text search; R-trees, geohashes and cell systems power geospatial queries.
- Every index costs writes and storage; index real queries, avoid low-selectivity columns, and confirm with EXPLAIN.
- B+ trees with fan-out in the hundreds reach billions of keys in 4 levels, and the top levels stay cached.
- In a composite index, columns after a range condition cannot be used for seeking.
- InnoDB secondary indexes carry the primary key, so keep it compact and time-ordered.
- Use inverted indexes for text and geohash, R-tree or cell IDs for location. Sync external indexes via CDC and accept the lag.
- The planner skips indexes for low selectivity. Use partial, expression or BRIN indexes when they fit, and read plans with ANALYZE and BUFFERS.