Interview › Databases & Caching
How do you find and fix a slow query (EXPLAIN / EXPLAIN ANALYZE)?
Databases & Caching · Intermediate level
Answer
I find a slow query from traces, slow logs, Performance Insights, or pg_stat_statements, then inspect it with EXPLAIN or EXPLAIN ANALYZE. I fix the root cause through better indexes, query rewrite, updated statistics, batching, or schema changes.
Technical explanation
Use real workload evidence from pg_stat_statements, slow logs, Performance Insights, or traces before adding indexes.
EXPLAIN shows the plan; EXPLAIN ANALYZE runs the query and compares estimated versus actual rows and timing.
Sequential scans are not always bad; for small tables or low-selectivity filters they may be optimal.
Hands-on example
Index tuning example:
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20;
CREATE INDEX CONCURRENTLY idx_orders_customer_created ON orders(customer_id, created_at DESC);Re-run EXPLAIN and confirm lower execution time, fewer buffers read, and no large sort. For covering reads, add INCLUDE columns where appropriate.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Databases & Caching interview questions
- What is a composite index, and does column order matter?
- How do you decide which columns to index?
- What is a deadlock, and how do databases detect and resolve them?
- What is a transaction, and what do the ACID properties mean?
- What is WAL (write-ahead logging), and how does it support durability and replication?
- What is AWS DMS, and when would you use it?
- What is schema migration, and how do you run migrations safely in production?
- What is connection exhaustion, and how do you prevent it?