Skip to content
Tech Interview Prep
Technical interview guide

Indexing & Query Performance

Why some queries are instant and others scan the whole table, and how an index (usually a B-tree) changes that.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain what an index is and why you would not index every column.

Answer

An index is a separate structure the database maintains so it can find rows without reading the whole table. The default and most important kind is a B-tree, which keeps entries sorted by its key columns, so the engine can descend to a value in logarithmic time and then walk forward in order.

That sorted property determines everything an index can do: equality lookups, range scans, prefix matching, and supplying rows already ordered so a sort is unnecessary. It equally determines what it cannot do: it cannot help a LIKE '%term' because there is no prefix to descend to, and it cannot help a predicate that transforms the column, because the transformed values are not what is sorted.

The reason not to index everything is that every index is maintained on every write. An insert writes to the table and to each index. An update touching an indexed column updates them. Each consumes storage, adds vacuum work, and slows bulk loads. Extra indexes also give the planner more options, and occasionally it picks a worse one.

So an index is a trade: faster reads for slower writes and more storage. The question is never 'would this help a query', almost any index helps some query, but 'does it help enough to justify taxing every write on this table'.

In practice I create the structural ones with the schema: primary keys and unique constraints, which are automatic, plus foreign key columns, which are not automatic and are the most commonly missing index. Then indexes for known critical queries. Then nothing further without measured evidence. And periodically I audit for unused and redundant indexes, which most mature systems accumulate and which are pure cost.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

What is sargability, and how does it affect index usage?

Answer

A predicate is sargable when the engine can convert it into a range over an index's sorted keys: a seek. The mechanical requirement is that the indexed column appears bare on one side, compared against something evaluable independently of the row.

The defeats are all forms of wrapping the column. WHERE YEAR(created_at) = 2026 applies a function per row, so the index cannot be sought; rewriting it as a half-open range, created_at >= '2026-01-01' AND created_at < '2027-01-01', returns identical rows and seeks. WHERE LOWER(email) = :value has the same problem, fixed by a normalised column, an expression index on LOWER(email), or a case-insensitive collation. WHERE amount * 12 > 1000 should be amount > 1000 / 12.

Leading wildcards are structural rather than fixable by rewriting: LIKE '%term' cannot use a B-tree because there is no prefix. That needs a different index type: a trigram index for substrings, or full text search for words.

The subtle one is implicit type conversion. Comparing a varchar column to a numeric literal can make the engine coerce the column rather than the literal, transforming every row's value. It looks like a plain equality and behaves like a hidden function call, so it is invisible in review and shows up only in the plan.

Two important limits. Sargability is necessary but not sufficient: a perfectly sargable predicate matching most of the table still gets a sequential scan, correctly, because sequential access is far cheaper per row than random access. And it interacts with composite ordering: a range predicate on an early column stops later columns being usable for seeking, which is why equality columns come first.

So when I see a slow query, checking whether its predicates are sargable is one of the first things I do, because the fix is often a rewrite that costs nothing rather than an index that costs every write.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Explain the difference between an index scan and a bitmap scan.

Answer

What a strong candidate says first. Both access methods read the same B-tree; they differ in how they turn index entries into heap rows. An index scan walks the index in key order and fetches each matching heap row as it goes: one random page read per row, but rows arrive already sorted and the scan can stop early under LIMIT. A bitmap scan reads the index first, builds an in-memory bitmap of the heap pages holding matches, then visits those pages in physical order, once each. It trades ordering for fewer, better-localised page reads. The planner picks it in the middle: too many rows for per-row random fetches to be cheap, too few to justify reading the whole table.

Why the middle. PostgreSQL 16 defaults: random_page_cost = 4.0, seq_page_cost = 1.0, work_mem = 4MB. Take a 1,000,000-row events table at 80 rows per 8 KB page (12,500 heap pages) with a B-tree on user_id of roughly 3,000 pages.

matching rowsindex scanbitmap scanplanner picks
10 (0.001%)~3 index pages + 10 random fetches ≈ 43 cost unitsthe same 10 page visits, still priced near random, plus the bitmap buildindex scan
50,000 (5%)~150 leaf pages + 50,000 heap fetches spread over all 12,500 pages~150 leaf pages + 12,500 pages visited in orderbitmap scan
500,000 (50%)—bitmap covers the whole table, so heap cost approaches a seq scan's 12,500 while still paying for the indexseq scan

In page-cost terms the middle row is 50,000 × 4.0 = 200,000 versus 12,500 × ~1.0 = 12,500. The real gap is smaller: the planner's index-scan cost uses the Mackert–Lohman model, which assumes repeated visits to the same page hit cache, so it does not charge a full random read for every tuple. That correction is why the crossover sits at a few percent of the table rather than at 0.03%.

What the plans look like. Illustrative output from PostgreSQL 16 on the setup above:

SQL
CREATE INDEX events_user_id_idx ON events (user_id);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM events WHERE user_id BETWEEN 1 AND 5000;
Bitmap Heap Scan on events  (cost=412.55..13418.20 rows=49873 width=44) (actual time=8.104..62.417 rows=49912 loops=1)
  Recheck Cond: ((user_id >= 1) AND (user_id <= 5000))
  Heap Blocks: exact=12488
  ->  Bitmap Index Scan on events_user_id_idx  (cost=0.00..412.55 rows=49873 width=0) (actual time=6.902..6.902 rows=49912 loops=1)
        Index Cond: ((user_id >= 1) AND (user_id <= 5000))
Planning Time: 0.312 ms
Execution Time: 63.884 ms

Two nodes, always: Bitmap Index Scan builds the bitmap, Bitmap Heap Scan consumes it. The same query with WHERE user_id = 42 gives a plain Index Scan; with BETWEEN 1 AND 50000 it gives a Seq Scan.

Trade-offs beyond cost.

  • Ordering: a bitmap scan returns rows in physical page order, so ORDER BY user_id needs a sort on top. An index scan gives it free and can stop after N rows.
  • Index-only scans: only index scans can skip the heap entirely, and only when the visibility map marks the pages all-visible. A bitmap scan always visits the heap.
  • Combining indexes: BitmapAnd / BitmapOr let two single-column indexes serve a two-column predicate, or one index serve a = 1 OR a = 2. It is a fallback, not a replacement for a composite index: it reads more index pages and gets no tighter seek.
  • Parallelism: Parallel Bitmap Heap Scan exists; the bitmap is built once and shared by the workers.

Failure mode: lossy bitmaps. The bitmap is capped at work_mem (4 MB default). Past that, PostgreSQL stops storing individual tuple offsets and keeps page numbers only. The heap scan must then recheck every tuple on those pages, and the plan says so:

Heap Blocks: exact=1204 lossy=11302
Rows Removed by Index Recheck: 412887

A large lossy count with a big recheck means the predicate is not selective enough for the index to be the right tool. Raising work_mem for the session buys back exactness, but if the bitmap is that large, a sequential scan or a better index is usually the honest answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Explain index-only scans and when they do not deliver the expected benefit.

Answer

An index-only scan answers a query entirely from the index, without visiting the table's heap. It requires that every column the query needs (in the select list, the predicates, everything) is present in the index. When it works it is a large win, because the heap access is often the dominant cost of an index scan: the index entries are compact and ordered, while the heap rows they point to are scattered.

