Updated on 2024-08-20 GMT+08:00

ALTER SYSTEM KILL SESSION

Description

ALTER SYSTEM KILL SESSION ends a session.

Syntax

1
ALTER SYSTEM KILL SESSION 'session_sid, serial' [ IMMEDIATE ];

Parameters

  • session_sid, serial

    Specifies SID and SERIAL of a session (see examples for format). You can use the pg_stat_activity system catalog to query the current active threads (see the examples). However, when you run the ALTER SYSTEM KILL SESSION command, the threads may have ended.

    Value range: SIDs and SERIALs of all sessions that can be queried from the system catalog dv_sessions.

  • IMMEDIATE

    Specifies that a session will be ended instantly after the statement is executed.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
-- Start two sessions, and create a table and start a transaction to insert data in the first session.
gaussdb=# CREATE TABLE tbl_test(id int);
gaussdb=# BEGIN;
gaussdb=# INSERT INTO tbl_test VALUES (1);

-- Query the session information in the second session. If the value of state is idle in transaction, the transaction is waiting to be committed.
gaussdb=# SELECT t1.datname,
       t1.usename,
       t1.pid,
       t2.serial#,
       t1.state 
FROM pg_stat_activity t1,
     dv_sessions t2 
WHERE t1.query LIKE 'INSERT INTO tbl_test%' 
  AND t1.sessionid = t2.sid;
 datname  | usename |       pid       | serial# |        state        
----------+---------+-----------------+---------+---------------------
 postgres | omm     | 139802072635136 |       0 | idle in transaction
(1 row)

-- End a session. If the IMMEDIATE parameter is not specified, the session and transactions in the session are forcibly ended.
gaussdb=# ALTER SYSTEM KILL SESSION '139802072635136,0';
 pg_terminate_backend 
----------------------
 t
(1 row)

-- Perform the reconnection and query the tbl_test table. The transaction is forcibly ended and the data is rolled back.
gaussdb=# SELECT * FROM tbl_test;
 id 
----
(0 rows)

-- Drop the table.
gaussdb=# DROP TABLE tbl_test;