PrepStack › Databases › Indexing & Query Optimization
Indexing & Query Optimization interview cheat sheet
B+trees, composite & covering indexes, EXPLAIN plans and slow-query fixes
Interviewers use this topic to see if you can make a slow query fast and explain why. Expect questions on how a B+tree works, clustered vs secondary indexes, the leftmost-prefix rule, covering indexes, why an index is ignored, and how to read an EXPLAIN plan. Senior rounds add trade-offs: write cost, too many indexes, bloat, LSM trees and pagination at scale. The SQLite snippets run as shown; PostgreSQL and MySQL examples are illustrative.
15-minute revision
- An index is a separate sorted structure (key → row location). It turns an O(n) full scan into an O(log n) lookup, but every INSERT/UPDATE/DELETE must also update it, and it uses disk and memory.
- Most databases use a B+tree: wide, shallow (3–4 levels for millions of rows), data or row pointers only in the leaves, and leaves linked for fast range scans and ORDER BY.
- Hash indexes do equality only (
=). No ranges, no sorting, no prefix match. B-tree handles = < > BETWEEN IN, LIKE 'abc%' and ORDER BY. - Clustered index = the table itself is stored in key order (InnoDB primary key, SQL Server). Only one per table. PostgreSQL stores rows in an unordered heap, so every index there is secondary.
- InnoDB secondary indexes store the primary key, so a lookup is two B-tree walks. Keep the PK small and roughly increasing (BIGINT or UUIDv7, not random UUIDv4).
- Composite index
(a, b, c) is sorted by a, then b, then c. It helps a, a,b, a,b,c, but not b or c alone (leftmost-prefix rule). Put equality columns first, the range column last. - Covering index: every column the query needs is in the index, so the table is never touched (index-only scan, MySQL
Using index). PostgreSQL and SQL Server have INCLUDE (...). - Selectivity = distinct values / rows. High selectivity (email, id) = great index. Low selectivity (gender, boolean status) is usually ignored by the planner, unless you use a partial index.
- Partial index (
WHERE deleted_at IS NULL) indexes only the rows you query. Expression index (lower(email)) lets a function in WHERE use an index. - Index is not used when you wrap the column in a function, use
LIKE '%x', compare mismatched types, use OR across different columns, skip the leftmost column, or the query returns a large share of the table. - EXPLAIN plan words: Seq Scan / ALL = full scan; Index Scan / ref / range = uses index; Index Only Scan / Using index = covering; Bitmap = many rows, read in page order.
- Join algorithms: nested loop (small outer, indexed inner), hash join (big unsorted equi-joins), merge join (both inputs sorted). Index the foreign key column on the inner side.
- The planner is cost-based and trusts statistics. Stale stats cause bad plans. Run
ANALYZE (Postgres), ANALYZE TABLE (MySQL) after big loads. Use EXPLAIN ANALYZE to compare estimated vs actual rows. - Query checklist: no
SELECT *, kill N+1 queries (JOIN or IN batch), keyset pagination instead of large OFFSET, batch writes in one transaction, find offenders with the slow query log / pg_stat_statements. - Too many indexes slow writes, waste buffer cache and confuse the planner. Drop unused and duplicate ones. Build new ones online (
CREATE INDEX CONCURRENTLY) and fix bloat with REINDEX CONCURRENTLY. - LSM trees (RocksDB, Cassandra) buffer writes in memory and flush sorted files, then compact. Faster writes, slower reads than B-trees, which update pages in place.
Index fundamentals
What an index is & what it costs
An index is an extra sorted copy of some columns that makes reads fast and writes slower.
- Think of the index at the back of a book: sorted keys plus page numbers. The database finds the key in O(log n) and jumps to the row instead of reading every row.
- Without an index the database does a full table scan (Postgres
Seq Scan, MySQL type: ALL, SQLite SCAN). - Indexes help
WHERE, JOIN ... ON, ORDER BY, GROUP BY, MIN/MAX and uniqueness checks. - Write cost: each INSERT adds an entry to every index; each UPDATE of an indexed column moves an entry; each DELETE removes one. More indexes = slower writes and more WAL/redo log.
- Storage cost: indexes live on disk and compete for buffer pool memory. Large tables often have indexes bigger than the table itself.
- Primary key and UNIQUE constraints create an index automatically. Foreign keys do not in PostgreSQL (MySQL InnoDB does create one if missing).
Interview questions
- What is a database index and why does it speed up queries?
- If indexes make reads faster, why not index every column?
- Does creating a foreign key create an index?
- What is the time complexity of a lookup with and without an index?
B-tree & B+tree structure
Databases use B+trees: wide, shallow, balanced trees where all data sits in linked leaf pages.
- A B-tree is a balanced search tree where each node is a disk page (8 KB in PostgreSQL, 16 KB in InnoDB, 4 KB default in SQLite) holding many sorted keys.
- Because one page holds hundreds of keys, the fan-out is huge and the tree is shallow: 3–4 levels cover millions to billions of rows. The root and upper levels usually stay cached in memory.
- In a B+tree, internal nodes hold only keys and child pointers; all values (or row pointers) live in the leaves. Leaves are linked to their neighbours.
- Linked leaves make range scans cheap: seek to the first key, then follow the leaf chain. That also gives ORDER BY for free.
- Inserts keep the tree balanced by splitting full pages and pushing a key up; deletes may merge pages. Every leaf stays at the same depth, so lookups are always O(log n).
- Indexes can be read forwards or backwards, so
ORDER BY col DESC can use an ascending index.
Interview questions
- Why do databases use B+trees instead of binary search trees or hash tables?
- What is the difference between a B-tree and a B+tree?
- How tall is a B+tree index on 100 million rows?
- What is a page split and why does it matter?
Hash indexes
Hash indexes map a key's hash to rows: great for exact =, useless for ranges and sorting.
- A hash index stores
hash(key) → row pointers in buckets. Lookup is O(1) on average for equality. - It cannot do
<, >, BETWEEN, ORDER BY, prefix LIKE, or use part of a composite key, because hashing destroys order. - PostgreSQL:
CREATE INDEX ... USING HASH (col). It is crash-safe and replicated since PostgreSQL 10, single-column only, and cannot be UNIQUE. - MySQL: explicit HASH indexes exist for the MEMORY engine. InnoDB always builds B-trees, but it has an internal adaptive hash index it builds on hot B-tree pages by itself.
- In practice a B-tree is almost always good enough for equality too, so hash indexes are a niche choice (e.g. very long keys like URLs where only
= is used).
Interview questions
- Difference between a B-tree index and a hash index?
- What is InnoDB's adaptive hash index?
- Can you use a hash index for
WHERE created_at > now() - interval '1 day'?
Clustered vs non-clustered (InnoDB vs Postgres heap)
A clustered index is the table stored in key order; non-clustered indexes point to rows stored elsewhere.
- Clustered index: the leaf pages of the index are the table rows, ordered by the key. Only one per table. InnoDB and SQL Server work this way.
- InnoDB clusters on the PRIMARY KEY. With no PK it uses the first UNIQUE NOT NULL index; failing that, a hidden 6-byte row id.
- InnoDB secondary indexes store the PK value as the row pointer. A secondary lookup = walk the secondary tree, then walk the PK tree (a “bookmark lookup”).
- PostgreSQL stores rows in an unordered heap. Every index, including the PK, is secondary and points to a physical location (TID = page, slot).
- PostgreSQL's
CLUSTER command reorders the heap once by an index, but new rows are not kept in order. BRIN and correlation stats benefit from that order. - SQLite tables are B-trees keyed by
rowid (an INTEGER PRIMARY KEY is the rowid), and WITHOUT ROWID tables are clustered on their declared PK.
Interview questions
- What is the difference between a clustered and a non-clustered index?
- How does a secondary index lookup work in InnoDB vs PostgreSQL?
- Why is a random UUID a poor primary key in MySQL?
- Does PostgreSQL have clustered indexes?
Primary, secondary & unique indexes
PK = unique, non-null row identity; UNIQUE indexes enforce no duplicates; everything else is a secondary index.
- Primary key: unique + NOT NULL, one per table, automatically indexed. In InnoDB it is also the clustered index.
- Secondary index: any other index. It may be unique or non-unique.
- Unique index enforces that no two rows share the key; the database checks it on every insert/update. A UNIQUE constraint is implemented with a unique index.
- NULLs are distinct by default in PostgreSQL, MySQL and SQLite, so a UNIQUE column can hold many NULLs. PostgreSQL 15+ supports
UNIQUE NULLS NOT DISTINCT. - A unique index also tells the planner “at most one row”, which enables cheaper plans (MySQL
const/eq_ref). - Unique indexes power upserts:
INSERT ... ON CONFLICT (PostgreSQL, SQLite) and INSERT ... ON DUPLICATE KEY UPDATE (MySQL).
Interview questions
- Difference between a primary key and a unique key?
- Can a unique column contain multiple NULLs?
- How would you guarantee unique emails under high concurrency?
Designing good indexes
Composite indexes & the leftmost-prefix rule
An index on (a, b, c) is sorted by a first, so queries must constrain its leading columns to seek.
- A composite (multi-column) index sorts by the first column, then the second within equal firsts, and so on, like a phone book sorted by last name, then first name.
- Leftmost-prefix rule:
(a, b, c) can seek on a, a,b, or a,b,c. A filter only on b or c cannot seek (it would need a full index scan). - Equality first, range last: once a column is used with a range (
>, BETWEEN, LIKE 'x%'), columns to its right cannot narrow the seek. They can still be filtered inside the index. - Column order should follow your queries: equality columns used together, then the range or ORDER BY column. Cardinality is a secondary concern.
- An index on
(a, b) makes a separate index on (a) redundant. It can also serve WHERE a = ? ORDER BY b without a sort. - Skip scan relaxes the rule when the leading column has few distinct values: MySQL 8.0.13+ and PostgreSQL 18+ can jump through each distinct leading value.
Interview questions
- What is the leftmost-prefix rule?
- How do you choose the column order in a composite index?
- I have an index on (last_name, first_name). Will
WHERE first_name = 'Asha' use it? - Is an index on (a) redundant if (a, b) exists?
Covering indexes & index-only scans
If the index holds every column a query needs, the database answers from the index alone and never reads the table.
- A covering index contains all columns in SELECT, WHERE, JOIN, ORDER BY and GROUP BY for a query.
- The plan becomes an index-only scan: PostgreSQL
Index Only Scan, MySQL Extra: Using index, SQLite COVERING INDEX. - It removes the expensive random reads to the table (heap fetch / PK lookup), which matters most when many rows match.
- Add payload columns with
INCLUDE: PostgreSQL 11+ and SQL Server CREATE INDEX ... (key) INCLUDE (col). Included columns are stored only in leaves and are not part of the sort. - MySQL has no INCLUDE; append the columns to the key instead. InnoDB secondaries already carry the PK, so the PK is covered for free.
- In PostgreSQL, index-only scans depend on the visibility map. On a table with many recent changes it still shows
Heap Fetches; VACUUM fixes that.
Interview questions
- What is a covering index?
- What does INCLUDE do and how is it different from adding a key column?
- The plan says Index Only Scan but it is still slow, with high Heap Fetches. Why?
Selectivity & cardinality
An index pays off when a predicate selects a small fraction of rows; the planner estimates that from cardinality stats.
- Cardinality = number of distinct values in a column. Selectivity = distinct values / total rows (1.0 for a unique column), or the fraction of rows a predicate returns.
- High selectivity (email, order id) = few rows per value = great index. Low selectivity (boolean, status with 3 values) = many rows per value.
- When a predicate matches more than a small share of the table (often quoted as roughly 5–20%, depending on the engine and caching), random index lookups cost more than one sequential scan, so the planner skips the index.
- Low-cardinality columns are still useful as the second column of a composite index, or as a partial index for the rare value (
WHERE status = 'FAILED'). - Skewed data matters:
status = 'PENDING' may match 0.1% while status = 'DONE' matches 99%. The same index is good for one and useless for the other; stats like MCV lists let the planner tell them apart.
Interview questions
- What is the difference between cardinality and selectivity?
- Why would the database ignore an index on a
gender or status column? - How would you index a status column where 99% of rows are 'DONE' and you query 'PENDING'?
Partial & expression indexes
Partial indexes cover only rows matching a WHERE; expression indexes index a computed value like lower(email).
- Partial (filtered) index:
CREATE INDEX ... WHERE condition. Smaller, cheaper to update, and only used when the query's WHERE implies the index condition. - Classic uses: soft deletes (
WHERE deleted_at IS NULL), queues (WHERE status = 'PENDING'), and partial unique constraints (one active email per user). - Supported in PostgreSQL, SQLite, and SQL Server (filtered indexes). MySQL has no partial indexes.
- Expression (functional) index: indexes the result of an expression, e.g.
lower(email) or (data->>'type'). The query must use the same expression. - MySQL 8.0.13+ supports functional key parts with double parentheses:
INDEX ((lower(email))). Older MySQL used an indexed generated column. - Expression functions must be deterministic (IMMUTABLE in PostgreSQL). You cannot index
now().
Interview questions
- What is a partial index and when would you use one?
- How do you enforce 'unique email among non-deleted users'?
- Why doesn't
WHERE lower(email) = ? use my index on email, and how do you fix it?
Full-text, GIN, GiST & BRIN
Beyond B-trees: inverted indexes for text/JSON/arrays, GiST for geometry and ranges, BRIN for huge naturally ordered tables.
- Full-text index = an inverted index: word → list of documents. It supports word search, stemming and ranking, which
LIKE '%word%' cannot do efficiently. - MySQL:
FULLTEXT index + MATCH(col) AGAINST('...'). PostgreSQL: tsvector + @@ with a GIN index. SQLite: the FTS5 virtual table. - GIN (Generalized Inverted Index, PostgreSQL): many keys per row. Use it for
jsonb containment (@>), arrays, full-text, and trigram LIKE '%x%' via pg_trgm. Reads are fast; writes are slower. - GiST: a balanced tree framework for overlapping data: geometry (PostGIS), ranges, nearest-neighbour
ORDER BY location <-> point, and exclusion constraints (no overlapping bookings). - BRIN (Block Range INdex): stores min/max per block range. Tiny and great for huge append-only tables where the value follows the physical order (timestamps in logs). Poor if data is randomly ordered.
- SP-GiST supports space-partitioned structures (quadtrees, tries). Also: spatial R-tree indexes in MySQL and SQLite.
Interview questions
- How would you implement search on product descriptions?
- What is a GIN index and when do you use it?
- When is BRIN a better choice than a B-tree?
- Difference between GIN and GiST?
How the planner uses indexes
When indexes are NOT used
Functions on the column, leading wildcards, type mismatches, ORs, skipped leading columns and low selectivity all block index use.
- Function or math on the column:
WHERE YEAR(created_at) = 2026, lower(email) = ?, price * 1.2 > 100. Rewrite as a range on the raw column (sargable) or add an expression index. - Leading wildcard:
LIKE '%son' has no fixed prefix to seek. LIKE 'Jo%' can use a B-tree (in PostgreSQL needs C collation or text_pattern_ops; in SQLite needs matching case sensitivity). - Implicit type cast: in MySQL,
WHERE phone = 98765 on a VARCHAR column converts every row's value to a number, so the index is skipped. Mismatched charsets/collations in joins have the same effect. - OR across different columns: needs a BitmapOr (PostgreSQL), index merge (MySQL) or MULTI-INDEX OR (SQLite); if any branch has no index, it is a full scan. A
UNION ALL rewrite can help. - Leftmost column missing from a composite index,
!= / NOT IN (usually match most rows), and IS NULL on engines or index types that do not index NULLs. - Low selectivity or a tiny table: the planner correctly prefers a sequential scan. Stale statistics can also make it wrongly ignore a good index.
Interview questions
- List common reasons an index is not used.
- What does 'sargable' mean? Give an example.
- A query with
WHERE phone = 9876543210 is slow on MySQL even though phone is indexed. Why? - How do you speed up
LIKE '%term%' searches?
Reading EXPLAIN plans
EXPLAIN shows the plan and estimates; EXPLAIN ANALYZE runs the query and shows actual rows and time per step.
- PostgreSQL:
EXPLAIN = estimated plan. EXPLAIN (ANALYZE, BUFFERS) = really executes and adds actual time, actual rows, loops and page reads. Wrap writes in BEGIN ... ROLLBACK. - Read the plan tree inside-out / bottom-up.
cost=startup..total is in arbitrary planner units; compare rows (estimate) to actual rows, and multiply by loops. - Scan types:
Seq Scan (all pages), Index Scan (index + heap), Index Only Scan (index only), Bitmap Index Scan + Bitmap Heap Scan (collect matching TIDs, then read heap pages in physical order; good for medium result sets and combining indexes with BitmapAnd/Or). - MySQL
EXPLAIN: key columns are type (best to worst: system/const, eq_ref, ref, range, index, ALL), key, rows, filtered and Extra. - MySQL
Extra red flags: Using filesort (sort not from an index), Using temporary (temp table for GROUP BY/DISTINCT). Good signs: Using index (covering), Using index condition (index condition pushdown). - MySQL 8.0.18+ has
EXPLAIN ANALYZE (tree format with actual times). SQLite has EXPLAIN QUERY PLAN (SCAN vs SEARCH, COVERING INDEX, TEMP B-TREE).
Interview questions
- How do you investigate a slow query?
- Difference between EXPLAIN and EXPLAIN ANALYZE?
- What is a Bitmap Heap Scan and when is it chosen?
- In MySQL EXPLAIN, what do type = ALL and Extra = Using filesort mean?
Join algorithms: nested loop, hash & merge
Nested loop for small or indexed lookups, hash join for large unsorted equi-joins, merge join for pre-sorted inputs.
- Nested loop join: for each outer row, look up matching inner rows. Fast when the outer side is small and the inner join column is indexed; terrible otherwise (O(n × m)).
- Hash join: build a hash table on the smaller input's join key, then probe it with each row of the bigger input. O(n + m), equality joins only, needs memory (
work_mem in PostgreSQL) or spills to disk. - Merge join: both inputs sorted on the join key (by indexes or explicit sorts), then merged in one pass. Great for large inputs already in order; supports equality joins (and some ranges).
- MySQL supports nested loop (with index lookups) and, since 8.0.18, hash join. PostgreSQL supports all three. SQLite uses nested loops only, sometimes with an automatic temporary index or bloom filter.
- The planner picks join order too; with many tables it uses heuristics (PostgreSQL switches to the genetic optimizer above
geqo_threshold tables). - Index the foreign key columns: they are the inner side of most nested-loop joins.
Interview questions
- Explain nested loop, hash and merge joins.
- Why might a join suddenly become slow after data growth?
- Which side should be the hash table in a hash join?
Statistics, ANALYZE & the cost-based optimizer
The optimizer estimates row counts from table statistics; bad stats mean bad plans.
- A cost-based optimizer enumerates plans and estimates their I/O and CPU cost. Its key input is cardinality estimates: how many rows each step returns.
- PostgreSQL keeps per-column stats in
pg_stats: null_frac, n_distinct, most common values (MCV) with frequencies, a histogram of the rest, and correlation with physical order. - Stats are refreshed by
ANALYZE (also run by autovacuum). Raise detail with ALTER TABLE ... ALTER COLUMN ... SET STATISTICS 1000 (default target 100). - The planner assumes columns are independent. For correlated columns (city and zip), use
CREATE STATISTICS ... (dependencies, ndistinct, mcv) in PostgreSQL. - MySQL: InnoDB samples index pages for persistent stats; refresh with
ANALYZE TABLE. MySQL 8.0+ adds histograms for non-indexed columns: ANALYZE TABLE t UPDATE HISTOGRAM ON col. - SQLite:
ANALYZE fills sqlite_stat1; PRAGMA optimize runs it when useful. - Prepared statements can use a generic plan that ignores the actual parameter value; for skewed data this can be wrong (PostgreSQL
plan_cache_mode).
Interview questions
- How does the query optimizer choose between a seq scan and an index scan?
- A query was fast yesterday and slow today with no code change. What do you check?
- What are extended statistics and why are they needed?
- What is the problem with generic plans for prepared statements?
Query optimization in practice
Query optimization checklist
Fetch less, ask fewer times, and let indexes do the filtering and sorting.
- **Avoid
SELECT ***: it moves more data, breaks covering indexes and breaks when columns change. Select only the columns you use. - Kill N+1 queries: loading 100 orders and then running one query per order for its customer = 101 round trips. Use a JOIN or one
WHERE id IN (...) batch (ORM eager loading: JOIN FETCH, select_related/prefetch_related, include). - Filter and aggregate in the database, not in application memory. Push
WHERE, LIMIT, COUNT down. - Batch writes: multi-row INSERT, bulk
COPY/LOAD DATA, and one transaction per batch instead of a commit per row. - Make predicates sargable and index the WHERE, JOIN and ORDER BY columns of hot queries.
- Avoid
COUNT(*) on huge tables for every page view, DISTINCT to hide bad joins, ORDER BY RAND(), and correlated subqueries that run per row (rewrite as JOIN or EXISTS). - Beyond queries: connection pooling, caching hot reads, read replicas, materialized views or summary tables for heavy reports, and partitioning very large tables.
Interview questions
- What is the N+1 query problem and how do you fix it?
- Why is
SELECT * considered bad practice? - How would you speed up inserting a million rows?
- Give quick wins for a slow dashboard query that aggregates millions of rows.
Finding slow queries: slow log & pg_stat_statements
Measure first: log queries over a threshold and rank normalized queries by total time.
- MySQL slow query log:
slow_query_log = ON, long_query_time = 0.5 (seconds), optional log_queries_not_using_indexes. Summarise with mysqldumpslow or Percona's pt-query-digest. - MySQL Performance Schema /
sys schema: events_statements_summary_by_digest, sys.statements_with_full_table_scans, sys.schema_unused_indexes. - PostgreSQL:
log_min_duration_statement = 500ms logs slow statements; auto_explain logs their plans automatically. - pg_stat_statements (load via
shared_preload_libraries) aggregates normalized queries: calls, total and mean time, rows, buffer hits/reads. - Optimise by total time (calls × mean), not just the slowest single query. A 5 ms query called 2 million times a day matters more than one 10 s report.
- APM tools (Datadog, New Relic, OpenTelemetry traces) tie slow queries back to the endpoint that issued them.
Interview questions
- How do you find which queries to optimise in production?
- What is pg_stat_statements?
- Should you optimise the slowest query or the most frequent one?
Too many indexes, bloat & index maintenance
Every index taxes writes; drop unused or duplicate ones, build new ones online, and rebuild bloated ones.
- Too many indexes: slower INSERT/UPDATE/DELETE, more WAL and replication traffic, more memory pressure, longer backups, fewer HOT updates in PostgreSQL, and more choices for the planner to get wrong.
- Find unused indexes: PostgreSQL
pg_stat_user_indexes.idx_scan = 0 (check every replica too); MySQL sys.schema_unused_indexes. Find duplicates/redundant ones: (a) next to (a, b), or MySQL sys.schema_redundant_indexes. - Test a drop safely: MySQL 8.0 invisible indexes (
ALTER TABLE t ALTER INDEX i INVISIBLE) keep the index maintained but hide it from the optimizer. - Bloat (PostgreSQL): MVCC leaves dead tuples; VACUUM marks space reusable but rarely shrinks files. Indexes on heavily updated columns grow and get sparse. Fix with
REINDEX INDEX CONCURRENTLY (PG 12+) or pg_repack. - Fragmentation (InnoDB): random inserts and deletes leave half-empty pages.
OPTIMIZE TABLE (or ALTER TABLE ... ENGINE=InnoDB) rebuilds the table and its indexes. - Building indexes on live tables: plain
CREATE INDEX in PostgreSQL blocks writes. Use CREATE INDEX CONCURRENTLY; if it fails it leaves an INVALID index to drop and retry. MySQL InnoDB builds most secondary indexes with online DDL (ALGORITHM=INPLACE, LOCK=NONE).
Interview questions
- Can having too many indexes hurt performance? How?
- What is index bloat and how do you fix it?
- How do you add an index to a 500 GB table in production without downtime?
- How do you safely remove an index you think is unused?
LSM trees vs B-trees
B-trees update pages in place and favour reads; LSM trees append and compact, favouring heavy writes.
- LSM tree (Log-Structured Merge): writes go to a WAL and an in-memory sorted memtable. When full, it is flushed as an immutable sorted file (SSTable). Background compaction merges files and drops overwritten or deleted keys.
- Reads check the memtable, then SSTables from newest to oldest. Bloom filters skip files that cannot contain the key, and sparse indexes locate blocks inside a file.
- Used by RocksDB, LevelDB, Cassandra, ScyllaDB, HBase, and MyRocks (MySQL); also inside many NewSQL systems (CockroachDB's Pebble, TiKV).
- B-tree: one copy of each key, updated in place. Predictable reads and range scans; random small writes rewrite whole pages (write amplification) and cause splits.
- Trade-off in three words: write, read and space amplification. LSM = cheap sequential writes, but reads may touch several files, and compaction uses CPU/disk in the background. Leveled compaction favours reads, size-tiered favours writes.
- Deletes in LSM are tombstones; they only disappear after compaction, and many tombstones slow reads (a known Cassandra issue).
Interview questions
- What is an LSM tree and why is it good for writes?
- Compare B-trees and LSM trees.
- What are bloom filters used for in LSM storage?