INCLUDE makes this practical without distorting the index. Columns in INCLUDE are stored in the leaf pages for retrieval but are not part of the sort key, so you can cover a query's output columns without widening the key or changing what the index can seek.

The caveat that surprises people is the visibility map. An index does not record whether a row version is visible to the current transaction: that information lives in the heap. To skip the heap, the engine consults the visibility map, and it can only skip pages marked all-visible. A page containing recently modified rows is not marked, so the heap must be checked after all.

The practical consequence is that on a heavily updated table, index-only scans degrade toward ordinary index scans, and the plan's 'Heap Fetches' count reveals how much. It is not a stable property of the index; it is a property of how recently the data changed and how well vacuum is keeping up. A table that gets an index-only scan in a quiet test can lose it under production write load, which is exactly the sort of thing that makes a change look effective in staging and disappointing in production.

So when I rely on one, I check Heap Fetches in EXPLAIN ANALYZE on a realistically-updated table, and I make sure autovacuum is configured appropriately for the table's write rate rather than left at defaults tuned for a much quieter workload.

And the usual trade applies: covering an index makes it wider, so it holds fewer entries per page and costs more to maintain. Covering a hot query is worth it; covering everything is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do you choose the column order for a composite index?

Answer

A useful starting heuristic is: equality predicates first, then a range or ordering column, while verifying the real plan.

The reason is how a B-tree stores composite keys. An index on (a, b, c) is sorted by a, then within equal a by b, then by c. So while earlier columns are pinned to single values by equality, later columns remain in a single sorted run and can be sought. The moment a column is constrained by a range, the scan spans many of its values, and the columns after it are no longer in one sorted run: they can only be filtered, not sought.

So for WHERE tenant_id = ? AND created_at > ? ORDER BY created_at DESC, the index is (tenant_id, created_at DESC): equality on the leading column, then the range column, which also supplies the ordering so no sort is needed.

The leftmost prefix rule follows from the same structure: an index on (a, b) serves predicates on a, and on a and b, while a b-only predicate usually needs a b-leading index for efficient access; PostgreSQL may still use skip scan or a broad scan. This is why a junction table's composite primary key on (student_id, course_id) does nothing for a course-first lookup, which needs its own index.

A common instinct I would push back on is 'most selective column first'. That is a reasonable tiebreaker among equality columns, but it is subordinate to the equality-before-range rule: putting a highly selective range column first defeats every column after it.

The other consideration is sharing. One well-ordered composite index often serves several queries, since any leftmost prefix is covered. So before adding a second index I check whether reordering or extending an existing one covers both: an index on (a, b) makes a separate (a) index a redundancy candidate whose size and usage should be checked, and consolidating is a real win because every index costs writes.

And I would verify with a plan rather than reasoning alone, because the interaction with selectivity and available statistics can produce surprises.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How can an index satisfy an ORDER BY or a top-N query without a sort step, and when does the planner still choose to sort anyway?

Answer

A B-tree index stores its entries in sorted key order, so an index scan can return rows already ordered: no Sort node. For ORDER BY created_at DESC LIMIT 10, Postgres walks the index backwards and stops after 10 rows. That early termination is the whole point: without the index it reads every row, top-N heapsorts them, and discards all but 10.

The match has to be exact on the leading columns. An index on (a, b) satisfies ORDER BY a and ORDER BY a, b, but not ORDER BY b. Direction matters per column: ORDER BY a ASC, b DESC needs CREATE INDEX ON t (a ASC, b DESC). Direction is declarable per column. NULLS FIRST/LAST must match the index default (ASC → NULLS LAST, DESC → NULLS FIRST) or be declared. Collation must match: an index built with COLLATE "C" will not satisfy ORDER BY name under the database's default collation. Expressions need an expression index: ORDER BY lower(name) needs ON t (lower(name)).

Then the planner's cost model decides. The index path has a startup cost, and with LIMIT the planner scales the row estimate by limit_tuples. It still sorts when:

  • The predicate is selective. WHERE status = 'active' ORDER BY created_at DESC LIMIT 10 with 0.1% active rows: the index scan may walk thousands of entries to find 10 matches, while a seq scan plus top-N heapsort reads the table once. The planner picks the sort.
  • The query returns most of the table. Random heap fetches through the index cost more than a sequential read plus an in-memory sort.
  • The plan uses a bitmap heap scan. Bitmap scans lose index order, so a Sort is mandatory.
  • A parallel plan. A plain Gather does not preserve order; only Gather Merge does.
  • A partial index whose predicate is not implied by the query's WHERE clause.

Concrete trace:

sql CREATE INDEX ON events (created_at);

EXPLAIN (ANALYZE) SELECT * FROM events ORDER BY created_at DESC LIMIT 10; -- Limit -- -> Index Scan Backward using events_created_at_idx on events -- (actual time=0.03..0.05 rows=10 loops=1)

EXPLAIN (ANALYZE) SELECT * FROM events WHERE status='active' ORDER BY created_at DESC LIMIT 10; -- Limit -- -> Sort (Sort Method: top-N heapsort Memory: 27kB) -- -> Seq Scan on events (rows=...)

Same ORDER BY, same LIMIT, different plan: the predicate changed which path was cheaper.

To fix the second case: a composite index (status, created_at DESC) lets the scan seek to status='active' and then walk in order. Or a partial index ON events (created_at DESC) WHERE status='active'.

Check with EXPLAIN (ANALYZE, BUFFERS) and look for the Sort node and its method. top-N heapsort means LIMIT is being exploited but rows are still being read; external merge means it spilled to disk.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain how joins are executed and what that means for indexing.

Answer

Three algorithms, each suited to a different shape, and each implying different indexes.

Nested loop. For each row of the outer input, probe the inner input. Cost is roughly outer rows times the cost of an inner lookup, so it is excellent when the outer input is small and the inner lookup is indexed, and catastrophic otherwise. This is the algorithm that turns a misestimate into a disaster: if the planner expects 50 outer rows and gets 50,000, a plan that looked cheap becomes 50,000 index probes. It is the strongest argument for an index on the join key of the inner relation.

Hash join. Build a hash table from the smaller input, then stream the larger past it. Cost is roughly linear in both inputs, and it needs no index on the join key at all, which is worth knowing, because people add indexes hoping to speed up a join that is already hash-joining and will not use them. It needs memory for the hash table, and spills to disk when the build side exceeds working memory, which is a common cause of a join that is fine in testing and slow in production.

Merge join. Both inputs sorted on the join key, then walked together. Sorting is the expense, but if indexes already supply both inputs in the right order, no sort is needed and it is very efficient. It also suits joins producing large ordered results.

What this means practically. Index the join key on the side that will be probed: usually the 'many' side of a one-to-many. That indexes the nested loop's inner lookup, and it is the same index a foreign key column should have anyway, which is why missing foreign key indexes show up as slow joins as well as slow deletes.

But do not assume an index will help every join: for two large tables a hash join is likely correct and indexes on the join keys will be ignored. Check the plan before adding one.

And the filtering predicates often matter more than the join keys. Reducing each side before joining changes which algorithm is viable: a selective predicate that shrinks the outer input can turn an untenable nested loop into an ideal one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

