Database Administrator interview questions
100 real questions with model answers and explanations for Middle candidates.
See a Database Administrator resume example →Practice with flashcards
Spaced repetition · Hunter Pass
Questions
A database parses and validates SQL, transforms it into an internal query tree, chooses an execution plan, and runs that plan.
- Parsing checks syntax and resolves referenced objects, columns, types, and permissions.
- Rewriting may expand views or apply engine rules before planning.
- The optimizer compares legal access paths and join orders using statistics and a cost model.
- The executor runs the chosen operators and returns rows while respecting transaction visibility.
Why interviewers ask this: The interviewer checks whether the candidate understands optimization as one stage in a broader query-processing pipeline.
EXPLAIN shows the optimizer's estimated plan, while EXPLAIN ANALYZE executes the statement and adds measured runtime information.
- Estimated rows and costs come from statistics and the engine's cost model.
- Actual rows, loops, and timing reveal how execution differed from estimates.
- Because ANALYZE runs the statement, write queries can change data unless wrapped and rolled back appropriately.
- PostgreSQL options such as BUFFERS expose cache and I/O activity in addition to timing.
Why interviewers ask this: A strong answer distinguishes prediction from measurement and recognizes that execution has real side effects.
These access paths trade startup, random access, and bulk page reading according to estimated selectivity.
- A sequential scan reads table pages and can be efficient when much of the table is needed.
- An index scan follows matching index entries to table rows and suits selective predicates.
- PostgreSQL bitmap scans collect matching row locations first, then visit table pages in a more grouped order.
- The optimizer chooses from estimated page cost, row count, ordering needs, and cache assumptions.
Why interviewers ask this: The interviewer evaluates whether the candidate understands why an index is not automatically the cheapest access path.
The three join algorithms combine inputs through repeated lookup, hashing, or ordered traversal.
- Nested loop scans the inner input for each outer row and performs well when the outer side is small and inner lookups are indexed.
- Hash join builds a hash table from one input and probes it with the other, commonly for equality joins.
- Merge join advances through two inputs sorted on compatible join keys and can handle large ordered sets efficiently.
- Join condition, input size, sort order, memory, and estimates determine which algorithm is eligible and attractive.
Why interviewers ask this: A strong answer connects each join algorithm to its input properties rather than ranking them universally.
Cardinality estimates predict row counts, while cost estimates compare expected resource work in engine-specific units.
- Costs usually combine modeled page access, CPU processing, sorting, and operator startup.
- They are relative planning values and are not direct milliseconds.
- A row-count error early in the plan can lead to a poor join algorithm or join order later.
- Actual execution metrics are compared with estimates to assess whether statistics and assumptions represent the data.
Why interviewers ask this: The interviewer checks whether the candidate can read estimates as optimizer inputs rather than literal runtime promises.
A planner uses summarized data distribution and table size information to estimate predicate and join cardinality.
- Row and page counts estimate relation size.
- Distinct-value counts and NULL fractions estimate equality and missing-value selectivity.
- Histograms approximate range distributions, while most-common-value lists represent skew.
- Extended or multicolumn statistics can describe correlation and dependencies that independent column statistics miss.
Why interviewers ask this: A strong answer identifies the statistics that drive cardinality rather than saying only that the planner uses metadata.
ANALYZE samples table data and updates planner statistics so estimates reflect the current distribution.
- PostgreSQL autovacuum workers can trigger automatic analyze after enough table changes.
- MySQL maintains persistent or sampled statistics with engine-specific refresh behavior.
- The sampling target balances collection cost, catalog size, and precision for skewed data.
- Statistics describe values, not cached query plans forever, so prepared-plan behavior remains a separate concern.
Why interviewers ask this: The interviewer evaluates whether the candidate understands statistics maintenance and its engine-specific automation.
Selectivity is the fraction of rows expected to satisfy a predicate, and it determines how much data each access path must process.
- A unique equality predicate is highly selective because it returns at most one row.
- A Boolean column with evenly split values is usually not selective by itself.
- Skew means a predicate on one common value can behave very differently from one on a rare value.
- The planner estimates selectivity from statistics and combines it with I/O, CPU, and ordering costs.
Why interviewers ask this: A strong answer connects data distribution to access-path choice and avoids judging selectivity from column type alone.
A sargable predicate lets the optimizer map a search condition to an ordered or otherwise searchable index operation.
- Direct comparison of an indexed column to a compatible value is commonly sargable.
- Wrapping the column in a function can prevent ordinary index use unless a matching expression index exists.
- Implicit type conversion on the indexed side can also block an efficient lookup.
- Rewriting preserves query semantics first, because an index-friendly expression is useless if it changes the result.
Why interviewers ask this: The interviewer checks whether the candidate understands how predicate form affects index access without reducing optimization to syntax tricks.
The optimizer normally reorders and combines safe predicates according to its plan rather than following their textual order.
- SQL describes the required result, not an imperative sequence of row tests.
- Predicate pushdown can move filters closer to scans or below joins when semantics permit.
- Volatile functions, outer joins, and error-producing expressions can constrain legal rewrites.
- Performance should be evaluated from the execution plan, not inferred from the condition order in the query text.
Why interviewers ask this: A strong answer understands declarative SQL and recognizes semantic limits on optimizer transformations.
A covering index contains every column needed to satisfy a query, allowing the engine to avoid or reduce table-row lookups.
- Search and join columns form the searchable index key.
- Additional output columns may be included as non-key payload where the engine supports INCLUDE.
- PostgreSQL index-only scans still depend on visibility information to know whether heap access can be skipped.
- Wider indexes consume more storage and write bandwidth, so coverage should target stable, frequent query shapes.
Why interviewers ask this: The interviewer evaluates whether the candidate understands both logical coverage and engine-specific conditions for index-only access.
Column order should follow equality constraints, range boundaries, join keys, and required ordering in the queries the index is meant to serve.
- Leading equality columns narrow the searchable prefix before a later range column.
- Once an unrestricted range is encountered, later columns may filter but often cannot narrow the same index scan efficiently.
- ORDER BY can benefit when its sequence and direction align with the usable index prefix.
- Cardinality alone is not a universal rule because the full predicate and sort shape determine usefulness.
Why interviewers ask this: A strong answer applies leading-prefix behavior to actual query structure rather than repeating a highest-cardinality-first rule.
A partial index stores entries only for rows satisfying a fixed predicate, reducing index size and maintenance for targeted queries.
- An index WHERE status = 'open' can serve queries that select the same open-row subset.
- The planner must be able to prove that the query predicate implies the index predicate.
- Partial unique indexes can enforce uniqueness only within a subset, such as active records.
- They are unsuitable when queries need most excluded rows or when the subset definition changes constantly.
Why interviewers ask this: The interviewer checks whether the candidate understands predicate implication and subset-specific indexing or constraints.
An expression index stores the result of a deterministic expression so matching query expressions can be searched directly.
- An index on lower(email) can support case-normalized equality lookups written with the same semantics.
- The query expression must match the indexed expression closely enough for the planner to recognize it.
- Expression indexes can also enforce uniqueness on a normalized representation.
- Computing and maintaining the expression adds cost to writes and increases schema coupling to query form.
Why interviewers ask this: A strong answer explains expression matching, normalized uniqueness, and maintenance cost.
The operator and data access pattern determine the index type rather than the column type alone.
- B-tree supports equality, ranges, ordering, and prefix scans for sortable values.
- Hash focuses on equality and offers fewer access patterns than B-tree.
- GIN is an inverted index suited to multivalued content such as arrays, full text, and many JSONB operators.
- GiST supports extensible search strategies such as geometric, range, nearest-neighbor, and some text operations.
Why interviewers ask this: The interviewer evaluates whether the candidate maps index access methods to supported operator classes and query patterns.
An index is most attractive when it avoids enough table work to offset traversal and row-fetch cost.
- A predicate returning a tiny fraction of rows often benefits from an index.
- A common value returning most rows may be cheaper to read sequentially.
- Clustering, cache state, row width, and index-only coverage can change the crossover point.
- Skew-aware statistics matter because average distinct counts can misrepresent popular and rare values.
Why interviewers ask this: A strong answer treats selectivity as one part of a cost decision rather than a fixed threshold.
An index can supply matching keys or useful ordering when its leading columns align with the operation.
- An index on a foreign key can make repeated inner lookups in a nested-loop join efficient.
- Ordered index access can avoid a separate sort for a compatible ORDER BY.
- GROUP BY may exploit ordered input for grouped aggregation, though a hash aggregate can still be cheaper.
- One index rarely serves every filter, join, and order permutation, so query families need explicit prioritization.
Why interviewers ask this: The interviewer checks whether the candidate sees indexes as access and ordering structures across multiple plan operators.
Each index consumes storage and adds work to data modification, logging, caching, and maintenance.
- INSERT must add entries to every applicable index.
- UPDATE may change indexed keys or invalidate versions, while DELETE leaves cleanup work according to the engine.
- Random page changes, page splits, and accumulated dead space can increase write amplification.
- Redundant indexes waste resources and may overlap without serving a distinct constraint or query pattern.
Why interviewers ask this: A strong answer describes write-path and lifecycle costs instead of viewing indexes as free read acceleration.
Multiversion concurrency control lets transactions read consistent row versions while other transactions modify the same logical data.
- Readers use a snapshot to decide which versions are visible.
- Writers create or reference new versions instead of overwriting a version visible to every reader immediately.
- This reduces reader-writer blocking but does not eliminate writer conflicts or all locks.
- Old versions require cleanup or reuse after no relevant transaction can see them.
Why interviewers ask this: The interviewer evaluates whether the candidate understands snapshot visibility, versions, and the remaining need for locks and cleanup.
A transaction snapshot defines which committed and in-progress changes are visible to a statement or transaction.
- It records a visibility boundary derived from transaction identifiers or engine-specific version metadata.
- Read Committed commonly acquires a fresh snapshot for each statement.
- Repeatable Read commonly holds one transaction-level view, subject to engine semantics.
- A long-lived snapshot can keep old row versions from becoming reclaimable.
Why interviewers ask this: A strong answer connects snapshot lifetime to isolation semantics and version retention.
Locked questions
- 21
Why does PostgreSQL need VACUUM in its MVCC model?
postgres - 22
How do PostgreSQL tuple versions and InnoDB undo records differ conceptually?
postgres - 23
How do standard transaction isolation levels relate to concurrency anomalies?
transactionsconcurrency - 24
How does Read Committed usually work under MVCC?
- 25
How does Repeatable Read differ between PostgreSQL and MySQL InnoDB?
postgres - 26
What does Serializable isolation guarantee?
serialization - 27
How do dirty read, non-repeatable read, phantom read, and lost update differ?
- 28
What is write skew under snapshot isolation?
snapshot - 29
How do optimistic and pessimistic concurrency control differ?
lockingconcurrency - 30
What is the difference between row-level and table-level locks?
- 31
What does SELECT FOR UPDATE do?
- 32
What is a database deadlock?
databaselocking - 33
What are intention locks?
- 34
What is table partitioning?
partitioning - 35
How do range, list, and hash partitioning differ?
partitioning - 36
What is partition pruning?
partitioning - 37
What makes a good partition key?
partitioning - 38
How does partitioning differ from sharding?
shardingpartitioning - 39
What is physical replication?
replication - 40
What is logical replication?
replication - 41
How do synchronous and asynchronous replication affect commits?
replicationasync - 42
What roles do WAL and binlog play in replication?
replication - 43
What is a PostgreSQL replication slot?
postgresreplication - 44
How do full, incremental, and differential backup strategies affect restore chains?
backups - 45
How does point-in-time recovery work?
- 46
How do stored procedures and stored functions differ?
stored-procedures - 47
What are database triggers, and what trade-offs do they introduce?
database - 48
Why is database connection pooling necessary?
databasepooling - 49
How do PgBouncer session, transaction, and statement pooling modes differ?
transactionssessions - 50
How do prepared statements interact with query planning and connection pools?
queriespooling - 51
A PostgreSQL query became slow after the table grew tenfold. How would you tune it from the execution plan?
queriespostgres - 52
A PostgreSQL plan estimates 100 rows but returns one million. What would you investigate?
estimationpostgres - 53
A large table uses a sequential scan despite having an index on the filter column. How would you diagnose it?
indexesschemaaggregation - 54
How would you design a composite index for a query filtering by tenant and status and sorting by created_at?
indexesqueriesdesign - 55
EXPLAIN ANALYZE shows a large sort spilling to disk. How would you optimize it?
optimization - 56
A hash join is much slower than expected and uses multiple batches. How would you respond?
joinsbatch - 57
An Oracle report changed from a hash join to a nested loop and slowed dramatically. How would you investigate?
joins - 58
The same prepared PostgreSQL statement is fast for most parameters but very slow for a few. How would you diagnose it?
postgres - 59
A query on a partitioned PostgreSQL table scans every partition. How would you restore partition pruning?
queriespostgrespartitioning - 60
A daily aggregation overwhelms the primary database for an hour. How would you optimize the workload?
databaseaggregationoptimization - 61
Users report that updates are hanging. How would you diagnose the PostgreSQL blocking chain?
postgres - 62
How would you analyze and reduce recurring database deadlocks?
databaselocking - 63
Many sessions are idle in transaction and vacuum cannot clean old rows. How would you fix the situation?
transactionssessions - 64
A schema change is waiting for a lock on a busy table. How would you proceed safely?
schema - 65
Autovacuum is running but a high-update table keeps accumulating dead tuples. How would you tune it?
- 66
The database has spare CPU but applications receive too many connections errors. How would you diagnose it?
database - 67
How would you configure PgBouncer for workloads that use prepared statements and session settings?
sessionsconfig - 68
Storage grows by 8 percent per month. How would you build a capacity plan?
capacity - 69
Database CPU is near 90 percent during peak hours. How would you decide between tuning and scaling?
databasescaling - 70
How would you diagnose database memory pressure that causes swapping or OOM kills?
databasememory - 71
Latency rises while CPU remains low and storage IOPS are saturated. How would you respond?
latency - 72
Connection count is growing faster than traffic. How would you forecast and control it?
- 73
How would you set actionable capacity alerts for a production database?
databasecapacityalerting - 74
How would you configure pgBackRest for a large PostgreSQL database with a limited backup window?
databasepostgresconfig - 75
A user asks to restore PostgreSQL to just before an accidental delete. How would you perform PITR safely?
postgres - 76
Backups report success every night. How would you prove they are actually recoverable?
backups - 77
The business requires a 15-minute RPO and a two-hour RTO. How would you translate that into a backup design?
designbackups - 78
A full restore of a multi-terabyte database misses the RTO. How would you shorten recovery?
database - 79
How would you prepare database recovery from a complete cloud-region outage?
database - 80
How would you set up PostgreSQL streaming replication for a new production standby?
postgresreplicationstreaming - 81
A PostgreSQL replica falls hours behind while the network is healthy. How would you diagnose the lag?
postgresreplication - 82
How would you choose synchronous or asynchronous replication for a PostgreSQL workload?
postgresreplicationasync - 83
What safeguards would you require before enabling automatic database failover?
database - 84
How would you configure HAProxy to route database connections during failover?
databaseconfig - 85
An AWS RDS or Aurora failover takes longer than expected. How would you analyze and improve readiness?
health-checks - 86
A MySQL replica stops with a duplicate-key error. How would you recover it safely?
replication - 87
How would you add a NOT NULL column with a default to a large busy table without downtime?
schemafundamentals - 88
How would you create an index on a large PostgreSQL table without blocking production writes?
indexespostgres - 89
How would you change the type of a heavily used column when the direct ALTER rewrites the table?
schema - 90
A backfill of 500 million rows causes replication lag and table bloat. How would you redesign it?
replicationbackfill - 91
How would you safely rename or remove a database column used by several application versions?
databaseschema - 92
How would you coordinate a multi-step schema migration with an application deployment?
schemamigrationsdeployment - 93
A PostgreSQL table is much larger than its live data. How would you assess and reduce table bloat?
postgres - 94
How would you diagnose whether a PostgreSQL index is bloated and decide to rebuild it?
indexespostgres - 95
Autovacuum settings work for most tables but not one very large hot table. How would you tune it without harming the cluster?
- 96
A PostgreSQL database approaches transaction ID wraparound protection. How would you respond?
databasetransactionspostgres - 97
A MongoDB query slows down as a collection grows. How would you diagnose and optimize it?
queriesmongodboptimization - 98
Redis starts evicting keys and latency rises near its memory limit. How would you recover and prevent recurrence?
latencymemoryredis - 99
CockroachDB shows high transaction retries and one range receives most traffic. How would you address it?
transactions - 100
How would you prepare monitoring and automation before putting a new production database into service?
databasemonitoring