Secondary Indexes and Index Trade-offs
Hash, B-tree, composite, covering and inverted indexes: what each can answer, where it points, and what it costs every write.
Overview
An index is a second copy of some of your data, sorted or hashed so a query can find rows without reading the whole table. It is derived data: the database can always rebuild it from the table. That is what makes it a trade. Every index speeds up some reads and slows down every write that has to keep it up to date.
The cost of an index
A table with no index is cheap to write and slow to search. Each index added makes the reverse true for the queries it serves.
Take a table with three indexes: the primary key index, an index on email and an index on (user_id, created_at). One INSERT writes the row to the table once, then writes its own entry into each of the three indexes. More indexes mean more work on every insert and on many updates.
Each extra index changes the cost of every kind of statement.
- INSERT: one more index entry to write.
- DELETE: entries to clean up. PostgreSQL does this later, in vacuum.
- UPDATE of an indexed column: a new index entry.
- UPDATE of other columns: in PostgreSQL, often no index work at all, thanks to HOT (heap-only tuple) updates, if the new row version fits on the same page.
- SELECT: faster, but only for queries the index can serve.
So index the columns that appear in frequent filters, joins and sort orders, and nothing else.
Key concepts
- Secondary index
- Clustered index
- Heap
- Covering index
- Composite index
- Hash index
- Inverted index
- HOT update
Interview questions
- Which index would you add for a query that filters on user_id and a created_at range, sorted by created_at?
- How does a secondary index lookup differ between PostgreSQL and MySQL InnoDB?
- Why does every index slow down writes, and how do you decide how many to keep?
- When will the planner ignore an index and read the whole table?
- How would you support search for words inside a text column?
Sign up free to read the full topic
More DDIA topics
- Rebalancing Partitions
- Relational vs Document Data Models
- Reliability, Scalability, and Maintainability
- Replication Lag and Consistency Anomalies
- Schema Evolution and Backward/Forward Compatibility
- Schema-on-Read vs Schema-on-Write
- Secondary Indexes on Partitioned Data
- Single-Leader Replication
- SLAs, SLOs, and Percentile Latency
- Unbundling the Database
- What Is a Data-Intensive Application?
- Write Skew and Phantom Reads
Start free on Cariara · Coding problems · System design studio