When would you use a partial index?

Answer

A partial index covers only rows matching a predicate, and it earns its place in two distinct situations.

When queries only ever touch a subset. The canonical case is a queue table: millions of rows accumulate, but every query asks for the unprocessed ones. CREATE INDEX ... ON jobs (created_at) WHERE processed = false indexes only those, so the index stays tiny and mostly cached even as the table grows without bound. A full index on the same column would grow forever while only its newest fraction was ever read.

It also makes low-cardinality columns worth indexing. A boolean is normally a poor index candidate because neither value is selective, but if is_flagged is true for 0.1% of rows and queries only ever ask for flagged ones, a partial index on that value is highly selective and very small.

When uniqueness applies to a subset. This is the one that is not about performance at all. A partial unique index enforces 'exactly one active row per user' while permitting any number of historical rows: an invariant a plain unique constraint simply cannot express. The same technique lets a soft-deleted user's email be reused, by making uniqueness apply only where deleted_at IS NULL.

The constraints to be aware of: the planner uses a partial index only when it can prove the query's predicate implies the index's, so the query condition must match closely. WHERE processed = false uses it; WHERE processed <> true may not, and a parameterised predicate may not either. That is a real gotcha: the index exists, looks correct, and is silently unused.

So I verify with a plan after creating one, and I keep the predicate simple and aligned with how queries are actually written. And if the definition of the subset changes, 'recent' meaning the last 30 days, a partial index needs periodic redefinition, which is maintenance that a full index does not carry.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

When would you index an expression or a function result rather than a plain column, and what pitfalls does that introduce?

Answer

An expression index is the right tool when the predicate is on a derived value and I can't change the query or the schema: case-insensitive lookup on email, a field inside a jsonb column, date_trunc('day', created_at), or a hash of a long URL. The index stores the computed value, and the planner only uses it when the query's parsed expression matches the index expression exactly: that matching rule is where most of the trouble lives.

sql -- PostgreSQL 18 CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));

EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM users WHERE lower(email) = 'ada@example.com'; -- Index Scan using users_lower_email_idx -- Index Cond: (lower(email) = 'ada@example.com'::text)

EXPLAIN SELECT id FROM users WHERE email = lower('Ada@Example.com'); -- Seq Scan on users -- Filter: (email = 'ada@example.com'::text) <- constant folded, index not matched

EXPLAIN SELECT id FROM users WHERE lower(email) = lower('Ada@Example.com'); -- Index Scan using users_lower_email_idx <- both sides fold to the same expression

The alternative I'd weigh first is a stored generated column (PostgreSQL 12+): it computes on write, the query names a plain column, and there is no expression-matching trap. I'd take the expression index when I can't alter the table, or when I want a unique constraint on the expression: CREATE UNIQUE INDEX ON users (lower(email)) is the only way to enforce case-insensitive uniqueness.

Pitfalls, roughly in the order they bite:

PitfallWhat actually happensHow you catch it
Expression mismatchWHERE email ILIKE 'ada@%' or lower(email::varchar) doesn't match; Seq ScanEXPLAIN shows no index; compare pg_get_indexdef with the predicate
Non-immutable functionOnly IMMUTABLE functions are allowed, and one wrongly marked IMMUTABLE (reads a table, depends on TimeZone) leaves stale entries that are never recomputedQuery results change after REINDEX; check pg_proc.provolatile
Write costThe expression is evaluated on every INSERT and on every UPDATE of the row, because Postgres computes the new index tuple to decide HOT-update eligibilityCPU per write; n_tup_upd against index size growth
StatisticsANALYZE does collect stats for expression indexes, so selectivity is real; without the index the planner falls back to the 0.5% default for equality on an unknown functionEXPLAIN row estimates vs actual
StorageThe computed value is stored again: lower(email) duplicates the textpg_relation_size on the index

The immutability one is dangerous because it fails silently and in the wrong direction: the index is used, the plan looks great, and the answers are wrong. A wrapper function that reads a lookup table or calls now() is the usual culprit. If I need prefix matching on the lowercased value, the index has to be declared (lower(email) text_pattern_ops): a plain lower(email) index won't serve LIKE 'ada%' under a non-C collation.

Storage is worth doing arithmetic on. A 200-byte URL column indexed directly costs roughly 216 bytes per entry; md5(url) costs about 48. At 50M rows that is ~10.8 GB against ~2.4 GB: the reason hashing long strings is common, at the price of losing prefix and range queries and accepting theoretical collisions.

I'd skip the expression index when the query can be rewritten to a sargable form, when a generated column is available, or when the function is expensive and the table is write-heavy: there the cost lands on every write, not just the reads I was trying to fix.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How do you decide between index types beyond the default B-tree?

Answer

The B-tree is right for almost everything: equality, ranges, prefix matching, and supplying order. I reach past it only when the query shape is one a sorted scalar structure cannot serve.

GIN for multi-valued containment: 'which documents contain this key', 'which rows have this array element', and full-text search. It indexes each contained value pointing back at the rows, which is exactly the inverted structure those queries need. Its costs are slower updates and a larger index, so it suits read-heavy data.

GiST for geometric data, range types, and nearest-neighbour searches, and, importantly, it backs exclusion constraints, which is how you prevent overlapping bookings. That is a correctness use rather than a performance one.

BRIN for very large tables whose values correlate with physical row order: append-only time-series being the classic. It stores a summary per block rather than an entry per row, so it is orders of magnitude smaller. The trade is coarse filtering: it narrows to candidate blocks which are then scanned. It is excellent when the correlation holds and nearly useless when it does not, so it depends on a physical property of the table rather than on the query.

Hash supports equality only, with no ordering and no range support, and its advantage over a B-tree is small. I would rarely choose it.

Trigram indexes (via an extension) make substring and fuzzy matching seekable, which is the answer to LIKE '%term%' when it genuinely needs to be fast.

The practical approach: start with a B-tree, and let the query shape tell you when it cannot work. If the predicate is containment, an ordered structure is the wrong shape. If it is substring matching, likewise. If the table is enormous, append-only, and always queried by its natural order, BRIN is worth measuring against a B-tree: it will be dramatically smaller and possibly fast enough.

And I would measure rather than assume, because these have very different maintenance costs and the right answer depends on the read-to-write ratio as much as on the query shape.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

You've added an index to fix a slow query. How do you confirm from the execution plan that it's actually being used and doing the work you intended?

Answer

I'd run EXPLAIN (ANALYZE, BUFFERS) on the exact query before and after, and look for three things: the index name appears in the plan, the Index Cond matches the columns I indexed, and the actual rows and buffer counts show the work I intended.

The plan node. A used index shows as Index Scan using <index_name> or Index Only Scan using <index_name>. If I see Seq Scan or a Bitmap Heap Scan on a different index, it's not being used. For example, on orders with WHERE customer_id = 42 AND status = 'shipped', after adding (customer_id, status):

Index Scan using orders_customer_id_status_idx on orders Index Cond: ((customer_id = 42) AND (status = 'shipped'::text)) Buffers: shared hit=4 read=2

