0
0
PostgreSQLquery~5 mins

pg_stat_statements for slow queries in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is pg_stat_statements in PostgreSQL?

pg_stat_statements is an extension that tracks execution statistics of all SQL statements executed by a server. It helps identify slow or expensive queries.

Click to reveal answer
beginner
How do you enable pg_stat_statements in PostgreSQL?

To enable, add pg_stat_statements to shared_preload_libraries in postgresql.conf and restart the server. Then run CREATE EXTENSION pg_stat_statements; in your database.

Click to reveal answer
beginner
Which view do you query to find slow queries using pg_stat_statements?

You query the pg_stat_statements view. It shows aggregated stats like total time, calls, and average time per query.

Click to reveal answer
intermediate
What SQL query helps find the top 5 slowest queries by average execution time using pg_stat_statements?
SELECT query, calls, total_time, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 5;
Click to reveal answer
intermediate
Why is it useful to look at mean_time instead of total_time when analyzing slow queries?

mean_time shows the average time per execution, helping identify queries that are slow individually, even if they run fewer times. total_time can be high for frequently run fast queries.

Click to reveal answer
What must you do first to use pg_stat_statements in PostgreSQL?
ARun <code>VACUUM</code> on all tables
BCreate a new database
CAdd it to <code>shared_preload_libraries</code> and restart the server
DInstall a third-party tool
Which column in pg_stat_statements shows the average execution time of a query?
Amean_time
Btotal_time
Ccalls
Drows
How can you find the slowest queries using pg_stat_statements?
AOrder by <code>calls</code> descending
BOrder by <code>mean_time</code> descending
COrder by <code>rows</code> ascending
DOrder by <code>queryid</code>
What does the calls column represent in pg_stat_statements?
AQuery text length
BNumber of rows returned
CTotal execution time in milliseconds
DNumber of times the query was executed
Why might a query with high total_time not be slow individually?
AIt runs many times but each execution is fast
BIt returns many rows
CIt has a long query text
DIt uses indexes
Explain how to set up and use pg_stat_statements to find slow queries in PostgreSQL.
Think about configuration, extension creation, and querying statistics.
You got /5 concepts.
    Describe why mean_time is more useful than total_time when analyzing slow queries with pg_stat_statements.
    Consider the difference between average and total values.
    You got /4 concepts.