Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL pg_stat_activity: Tracking Current Queries

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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_monitor role to see queries from all users; otherwise, you will only see your own current session.

Step-by-Step

  1. Connect to your database: Open your preferred SQL editor or terminal and connect to the PostgreSQL instance you wish to monitor.
  2. 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();
    The pg_backend_pid() function returns the process ID of the current server-side process.
  3. 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 by state = 'active' ensures you ignore idle connections and only see statements that are currently consuming resources.
  4. Find long-running queries: To identify queries that have been running for an unusual amount of time, use the query_start timestamp:
    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.
  5. 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';
  6. 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 pid found in the previous steps:
    SELECT pg_cancel_backend(pid);
    Use pg_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_activity without filtering for state = '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_backend immediately kills the connection. This can cause application errors if the app does not have robust reconnection logic. Always try pg_cancel_backend first 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_activity with pg_locks to see if the current query is waiting for a lock held by another process.
  • Check the Query Length: By default, PostgreSQL truncates the query string in pg_stat_activity. If your queries are very long, you may need to increase the track_activity_query_size setting in postgresql.conf and 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 the pg_monitor or pg_read_all_stats role from your administrator.
  • Verify the state: If the query column is empty or shows a previous command, the session is likely in an idle or idle in transaction state, meaning no query is currently executing.
  • Check for connection pooling: If you use a tool like PgBouncer, the pid you see in the application may not match the pid in pg_stat_activity because 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.