Before, it was Seq Scan with Filter: (customer_id = 42 AND status = 'shipped') and Buffers: shared hit=1000 read=500. The drop in buffers is the evidence it's doing less work.

Is it doing the intended work? Being used is not enough. If I intended the index to filter on both columns, I need both in Index Cond. If status appears under Filter instead, the index is only using customer_id, and Rows Removed by Filter will show how many rows were read and discarded. That means the composite index isn't doing the second column's job: often because statistics make the planner think a filter is cheaper, or because the column order is wrong for the query.

If I intended the index to avoid a sort, I check for a Sort node. If the plan still has Sort, the index isn't providing order. For an index-only scan, I need Heap Fetches: 0; a high number means the visibility map isn't set and it's still hitting the heap, so the covering benefit isn't there.

Failure modes. The index might not be used because of a type mismatch (text vs integer), a function on the column (WHERE lower(email) = ...), or stale statistics. I'd run ANALYZE and re-check. If it's still not used, I can set enable_seqscan = off to see if the planner would use it when forced, if it does, the cost estimate is the problem, not the index. Over time, pg_stat_user_indexes.idx_scan confirms it's being used, but the plan is the direct proof.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Walk through how you would diagnose a slow query.

Answer

I measure before changing anything, because time is almost never where intuition puts it.

Get the real plan. EXPLAIN ANALYZE on production-like data, since a plan against a small development table tells you nothing about the production one.

Check estimated versus actual rows first. This single comparison identifies the cause more often than anything else. A node that expected 50 rows and produced 50,000 means the planner chose its strategy on wrong information: typically a nested loop that is fine at the estimate and catastrophic at the reality. Causes are stale statistics, correlated columns the planner models as independent, or expressions it cannot estimate through. Running ANALYZE sometimes fixes the whole problem without touching the query, and extended statistics handle the correlated-column case.

Then recognise the shapes. A sequential scan on a large table under a selective predicate means a missing or unusable index. A sort spilling to disk means either a missing index that could supply the order or insufficient working memory. A filter discarding most rows after an index scan means the index got to the right region but the selective condition was not in it: adding that column moves the work into the seek. A nested loop over a large outer input is usually the misestimation above.

Then question the query itself, before adding indexes. Is a predicate non-sargable? Is there a DISTINCT masking join fan-out? Is SELECT * preventing an index-only scan? Is this deep OFFSET pagination that should be keyset? Fixing the query is better than indexing around it, because the index would cost every write forever.

Then consider indexes, chosen from the actual predicates and ordering, with the equality-range-sort rule.

Then question whether it should run at all. A dashboard aggregating millions of rows per view wants a materialized view, not a faster scan.

Then re-measure at production volume. And I would check whether the query is slow always or only sometimes: intermittent slowness points at lock contention, a plan flip, or cache state rather than at the query itself, and chasing it as a query problem wastes time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How would you decide whether a slow query needs an index or a rewrite?

Answer

I look for a defect in the query first, because a rewrite is free forever while an index taxes every write forever. If both would work, the rewrite is strictly better.

The defects worth checking, roughly in order of how often they turn out to be the cause:

A non-sargable predicate. A column wrapped in a function, an implicit type conversion, a leading wildcard. If an existing index is being defeated by the predicate's shape, rewriting restores it at no cost.

Unnecessary work. SELECT * pulling columns nobody uses, which also prevents an index-only scan. A DISTINCT masking join fan-out: the fix is correcting the join, and it makes the query both faster and correct. Sorting a result the caller does not need ordered.

A wrong join shape. A join used only to test existence, where EXISTS would short-circuit and avoid fan-out. Joining then aggregating where pre-aggregating would reduce rows first.

A pattern with a better form. Deep OFFSET pagination that should be keyset. A correlated subquery per row that should be a join or a window function. An N+1 pattern that should be a single batched query.

If none of those apply, the query is already expressing the minimum work needed and is still slow, then it is an index question, and I would choose the index from the actual predicates and ordering.

The third possibility I would not skip: neither. If the query is genuinely aggregating millions of rows for a dashboard, no index makes that fast, and the answer is precomputation. Reaching for an index there wastes effort and adds cost without solving the problem.

The test I apply: if I cannot articulate why the current plan is doing more work than the question requires, I do not yet understand the problem well enough to fix it, and adding an index at that point is guessing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain how pagination affects query performance and what you would recommend.

Answer

OFFSET pagination has two problems, and the correctness one is less discussed than the performance one.

Cost is proportional to the offset. The database must generate and discard every skipped row, so page 5,000 does thousands of times the work of page 1. This degrades smoothly and invisibly until someone deep-paginates or a crawler walks every page.

It is unstable under concurrent writes. If a row is inserted before the current page between requests, one row shifts across the boundary and the user sees it twice; a delete makes a row vanish unseen. For an export or a job iterating every page, that means silently duplicated and skipped records: a data problem, not a performance one.

Keyset pagination carries the last row's sort key forward instead of a count: WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 50. With an index on (created_at DESC, id DESC) the database seeks straight to the position, so every page costs the same, and concurrent inserts elsewhere cannot shift the boundary.

The row-value comparison is important and often written incorrectly. Expanding it into created_at < :x OR (created_at = :x AND id < :y) is equivalent but frequently gets the boundary condition subtly wrong, and it may not use the index as cleanly.

The trade-off is that keyset gives next and previous, not arbitrary page numbers, and the sort key must be unique, which is why a tiebreaker like the primary key is appended to any non-unique sort column. Without it, rows tied on the sort column are skipped or repeated at page boundaries.

So my recommendation: infinite scroll, feeds, APIs, exports and anything deep get keyset. A small admin table where users genuinely want page 7 can keep OFFSET, because at a few thousand rows neither problem bites and the simplicity is worth more.

For a batch job iterating everything, keyset is not merely faster, it is the only correct option, and I have seen more than one export quietly miss records because it used OFFSET while rows were being inserted.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How would you index a table that is written constantly and read rarely?

Answer

Minimally, and with each index justified individually, because on a write-heavy table the usual trade inverts. Every index is maintained on every insert, so index count directly limits write throughput, and adding one for a query that runs twice a day taxes millions of writes for it.

I would keep only what is structurally required: the primary key, any unique constraint the data genuinely needs, and foreign key columns if parents are ever deleted or updated, since without that index each such operation scans the child table.

For the rare reads, the question is whether they need to be fast. A report run twice daily can take thirty seconds; that is a perfectly good trade against faster writes. A sequential scan on a write-heavy table is often the right answer, and saying so is usually more useful than adding an index.

Where reads do need to be fast, I would look for the smallest possible index. A partial index covering only the rows those reads touch (recent rows, or unprocessed ones) is far cheaper to maintain than a full one, because most inserts do not match its predicate and so do not update it at all. That distinction matters a lot on this shape of table.

I would also consider moving the reads off the write path entirely: a replica, or periodically copying data into a separate table indexed for reading. That is often the honest answer when the two workloads genuinely conflict: an append-only ingest table and an analytical query pattern want opposite physical designs, and trying to satisfy both in one table compromises each.

For bulk ingestion specifically, dropping indexes before the load and rebuilding after is standard, since per-row maintenance is much more expensive than one bulk build.

