Skip to main content

Killing a session safely

When to use it

Only after you have identified the session, understood what it is doing, and received confirmation from the application owner or a senior DBA.

Run this

This script does not kill anything. It writes the kill commands for the inactive sessions of one user to a file so you can review them. Script: kill_inactive_sessions.sql. Full version in Administration › Session management › Session cleanup.

-- ============================================================
-- Kill inactive sessions por usuario
-- Uso: @kill_inactive_sessions.sql <USERNAME>
-- Exemplo: @kill_inactive_sessions.sql SYSADM
-- ============================================================

DEFINE target_user = '&1'

SET LINESIZE 200
SET PAGESIZE 0
SET FEEDBACK OFF
SET HEADING OFF
SET TRIMSPOOL ON
SET VERIFY OFF

-- Gera o spool com os comandos de kill
SPOOL /tmp/kill_sessions_&&target_user..sql

PROMPT -- ============================================================
PROMPT -- Kill inactive sessions: &&target_user
PROMPT -- ============================================================
PROMPT

SELECT
    'ALTER SYSTEM KILL SESSION ''' || s.sid || ',' || s.serial# || ',@' || s.inst_id || ''' IMMEDIATE;'
    || '  -- inst: '      || s.inst_id
    || '  | machine: '    || LOWER(s.machine)
    || '  | module: '     || LOWER(NVL(s.module, 'n/a'))
    || '  | status: '     || LOWER(s.status)
    || '  | last_call: '  || s.last_call_et || 's'
FROM gv$session s
WHERE s.username  = UPPER('&&target_user')
  AND s.status   != 'ACTIVE'
  AND s.type     != 'BACKGROUND'
ORDER BY s.inst_id, s.last_call_et DESC;

SPOOL OFF

SET FEEDBACK ON
SET HEADING ON
SET VERIFY ON

PROMPT
PROMPT >>> Spool gerado em: /tmp/kill_sessions_&&target_user..sql
PROMPT >>> Para executar o kill: @/tmp/kill_sessions_&&target_user..sql
PROMPT

The command it generates, for one session:

ALTER SYSTEM KILL SESSION 'sid,serial#,@inst_id' IMMEDIATE;

How to read the output

  • Each generated line ends with a comment showing instance, machine, module, status and seconds since the last call. Read it for every line.
  • The script only lists sessions that are not ACTIVE. An active session is running something and needs a separate decision.
  • After a kill, the session shows KILLED until its transaction finishes rolling back. A large transaction can take a long time to roll back.

What to do next

  1. Run the script and open the generated file.
  2. Remove any line you are not sure about.
  3. Get confirmation in writing, with the list of sessions.
  4. Run the remaining lines and check the result with "Who is connected".
  5. Record what was killed, when and who approved it.

Risk level

DESTRUCTIVE This ends sessions or removes things and cannot be undone. Confirm with a senior DBA before running it in production.