Explicitly distinguish similar queries in pg_stat_statements?

pg_stat_statements is (thankfully) pretty smart at normalizing queries to aggregate stats regardless of the arguments you pass. However, I'm facing a situation where a particular query is called from many locations across our application and I would like to get separate statistics based on these various locations. Inspired by the Marginalia library, I tried to append SQL comments to annotate the query. Unfortunately it doesn't work. See this example:

SELECT * FROM users WHERE email = 'a@b.c' /* action: signup */
SELECT * FROM users WHERE email = 'x@y.z' /* action: login */

What happens is that pg_stat_statements stores a normalized representation of the query with the first comment it sees:

SELECT * FROM users WHERE email = $1 /* action: signup */

Then, if I call the same query with different comments (or no comment at all), the stats will be aggregated into the same item. Comments are effectively ignored from the normalized query representation.

Is there any way to call equivalent SQL queries but have them tracked separately by pg_stat_statements?

1 answer

  • answered 2018-10-11 19:44 Laurenz Albe

    No, there isn't.

    If you need that, and the statement has a long duration, you can use log_min_duration_statement and aggregate the durations yourself.