And BRIN is worth evaluating if the table is large and append-only: it is orders of magnitude smaller than a B-tree and much cheaper to maintain, and if reads always filter on the naturally-ordered column its coarser filtering may be entirely sufficient. That is exactly the shape of table BRIN was designed for.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Explain what statistics the planner uses and how they go wrong.

Answer

Assume PostgreSQL 14+. Row estimates come from pg_statistic, filled by ANALYZE.

ANALYZE samples 300 × default_statistics_target rows per table: 30,000 at the default target of 100. Per column it records null_frac, avg_width, n_distinct (positive is an absolute count, negative a fraction of the table, so -1 means unique), a most_common_vals/most_common_freqs list truncated at the statistics target, histogram_bounds covering the rest, and correlation, the −1..1 measure of how closely physical row order matches value order. Correlation is what makes an index scan on a clustered column look cheap and on a randomly ordered one look expensive.

For an equality, selectivity is the MCV frequency if the value is in the list; otherwise it comes from the histogram bucket the value falls in, or, with no histogram, (1 - sum(mcv_freqs) - null_frac) / (n_distinct - mcv_count). With no statistic at all the planner uses constants: DEFAULT_EQ_SEL = 0.005, DEFAULT_INEQ_SEL = 0.3333, DEFAULT_NUM_DISTINCT = 200.

FailureMechanismFix
Stale statsautovacuum analyzes only after 50 + 0.1 × reltuples changes: 1,000,050 rows on a 10M-row table, so a 500k-row bulk load never triggers itmanual ANALYZE, or lower autovacuum_analyze_scale_factor for that table
Correlated columnsindependence is assumed, so selectivities multiplyCREATE STATISTICS s (dependencies, ndistinct, mcv) ON a, b FROM t (dependencies/ndistinct PG 10+, mcv PG 12+)
Predicate on an expressionlower(email) = ... has no column statistic and falls back to DEFAULT_EQ_SELexpression index, or CREATE STATISTICS ... ON (lower(email)) (PG 14+)
Skew past the MCV listthe list is truncated at the statistics target; the histogram assumes uniformity within each bucketALTER TABLE t ALTER COLUMN c SET STATISTICS 1000
Join compoundingper-node errors multiply along the join treeread rows= against actual rows= at the deepest diverging node, not the top

The compounding case is the one that bites. events has 10M rows; country = 'FR' matches 100,000 and city = 'Paris' matches 100,000, and every Paris row is French. The planner multiplies 0.01 × 0.01 and expects 1,000 rows:

Nested Loop  (cost=0.71..1892.30 rows=5000 width=32) (actual time=0.038..4218.907 rows=500000 loops=1)
  ->  Index Scan using events_country_city_idx on events  (cost=0.56..412.30 rows=1000 width=24) (actual time=0.031..88.412 rows=100000 loops=1)
        Index Cond: ((country = 'FR'::text) AND (city = 'Paris'::text))
  ->  Index Scan using sessions_event_id_idx on sessions  (cost=0.43..1.48 rows=5 width=8) (actual time=0.008..0.021 rows=5 loops=100000)

The scan is 100× low, so the join is too: 5,000 estimated against 500,000 actual, and the nested loop runs the inner index scan 100,000 times instead of the 1,000 the cost model priced. CREATE STATISTICS events_geo (dependencies, mcv) ON country, city FROM events; followed by ANALYZE events; gives the planner the joint distribution, it estimates ~100,000 rows, and it switches to a hash join.

So the diagnostic is mechanical: EXPLAIN (ANALYZE, BUFFERS), find the deepest node where rows= and actual rows= diverge, and fix that node. Everything above it is inherited error.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Why might a query that used an index yesterday stop using it today?

Answer

A plan is a cost decision, recomputed on every execution from the planner's statistics. Nothing in the query text has to change for the plan to change, and usually nothing did. So the first move is not to stare at today's slow plan: it is to get both plans and diff them.

EXPLAIN (ANALYZE, BUFFERS) on the slow query. The number that matters is the gap between rows= (estimate) and actual rows= (reality). A 10x gap means the planner is working from a wrong picture of the data. Estimates that match reality but a plan that changed shape means the data genuinely moved and the planner is right.

Here is the arithmetic that decides it. Take events: 20M rows, 250,000 pages of 8 KB (~80 rows/page), an index on created_at with correlation ≈ 1, and the defaults seq_page_cost=1.0, random_page_cost=4.0, cpu_tuple_cost=0.01, cpu_index_tuple_cost=0.005.

1% of rows (200k)40% of rows (8M)
seq scan250,000×1.0 + 20M×0.01 = 450,000unchanged: 450,000
index scan1,540 leaf pages×4.0 + 2,500 heap pages×1.0 + 200k×0.015 = 11,66061,500×4.0 + 100,000×1.0 + 8M×0.015 = 466,000

At 1% the index wins by 40x. At 40% it loses by 3%. The crossover sits a few percent into the table, and it moves with every constant above, which is why the same query flips without a single character changing.

What actually moved, and how to see it:

what movedhow it shows upcheck
data distributionestimates match actuals, selectivity is just high nowpg_stats MCV list and n_distinct for the column
stale statisticsestimate off by orders of magnituden_mod_since_analyze, last_analyze in pg_stat_user_tables
parameter valueidentical SQL, fast for one tenant, slow for anotherEXPLAIN with the literal vs. the bound parameter
index bloatindex scan cost up, heap cost flatpgstatindex avg_leaf_density
correlation changeheap-fetch estimate movespg_stats.correlation
new index, config, upgradeplan shape changes with no data changepg_settings diff, migration log

Stale statistics deserve the emphasis, because the default autovacuum thresholds make them easy to hit: autovacuum_analyze_threshold=50 and autovacuum_analyze_scale_factor=0.1 mean a 20M-row table does not get auto-analyzed until roughly 2M rows have changed. A bulk load of 500k rows leaves the planner estimating from a picture that is 500k rows old, and the resulting plan is wrong rather than differently right. ANALYZE events; fixes it in seconds.

The parameter case is the one people misdiagnose as flakiness. From PostgreSQL 12, plan_cache_mode defaults to auto: the planner builds a custom plan for the first five executions, then compares the generic plan's cost against the average custom plan cost and switches to generic if it is not more than about 10% worse. A generic plan uses average selectivity, so a tenant holding 30% of the rows gets the plan built for the median tenant. SET plan_cache_mode = force_custom_plan confirms it in one run.

If the data really is 40% one value, the index is the wrong tool and no amount of statistics will save it: a partial index on the hot value, or partitioning, is the fix. If the distribution is merely skewed, raise default_statistics_target for that column or add CREATE STATISTICS for correlated columns.

Plans are not stable by default. For a query that must not regress, capture plans on a schedule with auto_explain and diff them, and alert on the per-queryid mean time in pg_stat_statements shifting: otherwise the first person to notice is a user.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

What is the relationship between vacuum, bloat and index performance?

Answer

Under MVCC, an update does not overwrite a row: it writes a new version and leaves the old one, and a delete only marks a row dead. Those dead versions remain until vacuum reclaims them, and they occupy space in the table and in every index pointing at them.

The consequences for reads are direct. A bloated table has more pages holding the same live data, so a sequential scan reads more, and fewer live rows fit in each cached page, so the effective cache hit rate falls. A bloated index is larger and deeper, so lookups traverse more pages. Neither shows up as a query change; the same query simply gets slower.

Vacuum also maintains the visibility map, which is what index-only scans depend on. A table whose vacuum is behind gets fewer truly heap-free index-only scans because many pages are not marked all-visible, so a plan that was fast becomes an ordinary index scan with heap fetches, without anything about the query or the index changing.

And ANALYZE, usually run by autovacuum alongside, keeps the statistics the planner relies on. Behind-schedule autovacuum therefore causes both bloat and misestimation, and misestimation causes plan changes, which is why the symptoms can look like several unrelated problems at once.

The thing that most often prevents vacuum from working is a long-running transaction. Vacuum cannot remove row versions that any open transaction might still need, so one forgotten idle-in-transaction session (a leaked connection, an open psql, a stuck job) holds back cleanup database-wide, and bloat accumulates for as long as it lives. This is the single most valuable thing to monitor, because the fix is trivial and the damage is not.

So I would monitor: the oldest transaction age, autovacuum activity and whether it is keeping up on the busiest tables, and estimated bloat on large heavily-updated tables. For tables with high write rates I tune autovacuum per-table rather than relying on defaults set for a much quieter workload: the defaults scale by table size, so very large tables get vacuumed too rarely.

Severe existing bloat needs a rebuild rather than a vacuum, since ordinary vacuum makes space reusable rather than returning it, and a rebuild should be done concurrently to avoid locking.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

How do you quantify the write cost each additional secondary index imposes, and what tradeoffs decide whether it earns its place?

Answer

Every secondary index is a second copy of the key plus a heap pointer, and PostgreSQL maintains it synchronously inside the same transaction as the write. So the cost is not "some overhead": it is one extra B-tree insert per index per row written, the WAL for that insert, and the vacuum work to clean it up later. I quantify it in three numbers: bytes of index tuple per write, WAL bytes per write, and the HOT-update rate I lose.

Size the tuple first. A B-tree entry is an 8-byte IndexTupleData header (6-byte TID + 2-byte info) plus the key, aligned to 8 bytes. A bigint key is 16 bytes, (bigint, timestamptz) is 24, a uuid is 24. Pages are 8 KB with ~40 bytes of header and the default fillfactor = 90, so add roughly 10%.

Worked example, labelled as such: 2,000 inserts/s into a table with three secondary indexes averaging 24-byte entries.

2,000 x 3 x 24 B = 144 KB/s ~= 12.4 GB/day of index data with page overhead ~= 13.6 GB/day

That is before WAL, and before the first write to each index page after a checkpoint, which emits an 8 KB full-page image.

Then measure, don't estimate. pg_stat_user_tables gives n_tup_upd and n_tup_hot_upd; pg_stat_wal gives wal_bytes; pg_stat_user_indexes.idx_scan gives the read side. The cleanest experiment is staging: run the write workload with the index, drop it, run again, compare wal_bytes and p99 insert latency.

HOT is the lever people miss. An UPDATE that changes no indexed column and fits on the same page is a HOT update: no new index entries, the old line pointer is redirected. Add an index on a column that is updated on every request and HOT goes to zero for those updates: every update now writes a new heap tuple and N new index tuples. That is usually a bigger cost than the index's size.

Deciding whether it earns its place. Compare against the cheaper shapes:

ShapeWrite costWhen it wins
Full B-tree on status16 B/insert, kills HOT on status updatesnever, at 3 distinct values
Partial WHERE status='pending'16 B only for the pending rowsqueue-style tables
Two single-column indexes32 B/insertrarely: one 24-byte composite is smaller and more selective
INCLUDE covering indexwider leaf entries, more WALwhen it removes heap fetches from a hot read

A partial index is the strongest write-cost reduction available: entries exist only for rows matching the predicate, so a predicate matching 0.1% of rows costs 0.1% of the writes. B-tree deduplication (on by default for non-unique indexes) also collapses duplicate keys to one entry plus many TIDs, which is why a low-cardinality index is smaller than the arithmetic suggests.

Failure modes and how you see them. HOT collapse shows as n_tup_hot_upd/n_tup_upd falling and n_dead_tup climbing. Index bloat shows as pg_relation_size on the index growing faster than the table: fix with REINDEX CONCURRENTLY. A covering index that stops delivering shows as high Heap Fetches in EXPLAIN (ANALYZE, BUFFERS), meaning the visibility map is stale because vacuum is behind.

Removal needs evidence, not intuition. idx_scan = 0 in pg_stat_user_indexes since the last stats reset, over a full business cycle including the monthly and year-end jobs. Anything else is a guess.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How would you add an index to a large production table safely?

Answer

What I'd say first. CREATE INDEX CONCURRENTLY, run outside a transaction block, with the failure modes handled explicitly. A plain CREATE INDEX takes a ShareLock on the table, which blocks every INSERT, UPDATE and DELETE for the whole build: on a 200M-row table that is minutes of write outage, and it is invisible in development where the same table builds in milliseconds.

The command.

SQL
-- PostgreSQL 16
SET lock_timeout = '5s';            -- fail fast if the DDL lock can't be taken
SET statement_timeout = 0;          -- a long build must not be killed mid-flight
SET maintenance_work_mem = '2GB';   -- default is 64MB; more memory means fewer disk passes

CREATE INDEX CONCURRENTLY idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

CONCURRENTLY cannot run inside a transaction block, and most migration frameworks wrap migrations in one. The escape hatches: Rails disable_ddl_transaction! plus algorithm: :concurrently; Django AddIndexConcurrently with atomic = False; Alembic with op.get_context().autocommit_block():. Getting this wrong is a silent failure mode: some tools fall back to a plain build, which is exactly the outage you were avoiding.

What it actually does. Three phases, all under ShareUpdateExclusiveLock:

phaseworkwhy it matters
1full table scan, build index entriesthe long part
2second scan, add rows committed during phase 1why it costs ~2–3× a plain build
3wait for every transaction that could see the index as invalidlong-running transactions stall here

ShareUpdateExclusiveLock does not conflict with DML, so writes keep flowing. It does conflict with other DDL and with autovacuum: autovacuum on that table is blocked for the duration, which matters on a high-churn table.

Failure modes.

  • Invalid index. If the build fails or is cancelled, it leaves an index with indisvalid = false. It is still maintained on every write, you pay the write cost, but the planner will not use it. Drop it and retry; a retry with the same name fails until you do.
  • Stalled phase 3. An idle-in-transaction session or a 40-minute analytics query holds the build open. Check pg_stat_activity for state = 'idle in transaction' and long xact_start before starting.
  • Replication lag. The build writes WAL for every index entry. On a replica already behind, this compounds. Watch pg_stat_replication.replay_lag and be ready to cancel.
  • Index that is never used. Common: wrong column order, a predicate that does not match, or selectivity so poor the planner prefers a seq scan.

Monitoring while it runs.

SQL
SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
SELECT application_name, replay_lag FROM pg_stat_replication;

Verification after.

SQL
-- valid?
SELECT c.relname, i.indisvalid, i.indisready
FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE NOT i.indisvalid;

-- actually used?
SELECT idx_scan FROM pg_stat_user_indexes
WHERE indexrelname = 'idx_orders_customer_created';

idx_scan stays 0 until the query runs, so confirm with EXPLAIN (ANALYZE, BUFFERS) on the real query rather than trusting the index's existence.

Rollback. DROP INDEX CONCURRENTLY idx_orders_customer_created;: also outside a transaction, and also able to leave an invalid index if it fails. Dropping is fast and cheap; adding badly is not. That asymmetry is why concurrent is the default, not the cautious option.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you find indexes that should be removed?

Answer

Two categories, found differently, and both need a long observation window before you act.

Unused indexes. PostgreSQL counts scans per index in pg_stat_user_indexes.idx_scan (index-only scans included). Zero means no scan since the counters were last reset. The caveats decide the answer:

  • The counters reset on pg_stat_reset(), and since PostgreSQL 15 they survive a clean shutdown but are lost after a crash. A zero can mean "recently reset", not "unused".
  • The window must cover the full business cycle. An index used only by a quarterly report reads zero for eleven weeks.
  • Dropping and recreating an index gives it a new OID, so its counter starts at zero again.

So I check when stats were last reset, and I want a window of at least one full cycle: for most systems, a quarter.

Redundant indexes. An index on (a) is a prefix of (a, b) and is often covered by it, but not automatically: the shorter index can be materially smaller, and uniqueness, collation, operator class, predicate and included columns must match for the prefix argument to hold. Compare definitions, sizes and measured usage.

Also flag duplicate indexes with different names (they accumulate through migrations) and indexes already covered by a unique constraint's implicit index.

Exceptions before dropping. An index backing a constraint (pg_constraint.conindid) can't be dropped independently. A partial unique index enforcing subset uniqueness is a correctness feature and will show low scans while being essential. An index for an infrequent but critical operation (monthly reconciliation, incident-time lookup) is worth keeping.

The procedure. There is no way to make an index invisible in PostgreSQL; that's Oracle/SQL Server. The real options are DROP INDEX CONCURRENTLY (SHARE UPDATE EXCLUSIVE lock, can't run in a transaction block, can't be used on constraint-backing indexes, and can fail leaving an invalid index) or a plain DROP INDEX in a low-traffic window (brief ACCESS EXCLUSIVE lock on the table). Either way, have a tested CREATE INDEX CONCURRENTLY script ready first: dropping is fast, recreating a large index concurrently is slow and can fail, leaving an invalid index you must drop and retry.

Then the query:

SQL
SELECT s.relname AS table_name,
       s.indexrelname AS index_name,
       s.idx_scan,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size,
       pg_get_indexdef(s.indexrelid) AS definition
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE NOT i.indisunique
  AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = s.indexrelid)
ORDER BY s.idx_scan ASC, pg_relation_size(s.indexrelid) DESC;

Sample output (illustrative figures):

tableindexidx_scansizedefinition
ordersorders_created_at_idx0412 MBbtree (created_at)
ordersorders_customer_id_idx096 MBbtree (customer_id)
ordersorders_customer_id_created_at_idx1204881210 MBbtree (customer_id, created_at)

Read: orders_customer_id_idx is a prefix of the composite and unused. Drop candidate. orders_created_at_idx is unused but 412 MB; before dropping, check whether a monthly report or an ad-hoc query uses it, since it may be the only path for a range scan on created_at.

Do this periodically. Index sets accumulate, every incident adds one and nobody removes them, and the cost is paid on every write forever.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What performance considerations apply to a table that grows without bound?

Answer

The defining property is that anything scaling with total size eventually fails, so the design has to make the hot working set bounded even though the table is not.

Indexes must stay small relative to queries. A full index on an ever-growing table grows forever, and eventually neither it nor the table fits in cache. A partial index covering only the rows that are actually queried (recent, or unprocessed) stays bounded and mostly cached regardless of history. This is the single most effective technique for this shape of table.

Queries must be bounded. Any query without a limit on how much history it touches will eventually time out. A required date range with a maximum span, enforced rather than requested, is what keeps that from happening, and it is much easier to add before people have built habits around unbounded queries.

Deletion must be cheap. Deleting old rows from a huge table is expensive and leaves bloat that vacuum must then reclaim. This is the strongest argument for partitioning by time: detaching a partition is near-instant and reclaims space immediately, which turns retention from a painful recurring job into a trivial one. If there is a retention policy, partitioning is usually justified on that basis alone.

Partitioning's constraints must be accepted deliberately: unique constraints must include the partition key, queries not filtering on it touch every partition, and future partitions must be created automatically. A missing one causes insert failures at a period boundary, which is a classic midnight incident.

Vacuum must keep up. Autovacuum's defaults scale with table size in a way that vacuums very large tables too rarely, so per-table tuning is needed rather than defaults.

Old data should probably not live here. Archiving to cheaper storage, or aggregating detail into summaries and discarding the rows, keeps the operational table proportional to what is operationally needed. Most unbounded tables contain a lot of data nobody has queried in years.

And BRIN is worth evaluating for append-only tables of this shape, since it is orders of magnitude smaller than a B-tree and its coarse filtering is often sufficient when queries follow the natural insertion order.

The thing I would decide earliest is retention, because it determines whether partitioning is worthwhile, and retrofitting partitioning onto a huge existing table is far harder than starting with it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

What would you check before concluding that a database needs bigger hardware?

Answer

What I'd say first. Before agreeing to bigger hardware I want three things: the metric that is failing and at what percentile, evidence that the database rather than the application is the bottleneck, and a wait-event breakdown of what sessions are actually blocked on. Hardware is the most expensive remedy and the one that hides the cause, so it is the last thing I buy, not the first. If the application's p99 is bad but the database's own query latency is flat, the problem is upstream (pool exhaustion, N+1s, serialization) and a bigger box just moves the queue.

The queries that decide it.

SQL
-- 1. What are sessions blocked on right now?
SELECT wait_event_type, wait_event, count(*)
FROM pg_stat_activity
WHERE state = 'active' AND pid <> pg_backend_pid()
GROUP BY 1, 2 ORDER BY 3 DESC;

-- 2. Where does the time go? (PG 13+ names; total_time/mean_time before that)
SELECT calls, total_exec_time, mean_exec_time, rows, query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

-- 3. Cache, per table rather than as a global average
SELECT relname, heap_blks_hit, heap_blks_read,
       round(heap_blks_hit::numeric / nullif(heap_blks_hit + heap_blks_read, 0), 4) AS hit_ratio
FROM pg_statio_user_tables ORDER BY heap_blks_read DESC LIMIT 10;

-- 4. Bloat, vacuum lag, and what is pinning the horizon
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;

SELECT pid, xact_start, state, backend_xmin, left(query, 60)
FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY backend_xmin LIMIT 5;

pg_stat_statements needs shared_preload_libraries set and a restart, so on a box where it is not loaded that is the first thing to fix.

