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

  1. 3.1 Index fundamentals and B-trees
  2. 3.2 Clustered, secondary and covering indexes
  3. 3.3 Composite indexes and sargable predicates
  4. 3.4 Specialized index types
  5. 3.5 Execution plans and EXPLAIN
  6. 3.6 Statistics, cardinality and the optimizer
  7. 3.7 Joins, sorting and aggregation
  8. 3.8 Query patterns and anti-patterns
  9. 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

  1. What data structure do most relational databases use for a default index?

    1. A hash table, which can only answer range lookups
    2. A linked list of every row, kept in insert order
    3. A B-tree (B+ tree), sorted for equality and range lookups
    4. 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.

  2. In SQL Server, how many clustered indexes can a table have?

    1. As many as the table has columns
    2. Two: one ascending and one descending
    3. One, since it defines the rows' stored order
    4. 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.

  3. A composite index is defined on (last_name, first_name). Which WHERE clause can use it efficiently for a seek?

    1. `WHERE first_name = 'Ana'`
    2. `WHERE first_name = 'Ana' OR last_name = 'Lee'`
    3. `WHERE UPPER(last_name) = 'LEE'`
    4. `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).

  4. A hash index is a good fit for which query?

    1. `WHERE created_at BETWEEN '2026-01-01' AND '2026-02-01'`
    2. ORDER BY last_name
    3. `WHERE name LIKE 'Sm%'`
    4. `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.

  5. What does EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL) show?

    1. The query's SQL text after it has been reformatted
    2. The list of database users who have run the query
    3. The indexes that the database recommends you create
    4. 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.

  6. Why do query optimizers rely on table statistics?

    1. To estimate row counts and pick join orders, join types and indexes
    2. To decide which database users are allowed to run each query
    3. To cache each query's results so they can be reused later
    4. 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.

  7. Which join algorithm is usually best when one input is small and the other has an index on the join key?

    1. Hash join
    2. Merge join on unsorted inputs
    3. Nested loop join
    4. 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.

  8. What is the N+1 query problem?

    1. A query that joins together N+1 tables in a single statement
    2. An index defined with N+1 columns in its composite key
    3. One query for a list, then one more per item, instead of one or two
    4. 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.

  9. What is a materialized view?

    1. A stored query result, refreshed on a schedule or on demand
    2. A view that's recomputed from scratch on every single read
    3. A view that only database administrators are allowed to read
    4. 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.

  10. Why do indexes slow down INSERT, UPDATE and DELETE statements?

    1. Every index on the table must also be updated when indexed data changes
    2. Indexes lock the whole table during every write
    3. Indexes force each write to be rewritten twice to the transaction log
    4. 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.

Practice all 261 questions

More Storage and Data