Hello, I would like to propose adding a last_executed timestamptz column to pg_stat_statements. This column records when each tracked statement was most recently executed.
The motivation comes from real world experience with monitoring tools like pgwatch that poll pg_stat_statements regularly. Currently, these tools must fetch and store statistics for all statements, even those that haven't executed recently. This creates significant storage overhead. For a database with around 3400 statements polled every 3 minutes, storing full query text requires roughly 2.5 MB per snapshot. Over two weeks, this accumulates to about 17 GB. Even without query text, storage reaches 10 GB. With a last_executed timestamptz, monitoring tools can simply filter statements by "last_executed > NOW() - polling_interval" to fetch only statements that have been executed since the last poll. This eliminates the need for complex workarounds that some tools currently use to identify changed statements (https://github.com/cybertec-postgresql/pgwatch/blob/759df3a149cbbe973165547186068aa7b5332f9d/internal/metrics/metrics.yaml#L2605-L2766). Beyond monitoring efficiency, the timestamp enables other useful queries. You can find statements that haven't executed in 30 days to identify deprecated code paths. You can correlate statement execution with specific time windows during incident investigation. You can also make informed decisions about which statistics to reset. The implementation is straightforward. The timestamp is stored in the Counters structure and updated on every statement execution, protected by the existing spinlock. The overhead is minimal, just a single timestamp assignment per execution. The timestamp persists with other statistics across server restarts. I've bumped the stats file format version to handle the structure change cleanly. The patch includes a new pg_stat_statements_1_14 function, the upgrade script from 1.13 to 1.14, and regression tests. All existing tests continue to pass. I believe this is a simple addition that addresses a real pain point for database monitoring and provides useful functionality for understanding query patterns over time. Thanks in advance! Attached patch applies cleanly to the current master.
0001-pg_stat_statements_last_executed.patch
Description: Binary data
