Skip to main content

Who is connected

When to use it

When the number of sessions is high, when you need to know which application user holds the connections, or before maintenance.

Run this

Script: 03_count_sessions_by_user.sql. Full version in Administration › Session management › Session status.

-- ============================================================================
-- Script : count_sessions_by_user.sql
-- Descrição: Contagem de sessões ACTIVE/INACTIVE e processos por usuário (RAC)
-- Uso     : @count_sessions_by_user.sql
-- Views   : GV$SESSION, GV$PROCESS
-- ============================================================================

SET TERMOUT OFF;
ALTER SESSION SET NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS';
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(sys_context('USERENV', 'INSTANCE_NAME'), 17) current_instance FROM dual;
SET TERMOUT ON;

SET ECHO        OFF
SET FEEDBACK    OFF
SET HEADING     ON
SET LINES       160
SET PAGES       200
SET VERIFY      OFF
SET TRIMOUT     ON
SET TRIMSPOOL   ON
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES

col username      format a25       heading 'USERNAME'
col inst_id       format 9         heading 'I'
col total         format 99999     heading 'TOTAL'
col active        format 99999     heading 'ACTIVE'
col inactive      format 99999     heading 'INACTIVE'
col killed        format 9999      heading 'KILLED'
col other         format 9999      heading 'OTHER'
col processes     format 99999     heading 'PROCESSES'
col pct_active    format a8        heading '% ACTIVE'
col oldest_hrs    format 9999.9    heading 'OLDEST(h)'
col last_call_max format 9999.9    heading 'IDLE MAX(h)'

SET COLSEP ' | '

PROMPT
PROMPT ============================================================================
PROMPT  Contagem de Sessões e Processos por Usuário  –  Instância: &current_instance
PROMPT  Gerado em: &_DATE
PROMPT ============================================================================
PROMPT

-- ---------------------------------------------------------------------------
-- 1. RESUMO GERAL – ACTIVE / INACTIVE / KILLED por usuário e instância
-- ---------------------------------------------------------------------------
PROMPT [ 1/3 ] Sessoes por usuario / instancia
PROMPT -------------------------------------------------------------------------------

SELECT
    s.inst_id,
    NVL(s.username, '** BACKGROUND **')           AS username,
    COUNT(*)                                        AS total,
    SUM(CASE s.status WHEN 'ACTIVE'   THEN 1 ELSE 0 END) AS active,
    SUM(CASE s.status WHEN 'INACTIVE' THEN 1 ELSE 0 END) AS inactive,
    SUM(CASE s.status WHEN 'KILLED'   THEN 1 ELSE 0 END) AS killed,
    SUM(CASE WHEN s.status NOT IN ('ACTIVE','INACTIVE','KILLED') THEN 1 ELSE 0 END) AS other,
    COUNT(DISTINCT p.spid)                          AS processes,
    LPAD(ROUND(
        SUM(CASE s.status WHEN 'ACTIVE' THEN 1 ELSE 0 END)
        / NULLIF(COUNT(*), 0) * 100, 1
    ) || '%', 7)                                    AS pct_active,
    ROUND(MAX(SYSDATE - s.logon_time) * 24, 1)     AS oldest_hrs,
    ROUND(MAX(s.last_call_et) / 3600, 1)            AS last_call_max
FROM
    gv$session s
    LEFT JOIN gv$process p ON p.addr    = s.paddr
                           AND p.inst_id = s.inst_id
WHERE
    s.type = 'USER'
GROUP BY
    s.inst_id,
    NVL(s.username, '** BACKGROUND **')
ORDER BY
    s.inst_id,
    total DESC,
    username;

-- ---------------------------------------------------------------------------
-- 2. TOTAIS CONSOLIDADOS (todas as instâncias somadas)
-- ---------------------------------------------------------------------------
PROMPT
PROMPT [ 2/3 ] Totais consolidados (todas as instancias)
PROMPT -------------------------------------------------------------------------------

