Sub topic 13
Permissions and query text visibility
This chapter covers who can read pg_stat_statements rows, what other users see instead of query text, and how to give a monitoring role the access it needs. It assumes you have enabled the extension as described earlier in this tutorial. It also assumes you can run SQL as a superuser, or can ask someone who can, and that you know PostgreSQL roles and GRANT.
Why visibility rules exist
pg_stat_statements keeps one set of counters for the whole server. Every role's queries go into the same shared memory. The query text can contain table names, column names, and sometimes literal values. If any user could read every row in full, one application role could see what every other role runs.
PostgreSQL splits what a role can see into two parts:
- The statistics. Counters such as
calls,total_exec_time, androwsare visible to anyone who can query the view. - The identifying details. The SQL text and the
queryidare shown only to certain roles.
The visibility rule
A role sees the full row, including query and queryid, in either of these cases:
- The role is a superuser, or has the privileges of the built-in
pg_read_all_statsrole. - The row belongs to the role itself, meaning
useridmatches the current role.
For every other row, the query column contains the placeholder <insufficient privilege>, and queryid is NULL. The counters are still filled in.
You can measure the effect on your own role with a query like this:
SELECT count(*) FILTER (WHERE query = '<insufficient privilege>') AS hidden_rows,
count(*) AS total_rows
FROM pg_stat_statements;If hidden_rows is close to total_rows, you are probably connected as an ordinary application role. Any ranking you build from this view will be mostly unreadable.
Why hidden rows hurt rankings
A ranking by total_exec_time still sorts correctly when the text is hidden, because the counters are intact. You can see that some statement is expensive, but not which one. If you group by queryid, all hidden rows collapse into a single NULL group. That group can look like the biggest consumer on the server when it is really many unrelated queries added together.
Giving a monitoring role access
Do not use a superuser for routine monitoring. PostgreSQL 10 and later provide built-in roles for this purpose. Create a dedicated login role and grant it pg_read_all_stats:
CREATE ROLE metrics_reader LOGIN;
GRANT pg_read_all_stats TO metrics_reader;Set a password or configure authentication for the role in the way your site normally does. The role needs CONNECT on the database, and the default PUBLIC grant usually covers that.
pg_read_all_stats lets the role see the query text and queryid of all users' statements. It also gives read access to other statistics views. It does not allow the role to change data or settings.
The related built-in role pg_monitor includes pg_read_all_stats, pg_read_all_settings, and pg_stat_scan_tables. Monitoring agents are often given pg_monitor. Choose the narrower role when you only need query statistics.
| Role or privilege | Sees counters | Sees text and `queryid` of other users | Can reset statistics |
|---|---|---|---|
| Ordinary role | Yes | No, only its own rows | No |
| `pg_read_all_stats` member | Yes | Yes | No |
| `pg_monitor` member | Yes | Yes | No |
| Superuser | Yes | Yes | Yes |
Resetting is a separate permission
Reading statistics and clearing them are different privileges. By default pg_stat_statements_reset() is restricted to superusers. Membership in pg_read_all_stats does not change this. A reset discards data that other people may be relying on, so grant it deliberately.
The function has different signatures in different PostgreSQL versions. Newer versions let you reset only the rows for a given user, database, or queryid. List the signatures that exist on your server:
SELECT oid::regprocedure AS signature
FROM pg_proc
WHERE proname = 'pg_stat_statements_reset';To let a role reset statistics, grant EXECUTE on the signature this query shows. You can grant a narrow variant without handing out superuser rights.
One view, many databases and roles
The view reports statistics for the whole server, not only the current database. You create the extension per database, because that is where the view and functions live. Once it exists in a database, the view returns rows from every database on the server.
A row's identity is the combination of userid, dbid, toplevel (in PostgreSQL 14 and later), and queryid. The same statement text run by two roles appears as two rows, and the same statement in two databases also appears as two rows. When you rank queries, label each row with the role and database:
SELECT r.rolname,
d.datname,
s.queryid,
s.calls,
round(s.total_exec_time::numeric, 2) AS total_ms,
left(s.query, 60) AS query
FROM pg_stat_statements AS s
JOIN pg_roles AS r ON r.oid = s.userid
JOIN pg_database AS d ON d.oid = s.dbid
ORDER BY s.total_exec_time DESC
LIMIT 10;If the same application runs as several roles, and you want one cost figure per statement, aggregate across roles. Group by queryid and dbid, and take any one copy of the text:
SELECT s.dbid,
s.queryid,
sum(s.calls) AS calls,
round(sum(s.total_exec_time)::numeric, 2) AS total_ms,
min(s.query) AS query
FROM pg_stat_statements AS s
WHERE s.queryid IS NOT NULL
GROUP BY s.dbid, s.queryid
ORDER BY sum(s.total_exec_time) DESC
LIMIT 10;The WHERE s.queryid IS NOT NULL filter keeps hidden rows out of the result, so you do not read a NULL group by mistake.
Skipping the text
Query text is stored outside shared memory, in a file that PostgreSQL reads when you ask for it. That cost matters on a server with many long statements. The function behind the view accepts a showtext argument. Passing false returns the counters without reading the text file:
SELECT queryid, calls, total_exec_time
FROM pg_stat_statements(false)
ORDER BY total_exec_time DESC
LIMIT 10;Monitoring tools that scrape statistics often use this form. They collect the numbers every few seconds and fetch the text separately, only for queries they care about.
Is the query text safe to share?
Normalization replaces constants in most statements with placeholders such as $1, so a query like SELECT * FROM users WHERE email = '[email protected]' is stored with $1 in place of the address. This helps, but you should not assume the text is free of sensitive values:
- Some utility statements, such as
CREATE ROLE ... PASSWORD, may keep their literal values in the stored text. Whether a given utility statement is normalized depends on the PostgreSQL version. - Table, column, and schema names can reveal business details by themselves.
- A query written with the value inside a comment keeps the comment text unless your PostgreSQL version strips it. Check what your version stores before you assume.
Treat the query column as internal data. Restrict pg_read_all_stats to the people and tools that need it, and review it as you would other monitoring access. Before you paste query text into a ticket, a chat, or an external service, scan it for values you would not want to share.
Common mistakes
- Reading the view as an ordinary role and trusting the output. The placeholder text is the sign. Run the hidden-row count first.
- Granting superuser to a monitoring tool. Grant
pg_read_all_statsorpg_monitorinstead. - Expecting a reset to work for
pg_read_all_statsmembers. Reset needs an explicitEXECUTEgrant or superuser rights. - Installing the extension in only one database and expecting to see rows only from there. The view lists the whole server's statements once it exists, so filter on
dbidwhen you want a single database. - Ranking by
useridwithout joiningpg_roles. The number is an OID, not a name.
Exercise
You connect as the role appuser and run SELECT queryid, query FROM pgstatstatements ORDER BY totalexec_time DESC LIMIT 5. Most rows show query = '<insufficient privilege>' and a NULL queryid. The counters look normal. What happened, and what is the least-privileged fix?
Show answer
appuser is neither a superuser nor a member of pgreadallstats, so it can see the text and queryid only for its own statements. The other rows belong to other roles. The least-privileged fix is to connect as a dedicated monitoring role that has been granted pgreadallstats (GRANT pgreadallstats TO metrics_reader;), not to use a superuser.
Exercise
Why can the same statement text appear in several rows of pgstatstatements, and how do you get one total per statement?
Show answer
A row is identified by userid, dbid, toplevel, and queryid, so the same statement run by different roles, in different databases, or both at top level and nested inside a function gets separate rows. To get one total, aggregate with GROUP BY on queryid, and on dbid if you want to keep databases apart. Sum calls and totalexectime, and exclude rows where queryid IS NULL.