Indexing and Query Optimization Interview Questions
261 multiple-choice tech interview questions on Indexing and Query Optimization: B-tree, clustered and covering indexes, selectivity, execution plans, sargable queries. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 241 key terms with the flashcards first, then test yourself.
Take the practice test · Flashcards · All study tools
What it covers
- 3.1 Index fundamentals and B-trees
- 3.2 Clustered, secondary and covering indexes
- 3.3 Composite indexes and sargable predicates
- 3.4 Specialized index types
- 3.5 Execution plans and EXPLAIN
- 3.6 Statistics, cardinality and the optimizer
- 3.7 Joins, sorting and aggregation
- 3.8 Query patterns and anti-patterns
- 3.9 Index maintenance and production tuning
Key terms
3.1 Index fundamentals and B-trees
- B-tree index
- A balanced, sorted tree structure that supports equality, range and ordered lookups
- Clustered index
- An index that defines the physical order of rows; a table has at most one
- Covering index
- An index that holds every column a query needs, avoiding base-table lookups
- B-tree
- Shallow sorted tree
- pg_relation_size
- Index size
- Logarithmic cost
- Barely grows
- Index deletes
- Space reused
- Index entry
- Key plus row pointer
- Index overhead
- Space, memory, backups
- Sequential scan
- Read whole table
- Unique index
- Enforces uniqueness
- Oracle NULL keys
- Not indexed
- Write-heavy table
- Few indexes
- Page
- Block of rows
- Buffer cache
- Pages in memory
- Hot column
- Frequent updates
- Index upkeep
- Maintained on writes
- Over-indexing
- Unused indexes
- Narrow key
- More entries per page
- Page split
- Full page divides
- Random vs sequential I/O
- Scattered vs streaming
- Tiny table
- Scan wins
- Key vs index
- Logical vs physical
- Dense index
- Entry per row
- Sparse index
- Entry per block
- MIN/MAX via index
- Read tree ends
- Data volume
- Prod vs dev
- CREATE INDEX
- B-tree by default
- Range delete
- Indexed cleanup
3.2 Clustered, secondary and covering indexes
- Heap
- No clustered index
- CLUSTER
- One-time reorder
- InnoDB clustering
- Primary key
- Key lookup
- Fetch missing columns
- INCLUDE
- Leaf-only columns
- Index-only scan
- Visibility map
- PostgreSQL INCLUDE
- Since version 11
- Wide covering index
- More cost
- Clustering key
- Narrow and increasing
- Range on clustered key
- Few pages
- Volatile key
- Moves rows
- Index-organized table
- Table in PK tree
- Nonclustered PK
- Allowed
- Using index
- Covering read
- Staging heap
- Fast loads
- Forwarded record
- Moved row pointer
- Result order
- Only ORDER BY
- Tuple ID
- Page and slot
- Acceptable lookup
- Few rows
- Local secondary index
- Per shard
- Clustering a heap
- Full rewrite
- 999 indexes
- Nonclustered limit
- Compact covering read
- Fewer pages
- Uniquifier
- Hidden tiebreaker
3.3 Composite indexes and sargable predicates
- Leftmost prefix rule
- A composite index is used when queries filter on its leading column(s)
- Sargable
- A predicate that can use an index seek, such as col >= value rather than FUNC(col) = value
- Partial index
- An index on only the rows that match a condition
- Skip scan
- Probe each leading value
- Selectivity-first myth
- Query patterns matter
- Index-ordered results
- Equality then sort column
- Mixed sort index
- (a ASC, b DESC)
- Bare column
- Math on constant side
- LOWER(email)
- Expression index
- Leading wildcard
- No prefix
- OR predicates
- Bitmap OR or UNION
- Not-equal filter
- Broad match
- COALESCE rewrite
- OR IS NULL
- Redundant index
- Prefix of another
- Reverse composite
- (b, a)
- Index intersection
- Merge single indexes
- IN probes
- Equality per value
- 32 key columns
- Index limit
- Half-open range
- >= and <
- Concatenated filter
- Compare columns
- LEFT() rewrite
- LIKE prefix
- Tenant-first index
- Leading equality
- Constant-side function
- Still sargable
- id + 0
- Disable index
- key_len
- Columns used
- Index condition pushdown
- Filter in engine
3.4 Specialized index types
- GiST
- Geometric and range searches
- SP-GiST
- Space-partitioned trees
- JSON expression index
- Index one field
- pg_trgm
- Trigram matching
- FULLTEXT
- MATCH AGAINST
- Columnstore
- Analytic scans
- Nonclustered columnstore
- Analytics on OLTP
- Bitmap index locking
- Poor for OLTP
- Bitmap index
- Low cardinality
- Unique partial index
- One active row
- Filtered index and parameters
- Can't assume filter
- IVFFlat vs HNSW
- Build vs query speed
- ANN recall
- Approximate results
- Vector operator class
- Match distance
- Hash index safety
- WAL-logged since 10
- B-tree plus trigram
- Prefix and substring
- jsonb_path_ops
- Containment only
- GIN updates
- Many entries per row
- Computed column index
- Expression index
- bloom extension
- Many-column equality
- Array GIN
- Contains and overlaps
- Multi-valued index
- JSON array elements
- Reverse key index
- Spread inserts
- NULLS NOT DISTINCT
- One NULL allowed
- Adaptive hash index
- Automatic hash
3.5 Execution plans and EXPLAIN
- Execution plan
- The steps the optimizer chose to run a query, shown with EXPLAIN
- N+1 problem
- One query for a list plus one query per item, instead of a single batched query
- Keyset pagination
- Paging with WHERE key > last_seen instead of OFFSET
- EXPLAIN ANALYZE on writes
- Really executes
- Plan tree
- Leaves run first
- Misestimate
- Estimated vs actual rows
- Plan cost
- Planner units
- BUFFERS
- Cache hits vs reads
- Bitmap Heap Scan
- Index then ordered pages
- Rows Removed by Filter
- Wasted reads
- loops
- Multiply node time
- Actual plan
- Real row counts
- Seek vs scan
- Jump vs read all
- Thick arrows
- Many rows
- Sort spill warning
- tempdb
- Memory grant
- Sort and hash memory
- type ALL
- Full scan
- const / eq_ref
- Unique lookup
- MySQL EXPLAIN ANALYZE
- Actual timings
- Using filesort
- Extra sort
- auto_explain
- Log slow plans
- Plan visualizers
- depesz, PEV2
- Gather
- Parallel results
- CTE inlining
- PostgreSQL 12
- External merge sort
- work_mem spill
- Index Scan Backward
- Reverse read
- Recheck Cond
- Lossy bitmap
- STATISTICS IO
- Reads per table
- Logical reads
- Stable metric
- DBMS_XPLAN
- Show plan
3.6 Statistics, cardinality and the optimizer
- Histogram
- Value distribution
- MCV list
- Frequent values
- Independence assumption
- Multiplied selectivity
- Extended statistics
- Column dependencies
- Auto update statistics
- Change threshold
- Ascending key problem
- New values unseen
- Compatibility level
- Cardinality estimator
- Cost-based optimizer
- Cheapest estimate
- GEQO
- Many-join heuristic
- Plan cache
- Reuse compiled plans
- Sniffing fixes
- RECOMPILE, OPTIMIZE FOR
- Generic vs custom plan
- Prepared statements
- Query hint
- Forced choice
- pg_hint_plan
- Hints extension
- Plan forcing
- Query Store
- Adaptive join
- Runtime join choice
- PSP optimization
- Plans per value range
- Statistics target
- Bigger samples
- Table variable estimates
- Deferred compilation
- Scalar UDF inlining
- SQL Server 2019
- MySQL histogram
- ANALYZE TABLE
- Data skew
- One plan won't fit
- random_page_cost
- Random I/O cost
- effective_cache_size
- Cache estimate
- RECOMPILE cost
- CPU per run
- FULLSCAN
- Exact statistics
- Join error propagation
- Compounding errors
3.7 Joins, sorting and aggregation
- Hash join
- Hash smaller input
- Build and probe
- Hash then stream
- Merge join
- Pre-sorted inputs
- Range join
- No hash join
- Hash batches
- Spill to disk
- Unindexed nested loop
- Rows × rows
- Join order
- Small intermediates
- Semi-join
- Stop at first match
- Hash vs sort aggregate
- GROUP BY strategies
- Streaming aggregate
- Pre-grouped input
- Sort before merge
- Unordered input
- reltuples
- Approximate count
- Top-N heapsort
- Keep best rows
- ORDER BY RANDOM()
- Sorts everything
- Window sort
- Partition and order
- DISTINCT ON
- Latest per group
- Parallel aggregate
- Partial then final
- Join elimination
- Drop unneeded joins
- Partition-wise join
- Pairwise partitions
- Pre-aggregation
- Summarize before join
- COUNT(DISTINCT)
- Sort or hash values
- LIMIT misplan
- Early-match guess
- Cartesian product
- Missing join condition
- Collation cost
- Slower text compares
- Incremental sort
- Sort within groups
- Hash aggregate memory
- Entry per group
- Database aggregation
- Less data shipped
3.8 Query patterns and anti-patterns
- Long IN list
- Use temp table or array
- Variable IN lists
- Plan cache bloat
- Batched commits
- Fewer log flushes
- Batched deletes
- Short transactions
- Catch-all query
- One plan for all
- RBAR
- Row by agonizing row
- EXISTS vs COUNT
- Stop at first
- No-op update filter
- Skip unchanged rows
- Soft-delete buildup
- Dead rows in scans
- Temp table
- Indexes and stats
- In-memory paging
- Wasted rows
- Expression sort
- No index
- RETURNING
- Update and read
- Total time
- Cost × frequency
- Load behavior
- Concurrency costs
- JSON fields
- No stats or indexes
- uuid type
- 16 bytes
- String dates
- Broken ranges
- Counter cache
- Stored count
- Nested views
- Hidden work
- Trigger cost
- Hidden write work
- Wide rows
- Fewer per page
- Arbitrary sorting
- Unindexed sorts
- Combined dashboard query
- One pass
- text_pattern_ops
- LIKE prefix
- Ad hoc LIMIT
- Cap results
- CASE in WHERE
- Blocks seeks
3.9 Index maintenance and production tuning
- CREATE INDEX CONCURRENTLY
- No write blocking
- Invalid index
- Failed concurrent build
- ONLINE = ON
- Usable during build
- REBUILD vs REORGANIZE
- Recreate vs compact
- Fragmentation on SSD
- Matters less
- REINDEX CONCURRENTLY
- Online rebuild
- Fill factor
- Page headroom
- idx_scan
- Index usage
- Usage DMV reset
- Restart clears counts
- Missing-index DMVs
- Hints, not orders
- Invisible index
- Ignored by optimizer
- pg_stat_statements
- Per-query totals
- Query Store
- Plans and runtime history
- Slow query log
- long_query_time
- pt-query-digest
- Rank slow queries
- Concurrent MV refresh
- Unique index needed
- Indexed view
- Stored view results
- Partition maintenance
- Per-partition rebuild
- Upgrade plan capture
- Spot regressions
- Automatic tuning
- Index and plan fixes
- HypoPG
- Hypothetical indexes
- Wait statistics
- Where time goes
- pg_stat_activity
- Live sessions
- Overnight regression
- Plan change
- seq_scan count
- Missing index hint
- Disabled index
- Definition only
Sample practice questions
What data structure do most relational databases use for a default index?
- A hash table, which can only answer range lookups
- A linked list of every row, kept in insert order
- A B-tree (B+ tree), sorted for equality and range lookups
- A bitmap with one bit for every possible value
Answer: C. A B-tree (B+ tree), sorted for equality and range lookups B+ trees keep data sorted in balanced pages, so lookups, ranges and ORDER BY can all use them.
In SQL Server, how many clustered indexes can a table have?
- As many as the table has columns
- Two: one ascending and one descending
- One, since it defines the rows' stored order
- None; clustered indexes are Oracle-only
Answer: C. One, since it defines the rows' stored order The clustered index is the table's data. Other indexes are nonclustered and point back to the clustered key.
A composite index is defined on (last_name, first_name). Which WHERE clause can use it efficiently for a seek?
- `WHERE first_name = 'Ana'`
- `WHERE first_name = 'Ana' OR last_name = 'Lee'`
- `WHERE UPPER(last_name) = 'LEE'`
- `WHERE last_name = 'Lee'`
Answer: D. `WHERE last_name = 'Lee'` The leftmost-prefix rule: a composite index helps when the query filters on its leading column(s).
A hash index is a good fit for which query?
- `WHERE created_at BETWEEN '2026-01-01' AND '2026-02-01'`
- ORDER BY last_name
- `WHERE name LIKE 'Sm%'`
- `WHERE session_id = 'abc123'`
Answer: D. `WHERE session_id = 'abc123'` Hash indexes support equality only. Range scans, sorting and prefix matches need an ordered structure such as a B-tree.
What does EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL) show?
- The query's SQL text after it has been reformatted
- The list of database users who have run the query
- The indexes that the database recommends you create
- The chosen plan; with ANALYZE, actual rows and timings too
Answer: D. The chosen plan; with ANALYZE, actual rows and timings too Compare estimated and actual row counts: big differences usually mean stale statistics.
Why do query optimizers rely on table statistics?
- To estimate row counts and pick join orders, join types and indexes
- To decide which database users are allowed to run each query
- To cache each query's results so they can be reused later
- To decide how to compress the table's data pages on disk
Answer: A. To estimate row counts and pick join orders, join types and indexes Outdated statistics lead to poor cardinality estimates and bad plans. ANALYZE (PostgreSQL) and UPDATE STATISTICS (SQL Server) refresh them.
Which join algorithm is usually best when one input is small and the other has an index on the join key?
- Hash join
- Merge join on unsorted inputs
- Nested loop join
- Cartesian join
Answer: C. Nested loop join For each row of the small input, the engine seeks the index on the large one. Hash joins suit large unsorted inputs; merge joins suit sorted inputs.
What is the N+1 query problem?
- A query that joins together N+1 tables in a single statement
- An index defined with N+1 columns in its composite key
- One query for a list, then one more per item, instead of one or two
- A loop that accidentally skips the last row of the results
Answer: C. One query for a list, then one more per item, instead of one or two Fix it by joining, batching IDs into one query, or using eager loading in an ORM.
What is a materialized view?
- A stored query result, refreshed on a schedule or on demand
- A view that's recomputed from scratch on every single read
- A view that only database administrators are allowed to read
- A temporary table that disappears when the session ends
Answer: A. A stored query result, refreshed on a schedule or on demand SQL Server's indexed views and PostgreSQL's REFRESH MATERIALIZED VIEW are examples. The tradeoff is staleness or refresh cost.
Why do indexes slow down INSERT, UPDATE and DELETE statements?
- Every index on the table must also be updated when indexed data changes
- Indexes lock the whole table during every write
- Indexes force each write to be rewritten twice to the transaction log
- Writes must scan the entire index before inserting
Answer: A. Every index on the table must also be updated when indexed data changes Each index is a separate structure to maintain. Add indexes for real query needs, not speculatively.
More Storage and Data
- Relational Database Design and Normalization
- SQL Queries, Joins and Window Functions
- Transactions, ACID and Isolation Levels
- NoSQL Databases: Document, Key-Value, Wide-Column and Graph
- Caching: Redis, CDNs and Cache Invalidation
- ORMs: Entity Framework Core and Hibernate
- Data Warehousing and ETL
- Message Queues and Event Streaming: Kafka, RabbitMQ and Service Bus
- Blob and Object Storage
- Backups, Replication and Disaster Recovery