Interview Q&A · SQL · 12 questions in this topic

Indexes & EXPLAIN — SQL Interview Q&A

All SQL topics

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

Example.sqlsql
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

  1. 1Sorted pages — seeks, ranges, ordered scans.
  2. 2Balanced — O(log n) at any size.
  3. 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

Example.sqlsql
CREATE INDEX idx_o_cust_date ON orders (customer_id, created_at);
-- serves: customer_id = ? AND created_at > ? (both orders)

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits