Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Database Indexing

An index is an extra access path that trades storage and write work for less read work.

What, why, when and how

What is it?

An index is an additional access structure that lets a database locate relevant records without examining every row.

Why is it needed?

Table scans can read far more data than a selective query returns, increasing latency and resource consumption.

When should I use it?

Use an index for frequent selective filters, ordered pagination, joins or uniqueness constraints, and verify that the query planner benefits.

When should I choose something else?

An index may not help a query that reads most of a table. Excess indexes increase write, storage and maintenance costs.

How do I use it?

Start from the actual filter and order, choose a suitable structure and key order, inspect the plan, then measure reads and write overhead on representative data.

Can you show a concrete example?

A recent-notices query for one tenant can use a composite key containing tenant ID, creation time and a tie-breaking ID. The cursor carries the last time and ID so equal timestamps do not skip or repeat rows.

Query: tenant t1, newest notices first; Index: tenant + time + tie-breaking ID; Cursor uses time AND ID; bound the page
Database Indexing: one concrete example
Read the diagram

Query: tenant t1, newest notices first; Index: tenant + time + tie-breaking ID; Cursor uses time AND ID; bound the page

Open original
Database Indexing: worked example
Query: tenant t1, newest notices first; Index: tenant + time + tie-breaking ID; Cursor uses time AND ID; bound the page

Database Indexing: one concrete example

Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.

An index is an extra access path that trades storage and write work for less read work. It is not a general “make queries fast” switch. Explain which rows a query needs, which order it needs them in, and how the index lets the database avoid visiting unrelated data. Then account for the cost of maintaining that access path on every change.

Learning goals

B-tree intuition; selectivity; composite key ordering; covering and partial indexes; query plans; write amplification; pagination; maintenance cost.

Compare stored structures with the same small query

An index is another stored representation that reduces some reads at the cost of space and writes. Consider keys (tenant,time,id) ordered lexicographically: (t1,12:03,d93), (t1,12:03,d91), (t1,12:02,d90), then another tenant. A descending inbox query after (12:03,d91) returns d90, not d93 or d91. Tenant equality selects the relevant range; the ID resolves tied timestamps. A differently ordered index may require more filtering or sorting.

A B-tree has ordered separator keys in internal pages and ordered entries at leaves. Search compares separators, descends through a small number of pages and walks a leaf range. Fetching the referenced table rows can dominate the remaining cost; ordered index traversal does not imply physically adjacent table rows. A covering index can reduce those visits, with extra bytes and visibility considerations. A hash index maps equality keys to buckets; it does not naturally walk a time range. Never infer range capability from fast equality lookup.

An LSM-style path first appends recovery information under the engine's durability rules and changes an in-memory table, then flushes sorted immutable runs. Reads may need to consult memory and several runs; Bloom filters and indexes prune work. Compaction merges runs, keeps applicable versions and processes tombstones under retention/repair rules. This favors sequential write work but creates write amplification and background resource demand. LSM and B-tree designs both have implementation-dependent read/write costs; choose from measured workload, not a universal winner.

Contract / pseudocode
memtable: k7 -> v2
older run: k7 -> v1, k8 -> v1
read k7: choose the applicable newest version v2
flush: create another sorted run
compact: merge versions; preserve required tombstone semantics
Ordered keys: (t1,12:03,d93),(t1,12:03,d91); After cursor (12:03,d91): next row d90; B-tree: separators -> leaf range -> table rows; LSM: memtable k7=v2 overrides old run k7=v1; Inverted terms: intersection is not phrase order
Compare stored structures with the same small query
Read the diagram

Ordered keys: (t1,12:03,d93),(t1,12:03,d91); After cursor (12:03,d91): next row d90; B-tree: separators -> leaf range -> table rows; LSM: memtable k7=v2 overrides old run k7=v1; Inverted terms: intersection is not phrase order

Open original
Compare stored structures with the same small query
Ordered keys: (t1,12:03,d93),(t1,12:03,d91); After cursor (12:03,d91): next row d90; B-tree: separators -> leaf range -> table rows; LSM: memtable k7=v2 overrides old run k7=v1; Inverted terms: intersection is not phrase order

Compare stored structures with the same small query

An inverted index maps terms to document IDs and, when phrase queries matter, positions. red -> {p1:[1],p2:[4]} and bird -> {p1:[2],p2:[1]} intersect at p1 and p2, but only p1 matches the adjacent phrase “red bird.” Spatial indexes instead prune geometric candidates. A geohash prefix identifies cells; a tree indexes regions. In both cases a final distance/filter test may still be required. These are different query shapes, not optional names for one identical structure.

Evaluate the plan without hiding its cost

Use estimated plans first; actual-plan execution runs the statement. For a read, compare actual rows, loops, buffer work and sorting with representative skew. For a mutation, use a safe test environment. A partial index for state='failed' can be smaller than an all-state index, but the planner must be able to use its predicate. Every additional index must be maintained by relevant inserts, updates and deletes. Online creation and maintenance need capacity and a rollback plan.

Show answer and explanation

Answer: A hash lookup can find one delivery ID quickly but cannot satisfy a newest-first tenant inbox by walking a time interval. Two term matches do not prove phrase order. An index on a tiny uniform fixture is not evidence that one million-row tenant will meet the target.

Step-by-step reasoning

1. Think in ordered keys

A B-tree organizes keys so a search can narrow to a range instead of scanning every row. Equality and ordered range queries are natural uses. The actual cost also includes fetching table pages, cache behavior, and the number of qualifying rows. If a predicate matches most of the table, a sequential scan may be cheaper than many scattered lookups.

2. Match the common query

For a tenant’s newest failed deliveries, start with tenant equality, then the relevant status and time ordering. Add id as a deterministic tie-breaker. Composite key order matters because it controls which contiguous ranges are easy to find. Do not assume an index designed for tenant-first queries is equally effective for a global time-only query.

3. Use specialized indexes deliberately

A partial index can include only failed rows when that predicate matches the workload. A covering index includes selected values to reduce table visits, although visibility and engine details still matter. Both increase write and maintenance costs. Avoid adding every column just to make a hypothetical query index-only; large indexes reduce cache efficiency.

4. Read plans and measure

Use an execution plan to compare estimated and actual rows, scan type, sort work, and buffer access. EXPLAIN ANALYZE actually runs the statement, so use a safe environment for mutations. Test representative tenant sizes and skew rather than a tiny uniform fixture. Revisit indexes when the data distribution or dominant query changes.

Contracts and state

The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.

Contract / pseudocode
CREATE INDEX delivery_failed_recent
ON delivery (tenant_id, created_at DESC, id DESC)
WHERE state = 'failed';

SELECT id, created_at FROM delivery
WHERE tenant_id = :tenant AND state = 'failed'
  AND (created_at, id) < (:cursor_time, :cursor_id)
ORDER BY created_at DESC, id DESC LIMIT 50;

Worked example

A table has 100 million delivery rows, but one tenant has 200,000 and only 2,000 failed. An index on state alone first finds failed rows across every tenant. A tenant-scoped partial index can navigate directly to the relevant ordered range. These are illustrative counts, not a guaranteed speedup: confirm the plan, selected columns, data locality, and actual I/O. The cursor avoids walking through all prior pages just to reach the next 50 results.

Failure walkthrough

Indexes can make an overloaded write path worse. Updating a frequently indexed state column requires index maintenance, and building a large new index consumes resources. Plan the rollout and observe write latency, disk space, replication lag, and lock behavior. Remove unused indexes only after checking occasional operational queries and constraints that depend on them.

Receive stable cursor → Seek tenant and time range → Read next ordered keys → Fetch required columns → Return last key as cursor
Database Indexing · scenario walkthrough
Read the diagram

Receive stable cursor → Seek tenant and time range → Read next ordered keys → Fetch required columns → Return last key as cursor

