pg_stat_statements for slow queries in PostgreSQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time to find slow queries grows as the number of queries increases.
How does checking query statistics scale when many queries are logged?
Analyze the time complexity of this query using pg_stat_statements.
SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;
This query fetches the top 10 slowest queries by average execution time.
Look for repeated steps in the query process.
- Primary operation: Sorting all recorded queries by their average time.
- How many times: Once per query execution, but sorting involves comparing all query entries.
As the number of queries logged grows, sorting takes more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: Sorting work grows faster than the number of queries, roughly by n log n.
Time Complexity: O(n log n)
This means the time to find the slowest queries grows a bit faster than the number of queries as more are logged.
[X] Wrong: "Sorting the queries is just a simple list scan and takes linear time."
[OK] Correct: Sorting requires comparing many pairs, so it takes more than just looking once at each query.
Understanding how query statistics scale helps you manage database performance and shows you can think about efficiency in real systems.
"What if we added a filter to only sort queries from the last hour? How would the time complexity change?"
Practice
pg_stat_statements extension in PostgreSQL?Solution
Step 1: Understand the role of pg_stat_statements
The extension collects statistics about query execution times and counts, helping identify slow queries.Step 2: Compare with other options
Options A, B, and D describe unrelated database functions like backup, permissions, and storage optimization.Final Answer:
To track and report query execution statistics including slow queries -> Option DQuick Check:
pg_stat_statements = track slow queries [OK]
- Confusing pg_stat_statements with backup tools
- Thinking it manages user roles
- Assuming it optimizes disk space
pg_stat_statements extension in PostgreSQL?Solution
Step 1: Recall the syntax to enable extensions
PostgreSQL usesCREATE EXTENSION extension_name;to enable extensions.Step 2: Check other options
Commands like ENABLE, LOAD, or START are not valid for enabling extensions in PostgreSQL.Final Answer:
CREATE EXTENSION pg_stat_statements; -> Option AQuick Check:
Enable extension = CREATE EXTENSION [OK]
- Using ENABLE or LOAD instead of CREATE EXTENSION
- Forgetting the semicolon at the end
- Trying to enable without superuser rights
SELECT query, total_time, calls FROM pg_stat_statements ORDER BY total_time DESC LIMIT 1;
What does this query return?
Solution
Step 1: Analyze the ORDER BY clause
The query orders results bytotal_timein descending order, so the highest total execution time is first.Step 2: Understand the LIMIT 1
LIMIT 1 returns only the top row, which is the slowest query by total execution time.Final Answer:
The query with the highest total execution time and its stats -> Option CQuick Check:
ORDER BY total_time DESC LIMIT 1 = slowest query [OK]
- Thinking it returns the most recent query
- Confusing total_time with average time
- Assuming it returns all queries
SELECT * FROM pg_stat_statements WHERE query = 'SELECT * FROM users';
But it returns no rows. What could be the problem?
Solution
Step 1: Understand how pg_stat_statements stores queries
It stores normalized query texts, so exact string matches may fail if whitespace or formatting differs.Step 2: Consider other options
While B is possible, the question implies pg_stat_statements is enabled. C and D do not explain no rows for that query text.Final Answer:
The exact query text does not match due to whitespace or formatting differences -> Option AQuick Check:
Exact query text match may fail due to formatting [OK]
- Assuming any query text matches regardless of formatting
- Ignoring that extension might be disabled
- Thinking table existence affects pg_stat_statements output
pg_stat_statements to start fresh after fixing slow queries. Which command should you run?Solution
Step 1: Identify the correct function to reset stats
PostgreSQL provides the functionpg_stat_statements_reset()to clear collected statistics.Step 2: Evaluate other options
RESET is not valid syntax here, DROP EXTENSION removes the extension, and TRUNCATE is not allowed on this view.Final Answer:
SELECT pg_stat_statements_reset(); -> Option BQuick Check:
Reset stats = pg_stat_statements_reset() function [OK]
- Trying to DROP the extension to reset stats
- Using RESET command incorrectly
- Attempting to TRUNCATE the stats view
