API performance Level 2 This level · 7 of 20
Hard java backend

Find slow queries: pg_stat_statements and EXPLAIN (ANALYZE, BUFFERS)

The 30 second answer

I use the pg_stat_statements extension to rank queries by total and mean execution time, because a medium query called thousands of times can matter more than one slow query. Then I run EXPLAIN with ANALYZE and BUFFERS on the worst ones. That shows the real plan, actual row counts versus estimates, and how many pages came from cache or disk.

Could you say this in an interview?

pg_stat_statements keeps per-query stats such as calls, total_exec_time and mean_exec_time. Sort by total time to find what costs most overall. EXPLAIN ANALYZE runs the query and shows real row counts and times. BUFFERS shows pages hit in cache versus read from disk.

SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;

Alternate interview scenarios

"How would you optimize a slow SQL query, and where do slow query logs and denormalization fit?"

First I find it. pg_stat_statements ranks statements by total time, and PostgreSQL's log_min_duration_statement logs every statement that runs longer than a threshold I choose, which catches slow individual executions with their parameters. Then I run EXPLAIN with ANALYZE and BUFFERS on a real example and compare estimated with actual rows. Typical fixes, in order: an index that matches the WHERE and JOIN columns, so the planner can seek instead of scanning or hashing whole tables; selecting only needed columns instead of SELECT *; rewriting predicates that hide columns inside functions; and fresh statistics. Denormalization comes last. Copying data into a wider table or a materialized view removes joins from hot reads, but every write must then keep the copy correct, so I only do it for measured hot paths and define how the copy is refreshed.

Sources (4)
  1. PostgreSQL 17: pg_stat_statementspostgresql.org
  2. PostgreSQL 17: EXPLAINpostgresql.org
  3. Using EXPLAINpostgresql.org
  4. PostgreSQL 17: Error reporting and logging (log_min_duration_statement)postgresql.org
Previous
Next