PostgreSQL query writing and optimization for backend interviews 11 questions in 3 chapters

  1. 01Reading plans and estimates
  2. 02Indexes that match the query4 questions
  3. 03Joins, subqueries, counting and reports5 questions

Reading plans and estimates

  • 1.1 How do you read an EXPLAIN ANALYZE plan, and what do you look for first? Hard 4 min

    A plan is a tree; rows flow from the leaves up. For each node I compare the estimated rows with the actual rows, multiply time by loops, and check Buffers for pages read from disk versus cache. A big gap between estimated and actual rows usually explains a bad join or scan choice. Then I look for sequential scans on large tables, rows removed by filter, sorts spilling to disk and nested loops with huge loop counts.

    Read the full answer
  • 1.2 A query that was fast yesterday is slow today with no code change. How can statistics cause that? Hard 4 min

    The planner picks a plan from row estimates, and estimates come from sampled statistics gathered by ANALYZE. After a bulk update, a migration or skewed growth, those statistics can be stale or miss rare values, the estimate flips and so does the plan. I compare estimated and actual rows, run ANALYZE on the table, raise the statistics target for skewed columns, and add extended statistics for correlated columns.

    Read the full answer

Indexes that match the query

  • 2.1 How do you choose the column order of a composite index, and when do partial or covering indexes help? Hard 4 min

    A B-tree index is sorted by its first column, then the second, so put columns compared with equals first, then the one range or sort column. The docs say equality on leading columns plus a range on the next column limits the scan. A partial index covers only the hot rows, like open orders. A covering index with INCLUDE lets the query be answered from the index alone, an index-only scan, if the visibility map is current.

    Read the full answer
  • 2.2 Why does wrapping a column in a function or comparing it with a different type stop the index from being used? Medium 3 min

    A plain index stores the column's raw values, so it only helps when the query compares the raw column. lower of email, a date cast on a timestamp, or an integer column compared with a decimal parameter all compare a computed value instead. I rewrite the condition so the column stands alone, like a half-open date range, match the parameter type to the column, or create an expression index on exactly the expression the query uses.

    Read the full answer
  • 2.3 Why can an OR condition make PostgreSQL ignore your indexes, and how do you rewrite it? Medium 3 min

    An index on one column can't answer a condition that's true when either of two columns matches. PostgreSQL can combine two indexes with a BitmapOr, but only if each side of the OR has a usable index; one unindexed side forces a sequential scan. I make sure each branch is indexed, rewrite same-column ORs as IN or ANY, or split the query into a UNION ALL with a duplicate guard.

    Read the full answer
  • 2.4 How do you make a contains search like LIKE '%boot%' fast, and when do you use full-text search instead? Medium 3 min

    A B-tree can't help a pattern that starts with a wildcard. The pg_trgm extension breaks text into three-character pieces and its GIN or GiST index supports LIKE, ILIKE and regex anywhere in the string, plus similarity for typos. Full-text search with a tsvector and a GIN index matches words after stemming and can rank, which suits natural-language search. For real product search with ranking and facets, that's Elasticsearch's job.

    Read the full answer

Joins, subqueries, counting and reports

  • 3.1 How does PostgreSQL choose between a nested loop, hash join and merge join? Hard 4 min

    A nested loop runs the inner side once per outer row, which is great when the outer side is small and the inner side has an index. A hash join builds a hash table on the smaller input and probes it with the other, which suits large unsorted equi-joins if the table fits in work_mem. A merge join walks two inputs sorted on the join key. The planner picks by estimated rows, so bad estimates mean bad joins.

    Read the full answer
  • 3.2 When do you use EXISTS, IN or a JOIN, and why is NOT IN dangerous? Medium 4 min

    For "customers who placed an order", EXISTS and IN both express a semi-join and PostgreSQL usually plans them the same way; a plain JOIN can duplicate customers with several orders, so it needs DISTINCT. For "customers with no orders", use NOT EXISTS. NOT IN returns no rows at all if the subquery contains a NULL, and the planner can't turn it into an anti-join, so it can become very slow on large data.

    Read the full answer
  • 3.3 Why is COUNT(*) slow on a large table, and what do you do about it? Medium 4 min

    Because of MVCC, different transactions can see different rows, so PostgreSQL has no stored row count and must check row visibility, scanning the table or an index. For exact counts on a filtered set, a matching index allows an index-only scan if the visibility map is current. For UI totals, use the planner's estimate from pg_class or EXPLAIN, show "more than N", or fetch one extra row to know if there's a next page.

    Read the full answer
  • 3.4 How do you get the top N rows per group, such as the three best-selling products per category? Hard 3 min

    Rank rows inside each group with a window function, row_number over a partition by category ordered by sales, then keep rank three or less in an outer query. For large tables where each group is cheap to read in order from an index, a LATERAL subquery with ORDER BY and LIMIT per group can be faster, because it reads only N rows per group instead of ranking everything.

    Read the full answer
  • 3.5 Live task: write the SQL for a monthly category report, then make it fast. Hard 4 min

    I restate the output and edge cases first: which month, revenue definition, cancelled orders, categories with no sales. Then I build it in steps with CTEs: filter orders by a half-open date range, join items and products, group by category, use HAVING for the minimum order count, and a window for share of total. Finally I check EXPLAIN, index the date and join columns, and precompute if it runs often.

    Read the full answer