Reading the results. Wait events are the most decisive signal. IO:DataFileRead means reads are missing shared_buffers: a memory case. Lock:transactionid or Lock:tuple means contention, where more cores buy nothing. LWLock:BufferMapping points at buffer contention, not capacity. On the cache question, pg_stat_database.blks_hit/(blks_hit+blks_read) is an average and hides the hot table; the per-relation view is what matters, and it counts shared-buffer hits only, not OS page cache, so a low ratio is not automatically a RAM shortfall. On bloat, one idle-in-transaction session or an inactive replication slot pins the vacuum horizon and stops vacuum removing anything database-wide. VACUUM makes space reusable but does not shrink the file (only VACUUM FULL, CLUSTER or pg_repack do) so a bloated table keeps costing I/O on every sequential scan. Finally, shared_buffers defaults to 128 MB, work_mem to 4 MB, max_connections to 100, and effective_cache_size is a planner cost input, not an allocation: raising it changes plans, not memory use.

Worked trace (hypothetical: 32 vCPU / 128 GB, shared_buffers = 32 GB). Checkout p99 goes from 12 ms to 90 ms at 14:00 daily.

  • Wait events: 34 of 40 active sessions in IO:DataFileRead. Not locks, not CPU.
  • Global hit ratio 0.998: looks fine. Per table, orders is 0.61 with 900k heap_blks_read. The average hid it.
  • pg_stat_statements top entry: SELECT ... FROM orders WHERE customer_id = $1, 4.1M calls, mean 3.4 ms, 13,940 s of execution time in the stats window. EXPLAIN (ANALYZE, BUFFERS) shows a Seq Scan over 180M rows reading 2.2M shared blocks (≈17.6 GB at 8 kB per block). There is no index on customer_id. Build it: mean drops to 0.2 ms, total to 820 s.
  • orders holds 180M dead tuples against 60M live, last_autovacuum was 6 days ago, and a reporting session with xact_start 5 days old is holding backend_xmin. Vacuum cannot reclaim. Kill it, set idle_in_transaction_session_timeout, then vacuum.

Same box, no purchase. The hardware case is what is left when the index exists, vacuum is current, and the hot set still exceeds shared_buffers plus page cache: that is a well-evidenced decision rather than a hopeful one. The failure mode of skipping the sequence is specific: you buy RAM to cache pages that bloat created, or cores for a query that runs single-threaded, and the problem returns at a larger scale where the failover and restore you actually needed cost more.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

A query is fast for most customers and slow for one. How do you investigate?

Answer

Identical SQL behaving differently by parameter points at data skew, and the investigation is about finding which assumption the outlier violates.

Confirm the skew first. How many rows does this customer have compared with the median and the 95th percentile? Tenant size distributions are usually extremely uneven, the largest can hold thousands of times the median, and if this customer is simply enormous, then a plan chosen for typical customers may be genuinely wrong for them, and nothing is broken except the assumption.

Compare the plans. EXPLAIN ANALYZE for a fast customer and the slow one. If the plans differ, the planner is making a different choice for this parameter, which is usually correct behaviour responding to different selectivity. If the plans are the same and only the timings differ, the plan is fine and there is simply far more data: a different problem with different fixes.

Look for a plan chosen for the wrong value. With bound parameters, a plan may be reused for values with very different selectivity than the one it was planned for. A nested loop that is ideal for a customer with 10 orders is catastrophic for one with 500,000.

Check the statistics for that value. If the customer is in the most-common-values list, the planner has a good estimate; if not, it uses an average that badly understates them. Raising the statistics target for that column can fix it outright.

On remedies: if the plan is wrong, better statistics or extended statistics may fix it. If the plan is right and there is simply more data, the answer is a better index, often one leading with the tenant column so the scan prunes to that tenant, or a different query shape such as keyset pagination, or precomputation for that tenant.

And there is a design conclusion worth drawing rather than just a fix. If one tenant can degrade shared resources, that is a noisy-neighbour problem, and the answer includes per-tenant limits and a statement timeout so one customer's query cannot consume the capacity everyone else needs. Tuning for the largest tenant is a treadmill; bounding the damage is durable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

What does it mean when a query is fast in isolation but slow under load?

Answer

The 60-second answer. "Fast in isolation" means you measured it alone: one connection, warm cache, no competing work. Under load the query's own execution work is usually unchanged (same plan, same rows) but wall time grows. The difference is time spent waiting, not executing. So split total time into execution time and wait time; if execution time is flat while total time rises, stop tuning the query and find out what it waits on.

Measure it. In PostgreSQL, pg_stat_statements gives mean_exec_time and shared_blks_read per statement (PG 13+; mean_time/total_time before). Compare the same query's row under load against its row in isolation. Then pg_stat_activity, wait_event_type and wait_event, shows what running backends wait on right now: Lock/transactionid for row locks, IO for reads, Client for the app, LWLock for internal contention. pg_blocking_pids(pid) names the blocker. MySQL equivalents: sys.innodb_lock_waits and performance_schema.events_waits_current.

The four things that actually change.

Lock contention. Execution time unchanged, wait time dominated by Lock. Concurrent updates to the same rows queue behind each other; a migration taking ACCESS EXCLUSIVE blocks everything. Signature: many backends in wait_event_type = 'Lock' sharing one blocking PID.

Cache eviction. Alone, the working set fits in cache. Under load, other queries evict it. PostgreSQL's shared_buffers defaults to 128MB and MySQL 8.0's innodb_buffer_pool_size also defaults to 128MB: both far smaller than a production working set, so this is common. The tell is in EXPLAIN (ANALYZE, BUFFERS): shared hit=49200 alone versus shared hit=1200 read=48000 under load, same plan, same row count.

Memory pressure changing behaviour. work_mem defaults to 4MB in PostgreSQL and is per sort/hash operation, not per query. Ten concurrent sorts each get their own 4MB, so a query that sorts in memory alone can spill to disk under load. The plan node is identical; the runtime is not.

Queueing. At high utilization, response time is dominated by queueing, not service time. For a single-server queue, response time is S/(1-ρ): at 50% utilization a 10ms query takes 20ms; at 80% it takes 50ms; at 90%, 100ms. Nothing about the query changed. This is why per-query time rises across the board rather than for one query.

Connection exhaustion is the same effect at the pool. PostgreSQL's max_connections defaults to 100 and each connection is a process; MySQL's defaults to 151. Past the point the CPU can run them, you pay context switches and memory, and requests wait for a connection rather than execute. HikariCP's default maximumPoolSize is 10, and its sizing heuristic is cores * 2 + spindles: a 16-core box wants roughly 32, not 200.

Worked trace. A 16-core box, 100 concurrent clients, a query with 8ms execution time. Alone: 8ms. Under load, pg_stat_statements still shows mean_exec_time of 8ms, but wall time is 60ms. pg_stat_activity shows 70 of 100 backends in wait_event_type = 'Lock', all blocked by PID 4821, which is running a 40-second UPDATE. Execution time flat, wait time 52ms, blocker identified. That is a lock problem, not a query problem.

Remedies, with settings. A pooler (pgbouncer, pool_mode = transaction) caps real backends; statement_timeout (default 0, i.e. disabled) bounds a runaway query; heavy readers move to a replica; transactions holding locks get shorter; work_mem rises only if you can afford it per-operation × concurrency.

The question to ask first. Is it always slow, or only sometimes? Always slow → the query. Sometimes → contention. Getting that wrong means a week spent optimising a query that was never the problem.

Curated: · Written: · Reviewed:

Difficulty: Hard