PostgreSQL pg_stat_activity: Tracking Current Queries
In this article
To see the current query running in a PostgreSQL session, you query the pg_stat_activity system view. There is no standalone "function" called current_query; instead, the query column within the pg_stat_activity view provides the text of the last or currently executing statement for every active backend process.
What You'll Need
- A running PostgreSQL database instance.
- A database client (such as psql, pgAdmin, or DBeaver).
- Superuser privileges or the
pg_monitorrole to see queries from all users; otherwise, you will only see your own current session.
Step-by-Step
- Connect to your database: Open your preferred SQL editor or terminal and connect to the PostgreSQL instance you wish to monitor.
- Identify your own current query: If you only need to see the query associated with your current connection, run the following command:
SELECT query FROM pg_stat_activity WHERE pid = pg_backend_pid();
Thepg_backend_pid()function returns the process ID of the current server-side process. - List all active queries: To see every query currently running across the entire server, execute:
SELECT pid, usename, state, query FROM pg_stat_activity WHERE state = 'active';
Filtering bystate = 'active'ensures you ignore idle connections and only see statements that are currently consuming resources. - Find long-running queries: To identify queries that have been running for an unusual amount of time, use the
query_starttimestamp:SELECT pid, now() - query_start AS duration, query FROM pg_stat_activity WHERE state = 'active' ORDER BY duration DESC;
This calculates the difference between the current time and when the query began. - Filter by a specific user or database: If the server is busy, narrow the results to a specific user or database to find the problematic query:
SELECT pid, query FROM pg_stat_activity WHERE usename = 'your_username' AND state = 'active';
- Terminate a hanging query: If you find a current query that is locking tables or consuming too much CPU, you can stop it using the
pidfound in the previous steps:SELECT pg_cancel_backend(pid);
Usepg_terminate_backend(pid)if the query refuses to cancel, as this forcefully closes the entire connection.
Common Mistakes
- Confusing "Idle" with "Active": A common mistake is querying
pg_stat_activitywithout filtering forstate = 'active'. This results in a list of every open connection, most of which are likely "idle," making it difficult to find the actual query causing a performance bottleneck. - Insufficient Permissions: Users often wonder why they only see one row (their own) when querying the view. This happens because non-superusers cannot see the query text of other users' sessions for security reasons.
- Using Terminate instead of Cancel: Using
pg_terminate_backendimmediately kills the connection. This can cause application errors if the app does not have robust reconnection logic. Always trypg_cancel_backendfirst to stop the query while keeping the session alive.
Tips
- Use a View for Monitoring: If you frequently check for slow queries, create a view that calculates duration automatically so you don't have to write the subtraction logic every time.
- Combine with Locks: If a query is "active" but not moving, join
pg_stat_activitywithpg_locksto see if the current query is waiting for a lock held by another process. - Check the Query Length: By default, PostgreSQL truncates the
querystring inpg_stat_activity. If your queries are very long, you may need to increase thetrack_activity_query_sizesetting inpostgresql.confand restart the server.
Troubleshooting
If you cannot see the queries you expect to see, follow these steps:
- Check your role: Run
SELECT current_user;. If you are not a superuser, request thepg_monitororpg_read_all_statsrole from your administrator. - Verify the state: If the
querycolumn is empty or shows a previous command, the session is likely in anidleoridle in transactionstate, meaning no query is currently executing. - Check for connection pooling: If you use a tool like PgBouncer, the
pidyou see in the application may not match thepidinpg_stat_activitybecause the pooler manages the actual server connections. You will need to check the pooler's logs or admin console.
Frequently Asked Questions
Can I see the history of queries that have already finished?
No, pg_stat_activity only shows current or the most recent query. To see historical data, you must enable the pg_stat_statements extension in your configuration.
Does querying pg_stat_activity slow down the database?
No, querying this view is very lightweight and is the standard way to monitor a production database without impacting performance.
Why does the query text look cut off?
PostgreSQL limits the amount of query text stored in memory for this view. This is controlled by the track_activity_query_size parameter in the server configuration.
What is the difference between 'active' and 'idle in transaction'?
An 'active' session is currently executing a command. 'Idle in transaction' means a session started a transaction (e.g., BEGIN) but has not yet sent a COMMIT or ROLLBACK, which can lead to locking issues.
Can I find which IP address a current query is coming from?
Yes, the client_addr column in pg_stat_activity provides the IP address of the connected client.