Interview Q&A · SQL · 12 questions in this topic
Indexes & EXPLAIN — SQL Interview Q&A
Why queries get slow — B-tree indexes, composite order, EXPLAIN plans and the indexing discipline. Part of Indexes & Transactions · 192 questions in the SQL bank.
What is an index and why does it speed up queries?
Answer
An index is a separate lookup structure (usually B-tree) mapping column values to row locations — finding via index seeks O(log n) instead of scanning O(n). The engine maintains it on writes, trading write overhead and space for read speed.
Index the access paths (WHERE, JOIN, ORDER BY) — unindexed foreign keys and filter columns are the classic missing-index finds.
Example
CREATE INDEX idx_emp_dept ON employees (department); -- WHERE department = 'Sales' now seeks instead of scanning
💡 Separate-lookup-structure plus read-vs-write trade-off is the complete definition.
How do B-tree indexes work (conceptually)?
Answer
B-trees keep sorted key-pointer entries in balanced pages: point lookups and range scans descend O(log n), leaves link for ordered traversal. They serve equality, ranges, ORDER BY (matching direction), and prefix LIKE 'abc%'.
Balanced depth means predictable seeks at any table size — the structural reason indexes scale.
Key points
- 1Sorted pages — seeks, ranges, ordered scans.
- 2Balanced — O(log n) at any size.
- 3Prefix-friendly — left-anchored patterns only.
What is a composite index and why does column order matter?
Answer
Composite indexes cover multiple columns with leftmost-prefix matching: (a, b, c) serves a, (a,b), (a,b,c) — but not b alone or c alone. Order by equality-first (high-selectivity equality columns), then ranges, then sort keys.
Design for the query shapes: equality columns left, range/sort right.
Example
CREATE INDEX idx_o_cust_date ON orders (customer_id, created_at); -- serves: customer_id = ? AND created_at > ? (both orders)
What is a covering index (index-only scan)?
Answer
A covering index holds every column the query needs (key plus INCLUDE-d payloads in PostgreSQL/SQL Server) — the engine answers from the index without touching heap rows. EXPLAIN shows Index Only Scan; visibility-map freshness decides how often heap checks intrude.
Cover hot narrow queries; wide INCLUDEs bloat writes — cover selectively.
Example
-- PostgreSQL: payload without key semantics CREATE INDEX idx_cover ON employees (department) INCLUDE (name, salary);
💡 Answer-from-index-without-heap is the covering definition.
How do you read EXPLAIN output?
Answer
EXPLAIN shows the plan tree: scan types (Seq Scan vs Index/Bitmap scans), join algorithms (Nested Loop/Hash/Merge), row estimates vs actuals (EXPLAIN ANALYZE), and total cost. Red flags: Seq Scan on huge tables with selective filters, estimates off by 10x+ (stale statistics), and Materialize over big sorts.
ANALYZE (VACUUM ANALYZE / ANALYZE TABLE) refreshes the statistics plans depend on.
Example
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM employees WHERE department = 'Sales';
💡 Estimates-vs-actuals is the diagnostic gap to read first.
When is a full table scan (Seq Scan) actually fine?
Answer
Small tables (index overhead exceeds scan cost), unselective filters (most rows match anyway), bulk aggregations over whole tables, and tiny lookup tables cached in memory. The planner is usually right to scan — forcing indexes onto 90%-match queries slows them.
Scan-shaming without selectivity context is the novice tell.
Example
-- SELECT COUNT(*) FROM small_lookup; -- scan is correct
What indexes should every schema have (the default set)?
Answer
Primary keys (automatic), foreign keys (manual — not automatic everywhere), frequent WHERE/JOIN columns, composite equality-plus-range shapes, and UNIQUE where business rules demand. Then EXPLAIN-driven additions for proven slow queries — never speculative index piles.
Every index taxes writes: index deliberately, audit periodically (unused-index stats).
Key points
- 1Keys — PKs automatic, FKs manual.
- 2Access paths — WHERE/JOIN/ORDER shapes.
- 3Proof — EXPLAIN-driven, unused pruned.
Example
CREATE INDEX idx_orders_customer ON orders (customer_id); CREATE INDEX idx_orders_date ON orders (created_at DESC);
💡 FKs-manual is the most-missed default to name.
What are partial and expression indexes?
Answer
Partial indexes cover only matching rows (WHERE deleted_at IS NULL) — smaller, faster, conditional-uniqueness capable. Expression indexes cover computed values (LOWER(email), date_trunc) — making functional predicates sargable. Both trade generality for precision on proven query shapes.
Specialized indexes for proven shapes; plain indexes for general access.
Example
CREATE INDEX idx_active ON users (email) WHERE deleted_at IS NULL; CREATE INDEX idx_lower_email ON users (LOWER(email));
💡 Partial-for-subsets, expression-for-functions is the pairing.
Why do indexes slow down writes?
Answer
Every INSERT/UPDATE/DELETE must maintain each index (B-tree insert/split, uniqueness checks) — more indexes, more per-write work, bigger transactions, hotter replication. Bulk loads feel it most; OLTP feels it per statement.
Fast reads cost write maintenance — index count is a deliberate budget, not free seasoning.
Key points
- 1Maintenance — each index updated per write.
- 2Checks — uniqueness verified per insert.
- 3Budget — hot tables deserve fewer, proven indexes.
What is index bloat and VACUUM (PostgreSQL)?
Answer
Updates/deletes leave dead row versions (MVCC) that indexes still point at — bloat slows scans and wastes space. VACUUM reclaims dead space and refreshes visibility maps (enabling index-only scans); ANALYZE refreshes planner statistics; autovacuum handles steady state, manual tuning handles bulks.
Bloated indexes show as slow scans with healthy-looking plans — pgstattuple confirms.
Example
VACUUM (ANALYZE) employees; -- reclaim + refresh stats
💡 Dead-versions-plus-visibility-maps is the bloat mechanics to state.
How do you optimize a slow query (step-by-step)?
Answer
EXPLAIN (ANALYZE) first — find the misestimated/scan-heavy node. Check statistics freshness, missing indexes on join/filter keys, sargability of predicates, and fan-out before aggregates. Fix, re-measure, keep the faster plan. Rewrite (CTE shape, EXISTS vs IN, pre-aggregation) only after access paths are sound.
Measure-first beats guess-first every time.
Key points
- 1Diagnose — EXPLAIN ANALYZE, estimates vs actuals.
- 2Access — indexes, stats, sargability.
- 3Shape — rewrite, then re-measure.
💡 Estimates-first is the methodology sentence.
What is the N+1 query problem and how do you fix it?
Answer
One query fetches parents, then N queries fetch each parent's children (ORM lazy-loading default) — 1+N round trips instead of 1-2. Fix with eager loading (JOIN fetch), batched loaders (WHERE IN (...) / DataLoader), or explicit second queries per level.
ORM convenience hides it; query logs and counters expose it.
Key points
- 1Symptom — query count scales with rows.
- 2Fix — JOIN fetch, IN-batch, DataLoader.
- 3Detect — log and count queries per request.
Example
-- one batched fetch instead of N: SELECT * FROM orders WHERE customer_id IN (...);
💡 Count-queries-per-request is the detection habit.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission