Viewing and Killing Sessions

Use these commands when the connection count nears its limit, an application never releases its connections, or you need to kill a session running a problem query. In all three databases you read user, client program, state, and last activity time from a session list view, and kill a session by its session ID. Killing a session rolls back its open transaction.

Oracle

Required privileges: SELECT on V$SESSION (SELECT_CATALOG_ROLE); ALTER SYSTEM to kill.

Session list

SELECT s.sid, s.serial#, s.username, s.status, s.osuser, s.machine, s.program,
       s.sql_id, s.event, s.last_call_et AS idle_or_run_sec, s.logon_time
FROM v$session s
WHERE s.type = 'USER'
ORDER BY s.last_call_et DESC;
  • status is ACTIVE when the session is working and INACTIVE when it is idle. last_call_et is the number of seconds it has been in that state.
  • On RAC, use GV$SESSION and include inst_id.

Connections by user and program

SELECT username, machine, program, status, COUNT(*) AS cnt
FROM v$session
WHERE type = 'USER'
GROUP BY username, machine, program, status
ORDER BY cnt DESC;
-- Limit and current usage
SELECT resource_name, current_utilization, max_utilization, limit_value
FROM v$resource_limit
WHERE resource_name IN ('sessions', 'processes');

Killing a session

ALTER SYSTEM KILL SESSION '123,45678' IMMEDIATE;          -- 'sid,serial#'
ALTER SYSTEM KILL SESSION '123,45678,@2' IMMEDIATE;       -- RAC: instance number
ALTER SYSTEM DISCONNECT SESSION '123,45678' IMMEDIATE;    -- also cleans up the server process

WARNING The killed session's transaction is rolled back. For a large transaction, locks remain and the rollback takes time until it finishes (watch V$TRANSACTION.used_ublk decrease to follow progress).

Disconnecting idle sessions automatically

To use the profile's IDLE_TIME (minutes), RESOURCE_LIMIT must be TRUE (the default is TRUE in 12c+).

ALTER PROFILE app_profile LIMIT IDLE_TIME 60;

PostgreSQL

Required privileges: pg_read_all_stats to see other users' query text; superuser or pg_signal_backend to kill (superuser sessions excluded).

Session list

SELECT pid, usename, datname, application_name, client_addr, state,
       now() - backend_start AS connected_for,
       now() - state_change  AS in_state_for,
       wait_event_type, wait_event, left(query, 80) AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
ORDER BY state_change;
  • state: active (running), idle (waiting), idle in transaction (idle with a transaction open; the most dangerous, since it blocks locks and VACUUM).
  • query is the last statement executed. When the state is idle, it is a statement that has already finished.

Connections by user and application

SELECT usename, application_name, state, COUNT(*) AS cnt
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename, application_name, state
ORDER BY cnt DESC;
SELECT COUNT(*) AS used, current_setting('max_connections')::int AS max_connections,
       current_setting('superuser_reserved_connections')::int AS reserved
FROM pg_stat_activity;

Canceling queries and terminating sessions

SELECT pg_cancel_backend(12345);      -- cancels only the running statement; the connection stays
SELECT pg_terminate_backend(12345);   -- drops the connection

-- Clean up sessions idle in transaction for more than 30 minutes
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
  AND now() - state_change > interval '30 minutes';

WARNING pg_terminate_backend rolls back the session's transaction. Before killing several sessions by a condition, run a SELECT with the same condition first to check the targets.

Disconnecting idle sessions automatically

ALTER SYSTEM SET idle_in_transaction_session_timeout = '10min';
ALTER SYSTEM SET idle_session_timeout = '60min';   -- PostgreSQL 14+
SELECT pg_reload_conf();

You can also set them per role or per database: ALTER ROLE app SET idle_in_transaction_session_timeout = '5min';

SQL Server

Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+); ALTER ANY CONNECTION to kill.

Session list

SELECT s.session_id, s.login_name, s.host_name, s.program_name, s.status,
       DB_NAME(s.database_id) AS db, s.open_transaction_count,
       s.last_request_start_time, s.last_request_end_time, c.client_net_address
FROM sys.dm_exec_sessions s
LEFT JOIN sys.dm_exec_connections c ON c.session_id = s.session_id
WHERE s.is_user_process = 1
ORDER BY s.last_request_end_time;
  • status: running, sleeping, dormant (reset by the connection pool). A sleeping session with open_transaction_count > 0 is idle with a transaction open.
  • For a quick look, EXEC sp_who2; also works.

Connections by login and program

SELECT login_name, program_name, status, COUNT(*) AS cnt
FROM sys.dm_exec_sessions
WHERE is_user_process = 1
GROUP BY login_name, program_name, status
ORDER BY cnt DESC;

Killing a session

KILL 57;                    -- session_id
KILL 57 WITH STATUSONLY;    -- rollback progress of a session already killed

WARNING KILL rolls back the session's transaction. A long-running transaction takes a long time to roll back, and its locks remain meanwhile. Do not kill system sessions such as 1 to 50.

Disconnecting all connections to a database

Use this before maintenance (restore, rename, and so on) to push out every session connected to the database.

ALTER DATABASE sales SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
-- After the work
ALTER DATABASE sales SET MULTI_USER;