Scrivio Interview library

Query planning and optimization

41 questions in 11 subtopics.

EXPLAIN and EXPLAIN ANALYZE

ConceptFoundations8 min read
What is the difference between EXPLAIN and EXPLAIN ANALYZE in PostgreSQL, and what are the cost, rows and width numbers in a line such as: Seq Scan on orders (cost=0.00..18334.00 rows=1000000 width=52)?
DebuggingFoundations8 min read
EXPLAIN ANALYZE shows: Nested Loop (actual time=0.05..9120.4 rows=480000 loops=1) with inner Index Scan on order_items (rows=1 estimated, actual rows=48 loops=10000). What does this tell you and what would you check next?
InternalsIntermediate7 min read
Explain what EXPLAIN (ANALYZE, BUFFERS) adds in PostgreSQL. A query shows shared hit=120 read=48000 on the first run and shared hit=48120 read=0 on the second. How do you interpret this when tuning?
ScenarioIntermediate7 min read
A query takes 4 seconds in production but 40 ms when a developer runs it in psql with EXPLAIN ANALYZE against a copy of the database. List the reasons the plans or timings can differ and how you would capture the real production plan.
LeadershipAdvanced7 min read
Your teams rarely look at query plans until production incidents. How would you make reading EXPLAIN output part of normal engineering practice across 25 services without slowing delivery?

Cost-based optimizer and statistics

ConceptFoundations7 min read
How does a cost-based optimizer choose between a sequential scan and an index scan, and what role do table statistics play?
InternalsIntermediate8 min read
A query filters WHERE city = 'Paris' AND country = 'FR' on a table of 10 million addresses. The plan estimates 300 rows but returns 400,000. Explain why, and how you fix it in PostgreSQL.
ScenarioIntermediate6 min read
After a nightly job inserts 20 million rows into an events table, the first morning reports are very slow and become fast again by noon. What is happening and how would you fix it?
LeadershipPrincipal7 min read
Some teams want to replace the cost-based optimizer's decisions with hints everywhere because plans were unpredictable during incidents. As the senior database authority, what position do you take?

Sargable predicates

CodingFoundations7 min read
Rewrite each predicate so an index on the column can be used: (1) WHERE DATE(created_at) = '2026-03-01'; (2) WHERE LOWER(email) = 'a@b.com' with an index on email; (3) WHERE amount + 10 > 100; (4) WHERE name LIKE '%son'.
DebuggingFoundations6 min read
An index exists on orders(customer_id) where customer_id is VARCHAR. The Java code runs SELECT * FROM orders WHERE customer_id = ? with setLong(1, 42) on MySQL and the query does a full table scan. Why?
ScenarioIntermediate7 min read
A search endpoint builds WHERE (:status IS NULL OR status = :status) AND (:from IS NULL OR created_at >= :from) for optional filters. It is slow on a 50 million row table. Explain why and how you would rewrite it.
DesignAdvanced7 min read
You are writing data access guidelines for many teams. Which SQL patterns that defeat indexes would you forbid or flag automatically, and how would you enforce the rules?

Join order

ConceptFoundations7 min read
Explain nested loop, hash join and merge join. When does each one win?
InternalsIntermediate7 min read
A report query joins 14 tables and its plan changes unpredictably between runs. Explain how PostgreSQL searches join orders and which settings affect it.
ScenarioAdvanced8 min read
A dashboard query joins orders, customers and a 3,000 row region table. The planner starts from orders (200M rows) and the query takes minutes. MySQL's EXPLAIN shows the region filter applied last. How do you approach it, and when would you force join order?
DesignPrincipal7 min read
Analysts and product services both run complex multi-join queries on the same OLTP PostgreSQL cluster, and join-heavy analytics keep causing latency spikes. What long-term architecture would you propose?

OFFSET vs keyset pagination

CodingFoundations7 min read
Rewrite this pagination to keyset pagination and explain why it is faster on page 5,000:
SELECT *
FROM posts
ORDER BY created_at DESC
LIMIT 20 OFFSET 100000;
DesignIntermediate7 min read
Product wants a paginated orders API with page numbers, total count, filtering by status and jumping to the last page. The table has 300 million rows. Which parts would you push back on and what API would you design?
LeadershipAdvanced6 min read
Several public APIs in your company use OFFSET pagination and large partners now page through millions of records nightly, causing database load. How would you migrate them without breaking partners?

