← Blog
A folded strip of chart paper with one long orange plateau between two marks.
Published on
2026-11-30

Find slow PostgreSQL queries in a time window with pgBadger

A customer reports that the order screen stalled around 15:07 UTC. The database team has a day’s worth of PostgreSQL logs. Sorting all the queries by duration could send the team after a slow job that finished hours earlier. With pgBadger, you can narrow the log to the reported interval and trace a query in the HTML report back to the line that recorded it.

We tested this on PostgreSQL 18.6 with pgBadger 13.3. Four statements ran on a disposable database. Three cleared the 100 ms logging threshold, and only one of those finished inside our window. PostgreSQL logged it at 454.982 ms. Here’s how to reproduce the result with the three log lines below.

Check what the PostgreSQL server logged

pgBadger is an open-source PostgreSQL log analyzer written in Perl. It reads existing log files and generates a report, so you can analyze a copy on another machine without a database connection. Before choosing the input, find out which log format, time zone, and duration threshold applied during the incident. If you have database access, these commands show the current settings. For an older incident, check the configuration that was active then.

SHOW log_min_duration_statement;
SHOW log_line_prefix;
SHOW log_timezone;
SHOW log_destination;

For this test we used the following settings on the disposable server. The server wrote its standard error stream to a local file. On a managed instance, use the provider’s log export to collect the corresponding interval, including both files if rotation split the window. Keep the original log and any reports that show query text within the same access restrictions.

log_destination = 'stderr'
log_timezone = 'UTC'
log_line_prefix = '%t [%p] %u@%d '
log_min_duration_statement = '100ms'
log_statement = 'none'
log_duration = off

The prefix records the timestamp, process ID, user, and database. The trailing space separates the prefix from the severity label. With this configuration PostgreSQL writes the duration and SQL together for completed statements that take at least 100 ms. A quiet log can still represent a busy database executing many short queries. The PostgreSQL logging reference explains how duration thresholds and sampling affect what is captured.

Generate a pgBadger HTML report for the incident

To try the example without changing a server, save these three lines as orders.log in a new directory. They came from a real run of harmless test queries. The names after AS let you recognize each one even when the report groups similar SQL and replaces literal values.

2026-11-30 15:07:04 UTC [44740] labuser@postgres LOG:  duration: 256.391 ms  statement: SELECT pg_sleep(0.25) AS before_probe;
2026-11-30 15:07:06 UTC [51248] labuser@postgres LOG:  duration: 454.982 ms  statement: SELECT pg_sleep(0.45) AS incident_probe;
2026-11-30 15:07:07 UTC [25728] labuser@postgres LOG:  duration: 262.370 ms  statement: SELECT pg_sleep(0.25) AS after_probe;

Install pgBadger using the project’s installation instructions and check pgbadger --version. From the directory containing the log file, run the following command. Both dates use the same UTC clock as the log. On a fresh capture, use the timestamps from that run.

pgbadger -f stderr -p "%t [%p] %u@%d " -b "2026-11-30 15:07:05" -e "2026-11-30 15:07:06" -o incident.html orders.log

-f stderr tells pgBadger to read PostgreSQL’s standard-error text format. For a CSV or JSON log export, select the matching parser instead. The value after -p matches the server’s log_line_prefix. The begin and end arguments limit which timestamped records go into incident.html. The example uses the completion time on the duration line. A long query can start before your chosen interval and still appear if its completion is logged inside it. The pgBadger documentation lists the input formats and date filters.

Match the reported query to the raw log

Open incident.html in a browser, find incident_probe in the query rankings, and expand its details. In our report the execution count was one. The example showed 15:07:06 and displayed a duration of 454 ms. The corresponding raw log line has process ID 51248 and the more precise duration of 454.982 ms.

  • Before the window. PostgreSQL recorded before_probe at 15:07:04. Its 256.391 ms duration qualified for logging, but the date filter excluded it.
  • Inside the window. The server ran SELECT 1 AS fast_probe; successfully and returned 1. It finished below the threshold and contributed no duration line. The separate incident_probe did qualify and appeared in the report.
  • After the window. At 15:07:07, after_probe took 262.370 ms. You can find it in the input file even though it falls outside the report.

The deliberate pg_sleep call gives you a recognizable delay without reading customer data. Its duration measures elapsed statement time. It tells you nothing about how much CPU the query consumed. On a real incident, keep the timestamp, recorded duration, and a representative statement together when you hand the finding to the person investigating the application.

Read query rankings in context

A single slow execution and a query that consumes the most time across hundreds of calls can point to different fixes. Compare the maximum duration, total duration, and execution count for the same normalized query. Those counts cover only statements with usable log entries in the selected window. A 100 ms threshold hides frequent 20 ms calls, so the resulting average cannot stand in for the application’s average response time.

If an expected query is missing, start with the raw file. Check for its completion time, the time zone used in the incident report, and any file rotation. If the line is present, verify the parser format and prefix against that line. If the log contains only an error or a connection event, expanding the time window cannot supply the missing statement duration.

Can pgBadger show every query that ran?

Only if the input contains the corresponding statements. To capture fast and slow queries together for a short test, set log_min_duration_statement = 0 on the disposable database and repeat the test. The fast query will then produce a duration line too. On a busy server that setting can generate a large volume of SQL text. You can create a useful incident report from existing logs even when the original threshold limits what you can count.

Other sections answer different questions. The interactive HTML report can show connection activity, errors, and queries that wrote temporary files when PostgreSQL recorded those events. An empty chart is a reason to check the logging settings. For a recurring daily or weekly review across rotated files, pgBadger also supports incremental reports. A single bounded report is simpler to reconcile with the raw entries for one incident.

For a broader view of recurring work, use pg_stat_statements to compare cumulative query statistics. Once you have a representative read query, the guide to PostgreSQL EXPLAIN ANALYZE shows how to investigate its execution plan. To rehearse the incident workflow on a CPU instance with Hivenet, use a disposable database, record one known delay, and verify that the report finds it before using the same procedure on an actual incident.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.