col username   format a25  heading 'USERNAME'
col total      format 99999
col active     format 99999
col inactive   format 99999
col killed     format 9999
col other      format 9999
col processes  format 99999
col pct_active format a8
col oldest_hrs format 9999.9
col last_call_max format 9999.9

SELECT
    NVL(s.username, '** BACKGROUND **')            AS username,
    COUNT(*)                                         AS total,
    SUM(CASE s.status WHEN 'ACTIVE'   THEN 1 ELSE 0 END) AS active,
    SUM(CASE s.status WHEN 'INACTIVE' THEN 1 ELSE 0 END) AS inactive,
    SUM(CASE s.status WHEN 'KILLED'   THEN 1 ELSE 0 END) AS killed,
    SUM(CASE WHEN s.status NOT IN ('ACTIVE','INACTIVE','KILLED') THEN 1 ELSE 0 END) AS other,
    COUNT(DISTINCT p.spid)                           AS processes,
    LPAD(ROUND(
        SUM(CASE s.status WHEN 'ACTIVE' THEN 1 ELSE 0 END)
        / NULLIF(COUNT(*), 0) * 100, 1
    ) || '%', 7)                                     AS pct_active,
    ROUND(MAX(SYSDATE - s.logon_time) * 24, 1)      AS oldest_hrs,
    ROUND(MAX(s.last_call_et) / 3600, 1)             AS last_call_max
FROM
    gv$session s
    LEFT JOIN gv$process p ON p.addr    = s.paddr
                           AND p.inst_id = s.inst_id
WHERE
    s.type = 'USER'
GROUP BY
    NVL(s.username, '** BACKGROUND **')
ORDER BY
    total DESC,
    username;

-- ---------------------------------------------------------------------------
-- 3. GRAND TOTAL (linha única de sumário)
-- ---------------------------------------------------------------------------
PROMPT
PROMPT [ 3/3 ] Grand Total
PROMPT -------------------------------------------------------------------------------

col label      format a25  heading 'ESCOPO'
col total      format 99999
col active     format 99999
col inactive   format 99999
col killed     format 9999
col processes  format 99999
col pct_active format a8

SELECT
    'TODOS OS USUARIOS'                              AS label,
    COUNT(*)                                         AS total,
    SUM(CASE s.status WHEN 'ACTIVE'   THEN 1 ELSE 0 END) AS active,
    SUM(CASE s.status WHEN 'INACTIVE' THEN 1 ELSE 0 END) AS inactive,
    SUM(CASE s.status WHEN 'KILLED'   THEN 1 ELSE 0 END) AS killed,
    COUNT(DISTINCT p.spid)                           AS processes,
    LPAD(ROUND(
        SUM(CASE s.status WHEN 'ACTIVE' THEN 1 ELSE 0 END)
        / NULLIF(COUNT(*), 0) * 100, 1
    ) || '%', 7)                                     AS pct_active
FROM
    gv$session s
    LEFT JOIN gv$process p ON p.addr    = s.paddr
                           AND p.inst_id = s.inst_id
WHERE
    s.type = 'USER';

PROMPT
PROMPT ============================================================================
PROMPT  Fim do relatório
PROMPT ============================================================================
PROMPT

SET FEEDBACK ON
SET COLSEP ' '

For a detailed live view of active sessions, use 01_show_sessions.sql (Administration › Session management › Session status): active sessions with their SQL, wait and elapsed time.

How to read the output

  • One row per instance and user. active sessions are working now; inactive sessions are connected but idle.
  • Many inactive sessions for one application user usually means a connection pool. That is normal up to the size the pool is meant to have.
  • oldest_hrs is the age of the oldest session and last_call_max is the longest idle time, both in hours.
  • killed sessions that never go away are waiting for cleanup and still hold a process.

What to do next

  • If one user holds far more sessions than usual, tell the application team before you do anything else.
  • Do not remove idle sessions on your own. See "Killing a session safely" first.

Risk level

READ ONLY Safe to run at any time. It only queries the data dictionary.