Slow query log and pg_stat_statements

ConceptFoundations6 min read
How do you find the slowest queries in MySQL and in PostgreSQL? Name the settings or extensions involved.
ScenarioIntermediate7 min read
pg_stat_statements shows one query with calls=48,000,000, mean_exec_time=0.9 ms and the highest total_exec_time on the server. How would you decide what to do?
DesignAdvanced6 min read
Design how query performance data is collected and used across 60 PostgreSQL and MySQL databases owned by different teams.

Query rewriting

DebuggingFoundations7 min read
This query returns no rows even though many customers have no orders:
SELECT *
FROM customers
WHERE id NOT IN (SELECT customer_id
FROM orders);
Explain and fix it.
InternalsIntermediate7 min read
Since PostgreSQL 12, how are CTEs (WITH queries) planned, and when would you add MATERIALIZED or NOT MATERIALIZED?
CodingIntermediate7 min read
Rewrite this for a large table so it can use indexes on both columns:
SELECT *
FROM tickets
WHERE assignee_id = 7 OR reporter_id = 7
ORDER BY created_at DESC
LIMIT 50;
Explain the trade-offs.
LeadershipPrincipal6 min read
An ORM generates most SQL in your company, and many performance problems trace to generated queries. Do you push teams towards hand-written SQL, a SQL-first library like jOOQ, or better ORM use? Explain the long-term choice.

Plan regressions

DebuggingIntermediate7 min read
A query that ran in 20 ms for a year suddenly takes 8 seconds after no code change. Walk through how you find the cause.
ScenarioAdvanced6 min read
You are upgrading PostgreSQL by two major versions for 40 databases. How do you manage the risk of query plan regressions?
LeadershipPrincipal6 min read
Plan regressions caused three severe incidents last year in different products. How would you set up an organisational capability to prevent and respond to them?

Prepared statement plans and parameter sniffing

ConceptFoundations6 min read
What is the benefit of using PreparedStatement for repeated queries, and how can a cached plan become a problem?
InternalsIntermediate6 min read
With the PostgreSQL JDBC driver, a query becomes slow only after it has run several times in the same connection. Explain prepareThreshold, server-side prepared statements and generic plans, and how you would fix the case.
DesignAdvanced6 min read
Your multi-tenant SaaS has one huge tenant with 60 percent of rows and thousands of tiny tenants. Queries with WHERE tenant_id = ? have unstable performance. What design options do you consider?

COUNT(*) on large tables

ConceptFoundations6 min read
Why is SELECT COUNT(*) FROM orders slow on a 500 million row PostgreSQL table, and what faster options exist?
ScenarioIntermediate6 min read
A Spring Data JPA endpoint returning Page<Order> is slow, and the logs show a SELECT COUNT(*) taking most of the time. How do you fix it?
DesignAdvanced6 min read
Design how a product shows counts such as 'unread messages' and 'orders this month' for millions of users without running COUNT on large tables at read time.
LeadershipPrincipal5 min read
Exact totals appear in dozens of UIs and reports, and they drive a large share of database cost. How would you change this at company scale?

Batch and bulk loading

CodingFoundations6 min read
Inserting 1 million rows with a JDBC loop of executeUpdate takes 40 minutes against PostgreSQL. Show how you would make it fast with JDBC.
DebuggingIntermediate6 min read
A Spring Data JPA saveAll of 100,000 entities is slow although hibernate.jdbc.batch_size=50 is set. The entity uses @GeneratedValue(strategy = GenerationType.IDENTITY). Why, and what would you change?
ScenarioAdvanced7 min read
You must load 2 billion rows into a new PostgreSQL table during a migration window of 6 hours. Describe the plan.
DesignPrincipal6 min read
Several teams build their own bulk import pipelines for partner files, each with different reliability and performance. What would you standardise, and what would you leave to teams?