Query planning and optimization
41 questions in 11 subtopics.
EXPLAIN and EXPLAIN ANALYZE
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)?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?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?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.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
How does a cost-based optimizer choose between a sequential scan and an index scan, and what role do table statistics play?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.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?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
Rewrite each predicate so an index on the column can be used: (1) WHEREDATE(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'.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?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.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
Explain nested loop, hash join and merge join. When does each one win?A report query joins 14 tables and its plan changes unpredictably between runs. Explain how PostgreSQL searches join orders and which settings affect it.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?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
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;
Slow query log and pg_stat_statements
How do you find the slowest queries in MySQL and in PostgreSQL? Name the settings or extensions involved.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?Design how query performance data is collected and used across 60 PostgreSQL and MySQL databases owned by different teams.Query rewriting
This query returns no rows even though many customers have no orders:SELECT *
FROM customers
WHERE id NOT IN (SELECT customer_id
FROM orders);
SELECT *
FROM tickets
WHERE assignee_id = 7 OR reporter_id = 7
ORDER BY created_at DESC
LIMIT 50;
Plan regressions
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.You are upgrading PostgreSQL by two major versions for 40 databases. How do you manage the risk of query plan regressions?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
What is the benefit of usingPreparedStatement for repeated queries, and how can a cached plan become a problem?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.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
Why is SELECT COUNT(*) FROM orders slow on a 500 million row PostgreSQL table, and what faster options exist?A Spring Data JPA endpoint returningPage<Order> is slow, and the logs show a SELECT COUNT(*) taking most of the time. How do you fix it?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.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
Inserting 1 million rows with a JDBC loop ofexecuteUpdate takes 40 minutes against PostgreSQL. Show how you would make it fast with JDBC.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?You must load 2 billion rows into a new PostgreSQL table during a migration window of 6 hours. Describe the plan.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?No question matches these choices.