Databases & SQL Interview Questions: Database Performance
Reviewed by Mark Dickie · Last updated
16 questions on this page you can answer and see marked on the spot. Go to the first one
Database performance is the study of how fast a database system can read and write data under a given workload, and what slows it down. For interviews, you should know how indexes work (B-tree vs. hash, covering indexes, when an index is ignored), how to read an execution plan, and the common causes of slow queries: full table scans, N+1 queries, missing or redundant indexes, and poorly written joins.
The table below maps the core performance topics you are likely to be tested on:
| Topic | What an interviewer checks |
|---|---|
| Indexing strategy | Whether you can pick the right index type and explain trade-offs |
| Query execution plans | Whether you can interpret EXPLAIN output and spot inefficiencies |
| Join optimization | Whether you understand join algorithms and join ordering |
| Connection and lock contention | Whether you can diagnose blocking, deadlocks, and pool exhaustion |
| Data modeling for speed | Whether you can normalize enough without hurting read performance |
What does a database performance interview test?
Most interviewers focus on whether you can look at a slow query and form a concrete plan to fix it. That usually means walking through the following steps:
- Read the execution plan and identify the expensive operator (scan, sort, hash).
- Check whether an index exists on the columns used in the filter, join, and sort.
- Decide whether a covering index or a composite index would help, and in what column order.
- Rewrite the query if the structure prevents index usage, such as a function wrapping an indexed column.
- Consider whether the data model itself forces the problem, and whether denormalization or partitioning is worth the trade-off.
How do you read an EXPLAIN plan in SQL?
An execution plan shows the sequence of operations the query engine uses to return results. Look for the operator type (scan vs. seek), the estimated cost per node, row-count estimates, and whether a sort or hash is happening early. A key thing to watch for is a large gap between estimated and actual rows, which usually means stale statistics. If you see a full table scan on a large table where a filter is applied, that is a strong signal an index is missing or not usable.
Key facts
- Tarmac has 63 Databases & SQL interview questions on this topic, 25 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 3,405 job postings asking for Databases & SQL in November 2026.
- Roles asking for Databases & SQL advertise a median base salary of £70,000, across 1,264 job postings as of November 2026.
- Tarmac last reviewed these Databases & SQL interview questions on 13 October 2026.
At a glance
| Questions | 25 shown · 63 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | Multiple choice, True / false, Fill in the blank, Short answer, Ordering, Code output, Multiple answer, Find the bug |
What you'll review
- db performance
- query planning
- n plus one
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
Which of the following is the primary purpose of adding an index to a database table column?#
Options
Show answer
The primary purpose of a database index is to speed up data retrieval queries. An index (typically a B-tree) lets the database jump directly to matching rows instead of scanning the whole table, dramatically reducing query time for large datasets. Enforcing uniqueness or preventing NULLs requires separate constraints, not an index.
An index is a data structure (commonly a B-tree) that the database maintains alongside a table so that rows matching a WHERE clause or ORDER BY can be located without scanning every row. While a UNIQUE index also enforces uniqueness, that is a secondary effect — the primary purpose of an index is faster reads. Indexes do not compress data or prevent NULLs.
Adding an index to every column of a large table is always a good performance optimization because it makes every possible query faster.#
Options
Show answer
False — indexing every column actually hurts overall performance. While indexes speed up SELECT queries, they add overhead to every INSERT, UPDATE, and DELETE because each index must be updated. They also use extra disk space. Good practice is to index only the columns that appear frequently in WHERE, JOIN, or ORDER BY clauses.
Indexes speed up reads but slow down writes (INSERT, UPDATE, DELETE) because the database must maintain each index whenever data changes. They also consume additional disk space. Over-indexing is a common anti-pattern: only columns that appear frequently in WHERE, JOIN, or ORDER BY clauses benefit enough to justify the write overhead and storage cost.
In PostgreSQL, to see the planner's chosen strategy for a query without executing it, you prefix the query with the keyword _____. The output is called a query _____.#
Show answer
In PostgreSQL, to see the planner's chosen strategy for a query without executing it, you prefix the query with the keyword EXPLAIN. The output is called a query plan.
In PostgreSQL, a plain EXPLAIN before a statement makes the query planner return its chosen execution plan, showing operations such as sequential scans, index scans, and joins with estimated costs, and it does not run the query. The output is therefore called a query plan. Other engines use different commands (for example, SQLite uses EXPLAIN QUERY PLAN and SQL Server uses SHOWPLAN settings), so the dialect is pinned to PostgreSQL here.
What is the primary purpose of a database index?#
Show answer
The primary purpose of a database index is to speed up data retrieval (SELECT query) performance by providing a fast lookup structure so the database does not have to scan every row in a table.
A database index is a data structure that allows the database engine to find rows matching a query predicate without scanning the entire table. This makes SELECT queries with WHERE clauses much faster. Indexes do add overhead to inserts, updates, and deletes because the index must be maintained alongside the table data.
Consider the query SELECT name FROM users WHERE email = '[email protected]';, where name appears only in the SELECT list and email is the only filtered column. Adding a B-tree index on name (and no index on email) will let the planner perform an index seek to look up rows by email for this query.#
Options
Show answer
A B-tree index on name does not let the planner seek rows by email for WHERE email = ..., because its entries contain no email values to search. The planner may still scan that index in full, but that is not a lookup by email. Efficient lookup requires an index on email.
The statement is false. An index seek needs an index whose keys include email, so it can jump directly to matching entries. A B-tree index on name holds only name values, so it cannot be used to seek or look up rows by email. The planner could still read the whole name index in full and fetch each table row to check email, which is a full scan rather than a lookup by email, and PostgreSQL rarely chooses it for this query. Efficient lookup by email requires an index on email.
The query planner follows a general pipeline when processing a SQL query. Arrange these steps in the correct order from first to last:#
Put these in order
Show answer
The correct order is: Parse → Rewrite → Plan/Cost → Execute. First the SQL text is parsed into a parse tree. Then the tree is rewritten (e.g., views expanded). Next the planner generates candidate plans and estimates costs using table statistics. Finally, the cheapest plan is selected and executed. This pipeline is standard across major relational databases like PostgreSQL and MySQL.
A relational query planner works in four major stages: (1) Parsing — the SQL string is lexed and parsed into a structured parse tree, catching syntax errors early. (2) Rewriting — the parse tree is transformed by applying rewrite rules such as view expansion, subquery flattening, and constant folding. (3) Planning / Optimization — the planner enumerates candidate execution plans (e.g., which indexes to use, which join algorithm to apply) and estimates the cost of each using table statistics (row counts, histograms). (4) Execution — the chosen lowest-cost plan is executed by the storage engine. This pipeline is consistent across PostgreSQL, MySQL, and most other RDBMSs.
A table orders has 10 million rows. A developer runs the following query frequently:#
Options
Show answer
Creating an index on the customer_id column is the most direct improvement. Without it, the database performs a full table scan over all 10 million rows. An index allows the engine to do an O(log n) lookup instead, drastically reducing I/O. Selecting fewer columns helps with data transfer but does not eliminate the expensive scan.
Without an index on customer_id, the database must perform a full table scan over all 10 million rows for every query. Creating an index on customer_id allows the database engine to use a B-tree (or similar) lookup and retrieve matching rows in O(log n) time instead of O(n). Reducing the selected columns can reduce data transfer but doesn't eliminate the costly scan, and partitioning on id doesn't help filter by customer_id.
In PostgreSQL 17, a B-tree index defined as CREATE INDEX idx ON orders (status, created_at) can perform an index range seek on created_at for the filter WHERE created_at > '2024-01-01' when the query has no condition on status.#
Options
Show answer
False. In PostgreSQL 17, a B-tree index on (status, created_at) cannot perform a range seek on created_at alone when the query has no condition on status. PostgreSQL 17 has no skip scan (that arrived in PostgreSQL 18), so the qualifying created_at values are spread across every status group and form no single contiguous range to seek.
The statement is false for PostgreSQL 17 specifically. A B-tree index is sorted by its columns in order, so entries are ordered by status first and created_at second within each status value. Without a condition on the leading column status, the rows with created_at greater than the cutoff are scattered across every status group, so there is no contiguous range the index can seek to. PostgreSQL 17 does not perform skip scans, which is the feature that would work around this (added in PostgreSQL 18). The planner may still read the whole index or choose a sequential scan, but that is not a range seek on created_at. Constraining status (for example WHERE status = 'shipped' AND created_at > '2024-01-01') lets the index seek directly to the matching range.
A slow SQL query has been reported in production. Arrange the following diagnostic and remediation steps in the most logical order, from first to last.#
Put these in order
Show answer
The correct order is: (1) Identify the slow query using logs or monitoring tools, (2) run EXPLAIN/EXPLAIN ANALYZE to inspect its execution plan, (3) create or adjust an index based on what the plan reveals, and (4) re-run EXPLAIN and benchmark to confirm the improvement. This order ensures you diagnose the root cause before applying a fix, and verify results afterward.
The correct workflow is: (1) Identify which query is slow using logs or monitoring, (2) Inspect its execution plan with EXPLAIN to understand why it's slow (e.g., full table scan, missing index), (3) Apply the appropriate fix such as adding an index, and (4) Verify with EXPLAIN and benchmarking that the change actually improved performance. Skipping the EXPLAIN step before making changes is a common mistake that can lead to ineffective or even harmful modifications.
A PostgreSQL table employees has a B-tree index created with CREATE INDEX idx_dept_sal ON employees(department, salary). Within this index, entries are ordered first by one column, and only entries with equal values in that column are ordered by the second column. Name the first column that determines the overall sort order of the index entries.#
Show answer
department. The index's first key column, department, determines the primary sort order of the entries, and salary is only used to order rows that share the same department.
A PostgreSQL B-tree over (department, salary) sorts all entries by department first. Only among entries that have the same department value are they then sorted by salary. So the correct answer is the column department, which is the first key column of the index and the primary sort key. This is a deterministic fact about how multi-column B-tree indexes are ordered, and it holds in all current PostgreSQL versions.
An ORM-style loop loads authors and then accesses each author's books lazily. Each query() call sends exactly one SQL statement to the database. Assume authors returns 5 rows. How many SQL queries are executed in total? Answer with a number.#
queries = 0
def query(sql):
global queries
queries += 1
return []
authors = [1, 2, 3, 4, 5] # result of the query below
query("SELECT * FROM authors")
for author_id in authors:
query(f"SELECT * FROM books WHERE author_id = {author_id}")
print(queries)Show answer
6
This is the classic N+1 pattern. One query fetches the authors, then the loop sends one more query for each of the 5 authors, so the total is 1 + 5 = 6. The fix is to batch the second step into a single WHERE author_id IN (...) query or a JOIN, which is what eager loading does (for example selectinload or joinedload in SQLAlchemy, prefetch_related in Django). That brings it down to 2 queries or 1, however many authors there are.
A table employees has a composite B-tree index defined as:#
Options
Show answer
A filter on first_name alone does not satisfy the leftmost-prefix rule for an index on (last_name, first_name, dob). A composite B-tree index is ordered by its leading column first, so a predicate that omits last_name cannot use that ordering as a prefix. Clauses that include last_name, the leading column, all satisfy the rule.
A composite B-tree index is ordered by its columns in sequence, so it can be searched using a leftmost prefix of those columns. For (last_name, first_name, dob), the clauses on last_name alone, on last_name plus first_name, and on all three columns each start with the leading column and therefore satisfy the leftmost-prefix rule. The clause on first_name alone omits the leading column, so it does not satisfy the rule. Some optimizers have exceptions such as Oracle index skip scan or MySQL 8.0 skip-scan range access that can still use the index for such a filter, but that is an optimizer-specific exception, not what the leftmost-prefix rule permits.
You run EXPLAIN ANALYZE on a slow query in PostgreSQL. Which of the following are valid and actionable insights you can directly obtain from its output? Select all that apply.#
Options
Pick every one that applies.
Show answer
From EXPLAIN ANALYZE output you can directly learn: the access method chosen for each table (Sequential Scan vs. Index Scan), estimated vs. actual row counts at every plan node — crucial for spotting stale statistics — and the total wall-clock execution time. Network latency between client and server and specific OS page-cache blocks read are not reported in EXPLAIN ANALYZE output.
EXPLAIN ANALYZE executes the query and annotates each plan node with estimated cost/rows, actual rows returned, and actual timing (wall-clock time per node and total). This lets you identify bad row-count estimates (estimated vs. actual rows) and expensive nodes (total wall-clock execution time). Network latency is outside the scope of the query planner output entirely. Buffer/block-level cache statistics are only visible with EXPLAIN (ANALYZE, BUFFERS) and even then show buffer hit counts, not specific block addresses.
In PostgreSQL, after loading millions of new rows into a table, the query planner may choose poor plans because its internal _____ for that table are stale. Running the single-keyword PostgreSQL SQL command _____ on the table refreshes them (do not use VACUUM ANALYZE). Separately, if a WHERE clause is estimated to match a very large fraction of the table, the planner's estimated fraction of matching rows, a value between 0 and 1 known as _____, is large, and the planner may prefer a sequential scan over an index scan.#
Show answer
In PostgreSQL, after loading millions of new rows into a table, the query planner may choose poor plans because its internal statistics for that table are stale. Running the single-keyword PostgreSQL SQL command **ANALYZE** on the table refreshes them (do not use VACUUM ANALYZE). Separately, if a WHERE clause is estimated to match a very large fraction of the table, the planner's estimated fraction of matching rows, a value between 0 and 1 known as selectivity, is large, and the planner may prefer a sequential scan over an index scan.
This is PostgreSQL-specific. The planner estimates row counts and value distributions from its planner statistics: per-table figures such as reltuples and relpages live in pg_class, and detailed per-column value distributions live in pg_statistic. After a large bulk load these estimates can be badly out of date, so the planner's row estimates go wrong. Running the standalone ANALYZE command samples the table and refreshes those statistics; VACUUM ANALYZE is excluded by the wording because the question asks for the single-keyword command. Separately, selectivity is the fraction of a table's rows that a predicate matches, so a predicate estimated to match a large share of rows has a large selectivity value; because reading most of the table through an index means many random page reads, the planner often prefers a sequential scan in that case.
Complete the two blanks in this PostgreSQL EXPLAIN sentence. Write each blank as the exact plan node name that EXPLAIN prints (two words, capitalized as in the output, no abbreviations or alternate names).#
Show answer
Complete the two blanks in this PostgreSQL EXPLAIN sentence. Write each blank as the exact plan node name that EXPLAIN prints (two words, capitalized as in the output, no abbreviations or alternate names).
"When PostgreSQL reads every row in a table without using an index, the plan node is printed as **Seq Scan**. When it uses an index to find matching row pointers and then fetches each row's non-indexed columns from the heap one row at a time, with no bitmap built first and no heap access skipped, the plan node is printed as **Index Scan**."
In PostgreSQL's EXPLAIN output, a full-table read with no index is printed as Seq Scan, which reads every page of the table from start to finish. The row-by-row index path is printed as Index Scan: it walks the B-tree (or other index) to find matching row pointers and follows each one to the heap to fetch columns not stored in the index. It is distinct from Bitmap Heap Scan, which is preceded by a Bitmap Index Scan that collects all matching tuple IDs into a bitmap before visiting heap pages in physical order, and from Index Only Scan, which skips the heap when the index covers all needed columns and the visibility map shows the pages are all-visible.
A developer adds the following index and query to power a leaderboard page that should show the top 10 players (highest scores) for a given game. The query returns incorrect results. Identify the line that contains the bug.#
CREATE INDEX idx_leaderboard
ON player_scores (game_id, score);
SELECT player_id, score
FROM player_scores
WHERE game_id = 7
ORDER BY score ASC
LIMIT 10;Options
Show answer
Line 7 — ORDER BY score ASC returns the 10 lowest scores; it should be ORDER BY score DESC to retrieve the top (highest) 10 scores
The intent is to fetch the top 10 players by highest score, making this a leaderboard. ORDER BY score ASC LIMIT 10 is a purely logical bug: it returns the 10 lowest scores, not the highest. Changing it to ORDER BY score DESC LIMIT 10 fixes the correctness issue. Importantly, B-tree indexes on (game_id, score) support both forward (ASC) and backward (DESC) scans with equal efficiency — modern optimizers (PostgreSQL, MySQL, SQL Server) simply traverse the index leaf pages in the opposite direction for DESC, incurring no extra cost. So the bug is entirely about correctness, not performance. The claim that the index should be on (score, game_id) instead of (game_id, score) is wrong: (game_id, score) is the correct column order — placing the equality-filtered column (game_id) first and the sort column (score) second is the standard pattern for this access pattern. The claim that LIMIT is incompatible with indexed lookups and should be removed is wrong: LIMIT actually enables an early-stop optimization, reducing work. The claim that WHERE game_id = 7 should use a range predicate (e.g., game_id >= 7) to allow the index to be used is wrong: WHERE game_id = 7 is an exact equality predicate, which is ideal for the leading index column and allows the index to be used efficiently.
This pseudocode renders a list of posts with their author names but is slow on large lists. What is the performance bug?#
posts = db.query("SELECT id, author_id, title FROM posts")
for post in posts:
author = db.query(
"SELECT name FROM authors WHERE id = ?", post.author_id)
render(post.title, author.name)Options
Show answer
It is an N+1 query: 1 query for the posts plus one extra query per post to fetch its author
This is the N+1 query problem: one query loads N posts, then the loop fires one additional query per post to fetch its author — N+1 round trips total. Replace it with a single JOIN (or a batched WHERE id IN (...) over the collected author ids) so the database returns posts and author names in one round trip.
You have a PostgreSQL table orders(id, customer_id, status, created_at, total) with a composite B-tree index idx_cs on (customer_id, status, created_at). Write a query (or describe its predicate structure) that gives the index seek the tightest possible bounds on all three columns of idx_cs, so that all three appear as Index Cond in EXPLAIN when the planner chooses the index. Explain the principle.#
Show answer
Use equality conditions on the two leading columns and a range condition on the third, e.g. SELECT * FROM orders WHERE customer_id = 42 AND status = 'shipped' AND created_at >= '2024-01-01';. Equality on customer_id pins a contiguous sub-range of the B-tree, and equality on status narrows it further to one (customer_id, status) group. Within that group the index entries are sorted by created_at, so the range on created_at becomes a tight seek bound rather than a row-by-row filter. Leading equality predicates are what bound the scan tightly; whether the planner picks this index still depends on statistics and cost.
The query pins customer_id and status with equality predicates, which restricts the B-tree scan to one contiguous group of entries. Within that group the entries are ordered by created_at, so the created_at >= '2024-01-01' range bounds the scan further and can be shown in Index Cond alongside the two equality columns. The principle is that leading equality predicates make the index scan tightly bounded and let later key columns narrow it precisely; the answer does not claim that later columns are impossible as Index Cond without leading equality, and the actual EXPLAIN output still depends on the planner's cost choice.
A PostgreSQL table orders has 10 million rows. A B-tree index exists on the status column. The following query ignores the index and performs a sequential scan:#
Options
Show answer
The planner correctly chooses a sequential scan because fetching ~9.4 million rows via random index lookups would be far more expensive than one sequential pass over the heap. PostgreSQL's cost model weights random I/O (random_page_cost) higher than sequential I/O (seq_page_cost), so when a predicate matches a large fraction of rows the index offers no benefit.
PostgreSQL's query planner chooses between a sequential scan and an index scan based on cost estimates derived from statistics (pg_statistic). When a predicate matches a large fraction of rows (e.g., a low-selectivity condition like status = 'active' on a table where 95% of rows are active), the planner correctly decides that reading the entire heap sequentially is cheaper than random index lookups plus heap fetches. The planner uses the page-level cost model: random I/O has a higher cost constant (random_page_cost) than sequential I/O (seq_page_cost). An index is only beneficial when selectivity is high (few rows returned). Options about outdated statistics (ANALYZE not run) and fillfactor are distractors — the described behavior is correct planner behavior, not a bug.
Place the following PostgreSQL query-processing stages in the correct order, from first to last, for a standard SELECT query.#
Put these in order
Show answer
The correct order is: (1) Parser – converts raw SQL into a parse tree; (2) Analyzer & Rewriter – resolves names and expands views; (3) Planner/Optimizer – costs candidate plans and picks the cheapest; (4) Executor – walks the plan tree to produce result rows. Each stage transforms the query representation before handing it to the next.
The correct sequence for how PostgreSQL processes a query through the planner/optimizer is: (1) Parser – turns SQL text into a parse tree; (2) Analyzer/Rewriter – resolves names, applies rules/views to produce a query tree; (3) Planner/Optimizer – generates and costs candidate plans using statistics, then selects the cheapest; (4) Executor – executes the chosen plan. Understanding this pipeline is essential for diagnosing why plans are chosen and how statistics feed into cost estimation.
PostgreSQL 15 table orders has about 50 million rows. Roughly 10 million rows have status = 'pending', and nearly all of those were created in the last 7 days. The other ~40 million rows are older completed orders. status has about 4 distinct values and created_at is a high-cardinality timestamp. The table has no indexes except the primary key on id.#
Options
Show answer
The composite index on (status, created_at) best supports this query. Postgres jumps to the pending rows and reads them already in created_at order, stopping after 100 rows. Indexes leading with created_at must scan many older completed orders first, and a status-only index forces a sort of millions of pending rows.
The composite index (status, created_at) stores pending rows contiguously and in created_at order. Postgres can seek to the 'pending' prefix, read the index entries in order, fetch the user_id for each, and stop after 100 rows because of the LIMIT, so it touches about 100 pending rows. An index on (created_at) alone must walk the index from the oldest timestamps forward, and since every pending row is recent, it passes through roughly 40 million completed rows before it finds 100 matches. The index on (created_at, status) has the same problem, because status can only filter entries during that walk and cannot narrow the starting point. An index on (status) alone finds all roughly 10 million pending rows and has to sort them by created_at before returning 100, which is far more work than reading the top 100 directly from the composite index.
In PostgreSQL's MVCC implementation (current major versions), table and index bloat can degrade performance over time. Which of the following statements about bloat and its remediation are correct? (Select all that apply.)#
Options
Pick every one that applies.
Show answer
In PostgreSQL, dead tuples cannot be vacuumed while an open snapshot may still need them, and a long-running SELECT pins the xmin horizon. VACUUM FULL rewrites the table under a long ACCESS EXCLUSIVE lock, while pg_repack locks only briefly at start and end. HOT updates do not eliminate index bloat when indexed columns change.
The statement about dead tuples awaiting old snapshots is correct: VACUUM may only remove a row version once no snapshot could still see it. VACUUM FULL rewrites the table into a new file while holding ACCESS EXCLUSIVE for the whole operation, blocking reads and writes. pg_repack builds a copy in the background and takes ACCESS EXCLUSIVE only briefly at the start and end (it also needs a primary key or unique index), so it avoids a long blocking window. A long-running SELECT holding a snapshot pins the xmin horizon, so tuples deleted by transactions committing after that snapshot cannot be removed. The HOT statement is wrong: HOT only applies when no indexed column changes and the new version fits on the same page, so updates that change indexed columns still create new index entries and cause index bloat.
A PostgreSQL developer runs the following query, which returns exactly one row but takes ~900 ms:#
Show answer
Run ANALYZE transactions;. It samples the table and recomputes the per-column statistics the planner relies on (such as n_distinct, most-common-values, and histogram data for account_id) to estimate how many rows match account_id = 42. Because the estimate of 50000 rows is far from the actual 1, recomputing statistics is the standard first step to test whether outdated or insufficient statistics explain the bad plan; if the estimate stays wrong afterward, the cause lies elsewhere, such as a low statistics target or a heavily skewed column.
ANALYZE on a table samples its rows and updates the planner's column statistics (n_distinct, most-common-values, and histogram bounds), which drive the selectivity estimate for a predicate like account_id = 42. The command requested is the statistics-only form, ANALYZE transactions;, which is distinct from VACUUM ANALYZE because it does not run vacuum and does not remove dead tuples or mark space reusable. The EXPLAIN output does not by itself prove the statistics are stale; it only shows the estimate is far off. Refreshing statistics is the appropriate first check, and if the estimate remains wrong, the statistics target or column skew should be investigated next.
A table events has ~500 million rows and this composite B-tree index:#
Show answer
In a B-tree, entries are sorted by the full key tuple, so with (status, created_at) all entries for status = 'PENDING' are stored together, and within that block they are sorted by created_at. The equality on the leading column locates one contiguous block, and the condition created_at > NOW() - INTERVAL '7 days' selects a contiguous sub-range at the end of it. Because that sub-range is already ordered by created_at, a backward index scan can return rows in ORDER BY created_at DESC order and stop after 100 matches, so no Sort node is needed.
With the key order (status, created_at), the index is sorted first by status and then by created_at inside each status value. The equality predicate on status therefore pins down one contiguous block of index entries, and the created_at range is a contiguous sub-range within that block. Entries inside that sub-range are already in created_at order, so the ORDER BY created_at DESC LIMIT 100 can be served by a backward scan of the index that stops after 100 matching rows, avoiding an explicit sort. The argument rests on the sort order of the key tuple, not on how many distinct status values exist.
In PostgreSQL, a long-running OLAP query runs for 4 hours on a table that receives heavy OLTP writes. After the query completes, the DBA notices severe table and index bloat even though autovacuum is enabled. Which of the following accurately explain(s) why this happened? (Select all that apply.)#
Options
Pick every one that applies.
Show answer
The main cause is that a long-running transaction holds back the xmin horizon, so VACUUM cannot remove dead row versions its snapshot can still see. HOT pruning is blocked by the same horizon. Dead tuples therefore pile up during the query and remain afterward, which produces table and index bloat even with autovacuum enabled.
Autovacuum and HOT pruning both remove a dead row version only when no running transaction can still see it. Their removal test uses the xmin horizon, which is computed from the oldest backend_xmin of running transactions. A four-hour query holds an old snapshot, so the horizon stays pinned and dead tuples created by the OLTP writes cannot be reclaimed, including the ones that HOT pruning would otherwise clean up during normal page access. Because index entries point to heap tuples that are still retained, index bloat builds alongside the table bloat. The other options are wrong: autovacuum uses a SHARE UPDATE EXCLUSIVE lock, which does not conflict with ordinary reads, so it is not blocked from starting; relfrozenxid tracks freezing progress and does not cause VACUUM to skip pages whose dead tuples are still visible to the snapshot; and autovacuum does process tables with open transactions, it simply cannot remove tuples the old snapshot still sees.
Sources
The official documentation these questions are checked against:
Related interview questions
Job market
See databases-sql salaries and hiring demand from live job postings.
The other 38 questions
This page shows 25 and marks what you pick. That's as far as a page can go. A free account opens the other 38 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 answers per 30 days, each marked with written feedback