Sub topic 3
How queries are grouped: normalization and queryid
pgstatstatements does not store one row per execution. It stores one row per group of executions it considers the same query. This chapter explains how that grouping works, so you can read the rankings correctly and avoid two mistakes: assuming two rows are the same query when they are not, and assuming one row is a single query when it is a family of statements.
This chapter assumes you have enabled the extension as described earlier in the tutorial. You should be comfortable running SELECT statements in psql, and you should know that PostgreSQL turns SQL text into a parse tree before planning it.
Why grouping is needed
An application rarely runs a query once. A web request might run SELECT * FROM orders WHERE customer_id = 42 and the next might use 7. If the extension kept each text separately, a busy system would produce millions of rows that each show one call. No ranking of "most expensive query" would be possible.
The extension solves this by removing the constants from each statement and counting the executions of what remains. That process is called normalization.
Normalization: constants become placeholders
When pgstatstatements stores a statement, it replaces literal constants with numbered placeholders: $1, $2, and so on. These are the same symbols used by prepared statements. The stored text is the first text seen for that group, with its constants replaced.
Here is a short experiment. It assumes the extension is already created in your database.
CREATE TABLE IF NOT EXISTS orders (
id bigserial PRIMARY KEY,
customer_id integer NOT NULL,
status text NOT NULL DEFAULT 'new',
total numeric NOT NULL DEFAULT 0
);
SELECT pg_stat_statements_reset();
SELECT * FROM orders WHERE customer_id = 42;
SELECT * FROM orders WHERE customer_id = 7;
select *
from orders -- a comment
where customer_id = 99;
SELECT queryid, calls, query
FROM pg_stat_statements
WHERE query LIKE '%FROM orders%'
AND query NOT LIKE '%pg_stat_statements%';You should see a single row, similar to this (your queryid will differ):
queryid | calls | query
----------------------+-------+------------------------------------------
-4871520936428770517 | 3 | SELECT * FROM orders WHERE customer_id = $1Three statements with three different texts produced one row with calls = 3. The value 42, the value 7, the lowercase keywords, the extra whitespace and the comment did not split the group.
Note that queryid can be negative. It is a 64-bit signed integer (bigint), so do not treat it as a counter or assume it is positive.
What queryid is
The queryid is a hash value. The PostgreSQL server computes it from the parse tree after parse analysis. Parse analysis is the step that resolves names to objects. The hash covers the structure of the statement: which tables and columns, which operators and functions, which clauses. It deliberately skips constant values.
This design explains the behavior you saw:
- Whitespace, comments and keyword case are gone by the time the parse tree exists, so they cannot affect the hash.
- Constants are skipped, so changing
42to7leaves the hash unchanged. - Names are resolved to internal object identifiers (OIDs). The hash therefore depends on which table the name resolved to, not on the spelling of the name.
Since PostgreSQL 14, the core server computes the query identifier. The setting compute_query_id controls this. Its default, auto, turns computation on when a module such as pgstatstatements asks for it. You can check the current value:
SHOW compute_query_id;If it is off, the extension has no identifier to group by. On a normal installation with the extension preloaded, auto is enough.
The full key: more than the queryid
A row in pgstatstatements is identified by a combination of values, not by queryid alone:
userid: the role that ran the statement.dbid: the database it ran in.toplevel: whether the statement ran directly from the client (true) or was nested inside a function or procedure (false). This column exists in PostgreSQL 14 and later.queryid: the hash described above.
If two roles run the same query, you get two rows with the same queryid. The same happens if you run it in two databases, or if you run it both directly and from inside a function while pg_stat_statements.track is set to all. When you rank queries, you usually want one number per query, so aggregate by queryid:
SELECT queryid,
sum(calls) AS calls,
round(sum(total_exec_time)::numeric, 2) AS total_ms,
count(*) AS stat_rows,
min(query) AS query
FROM pg_stat_statements
GROUP BY queryid
ORDER BY sum(total_exec_time) DESC
LIMIT 10;The stat_rows column tells you how many separate entries were merged. A value above 1 means the query ran under more than one role, database or call context.
The diagram shows how a statement reaches its counters.
What splits a group and what does not
| Difference between two statements | Same group? |
|---|---|
| Different constant values | Yes |
| Different whitespace, comments or keyword case | Yes |
| Different column list in SELECT | No |
| Different table, or different operator in WHERE | No |
| Same text, different role | Same queryid, separate rows |
| Same text, different database | Same queryid is not guaranteed; rows are separate |
| Same text, `search_path` resolves a name to a different table | No, because the OIDs differ |
| Same statement on a different major PostgreSQL version | queryid may differ |
The searchpath case catches people in multi-tenant designs where each tenant has its own schema holding an identical table. The text `SELECT * FROM orders WHERE customerid = $1` then appears in many rows with different queryids, each belonging to one tenant's table. A ranking by queryid will spread the cost across them, so the real total for "the orders query" is larger than any single row.
Lists of constants
A query such as WHERE id IN (1, 2, 3) contains three constants, and WHERE id IN (1, 2) contains two. In older PostgreSQL versions each list length produces a different parse tree and so a different group. Applications that build IN lists of varying length can then flood the statistics with near-duplicate rows. Newer releases, starting with PostgreSQL 18, can merge such lists into one group. Check the release notes for your version before relying on either behavior.
If you see many rows whose text differs only in the number of placeholders, such as IN ($1, $2) and IN ($1, $2, $3), you have found this effect. Summing their total_exec_time gives the true cost. A fix on the application side, such as = ANY($1) with an array parameter, keeps the statement shape constant.
Common errors
- Comparing queryids across servers or versions. The hash includes OIDs, which differ between databases and clusters. The algorithm can also change between major versions. A queryid copied from production will not match the same query on a test server.
- Storing queryid as a permanent identifier. After an upgrade, or after a table is dropped and recreated (which gives it a new OID), the same logical query gets a new queryid. If you save snapshots over time, save the query text beside the id.
- Looking for parameter values. Normalization throws the constants away. The extension cannot tell you which
customer_idmade a query slow. To find a real value, use the server log (for example withlog_min_duration_statement) or take the shape from the statistics and test with a representative value. - Reading one row as one query when it hides several roles. Always check whether
useridordbidsplits the entry, or aggregate byqueryidas shown above. - Assuming that equal-looking text means equal queryid. Two rows can show identical text yet have different queryids because of
search_pathortoplevel.
Checking your own system
Run this to see whether any query appears under more than one key:
SELECT queryid,
count(*) AS stat_rows,
count(DISTINCT userid) AS roles,
count(DISTINCT dbid) AS databases,
sum(calls) AS calls
FROM pg_stat_statements
GROUP BY queryid
HAVING count(*) > 1
ORDER BY sum(calls) DESC
LIMIT 10;Rows returned here show queries whose cost is split across entries. Use the aggregated form when you rank by total time in the next chapters.
Exercise
You run SELECT * FROM orders WHERE customer_id = 42 as role app and then the same statement as role report, both in the same database, at the top level. How many rows does pgstatstatements hold for them, and do they share a queryid? Which query would you use to see their combined call count?
Show answer
There are two rows, one for each userid, because the key includes userid. They share the same queryid, since the parse tree is identical. To get the combined count, group by queryid: SELECT queryid, sum(calls) FROM pg_stat_statements GROUP BY queryid;.
Exercise
A table named orders exists in schemas tenant_a and tenant_b. The application sets search_path to one schema per connection and runs the identical text SELECT count(*) FROM orders WHERE status = 'new'. Will the two executions be counted under one queryid? Explain.
Show answer
No. Name resolution happens before the hash is computed, and the hash uses the OID of the resolved table. The two orders tables have different OIDs, so the statements get different queryids and separate rows, even though the text looks the same.