Open original
Database Indexing · scenario walkthrough
Receive stable cursor → Seek tenant and time range → Read next ordered keys → Fetch required columns → Return last key as cursor

Database Indexing · scenario walkthrough

Decisions and trade-offs

TechniqueHelps whenCost
Composite indexFilters and order alignLess useful for unrelated leading keys
Partial indexStable selective predicateQueries must satisfy its predicate
Covering valuesAvoiding table fetches mattersLarger writes and memory footprint

Check your understanding

Why might a status-only index be ignored when nearly every record is active?

Show answer and explanation

Answer: It excludes little data. Fetching most table rows through an index can cost more than scanning them sequentially. Selectivity, row width, ordering, and physical locality determine whether the index helps.

Transfer to a new scenario

Serve a tenant's newest failed deliveries with an ordered composite index and a stable cursor.

Why might an index on status alone fail to improve a large table's common query?

Primary documentation

Read the first-party engineering account or official technical reference. Company engineering posts describe the scope and date of that publication; the interview reconstruction and scenarios here are original teaching examples.

Read an access path before adding an index

For a tenant inbox ordered newest first, an index on (tenant_id,created_at,id) can constrain the tenant and walk the desired range. An index on created_at alone may inspect many other tenants before finding enough rows. Column order is about predicates and ordering, not simply putting the most unique column first.

Use EXPLAIN and measured execution to inspect rows scanned, filtering, sorts and heap access. A planner may correctly choose a sequential scan when the query touches much of the table. A covering index can reduce table access but increases size and write work; visibility rules can still require heap checks in PostgreSQL.

Think of a B-tree as ordered pages that narrow a range, not a magic O(1) lookup. Inserts can split pages, updates maintain indexes and dead versions need cleanup. Each additional index consumes storage and write bandwidth. Test with realistic data distribution, including a very large tenant, because averages hide skew.

A decision worksheet for Database Indexing: read the mechanism and its guarantee together.
A decision worksheet for Database Indexing: read the mechanism and its guarantee together.
Read the diagram

Technique / Helps when / Cost; Composite index / Filters and order align / Less useful for unrelated leading keys; Partial index / Stable selective predicate / Queries must satisfy its predicate; Covering values / Avoiding table fetches matters / Larger writes and memory footprint

Open original
Database Indexing choices for this workload
A decision worksheet for Database Indexing: read the mechanism and its guarantee together.

A decision worksheet for Database Indexing: read the mechanism and its guarantee together.

Operational sketch

Contract / pseudocode
CREATE INDEX inbox_recent ON delivery
 (tenant_id, created_at DESC, id DESC);
SELECT id,state FROM delivery
WHERE tenant_id = $1
  AND (created_at,id) < ($2,$3)
ORDER BY created_at DESC,id DESC LIMIT 50;

A tempting mistake

An index cannot fix a query that asks for an unbounded result. Running EXPLAIN ANALYZE executes the query, so use care for mutating statements and production load. Index creation also has operational cost and needs a rollout plan.

Transfer exercise

Why might an index on (tenant_id,created_at) not efficiently answer all tenants for one date?

Show answer and explanation

Answer: The leading tenant key separates ranges by tenant. The desired global date range is not one contiguous portion of that ordering; choose a different access path if that query matters.

A simplified B-tree range lookup. Real pages contain more entries and can have additional levels.
A simplified B-tree range lookup. Real pages contain more entries and can have additional levels.
Read the diagram

For key 42, a root separator directs the lookup to the middle leaf. A leaf entry then points to a heap row unless an index-only path is sufficient.

Open original
Database index · ordered pages narrow the search
A simplified B-tree range lookup. Real pages contain more entries and can have additional levels.

A simplified B-tree range lookup. Real pages contain more entries and can have additional levels.

Shared foundation: Storage Engines and Index Mechanics

Storage Engines and Index Mechanics: Connect access paths to durable acknowledgement, version retention, amplification and verified recovery. Work its failure history before extending this design.

12:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

Why might a status-only index be ignored when nearly every record is active?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Read study notes

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.