Updated on 2025-05-29 GMT+08:00

ALTER SYSTEM KILL SESSION

Description

ALTER SYSTEM KILL SESSION ends a session.

Syntax

ALTER SYSTEM KILL SESSION 'pid, sessionid' [ IMMEDIATE ];

Parameters

  • pid, sessionid

    Specifies the PID and SESSIONID of a session (To obtain the values, see the example.) 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: PIDs and SESSIONIDs of all sessions that can be queried from the system catalog pg_stat_activity. In non-thread pool mode, the PID and SESSIONID are usually the same.

  • 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
-- 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 datname,
       usename,
       pid,
       sessionid,
       state 
FROM pg_stat_activity
WHERE query LIKE 'INSERT INTO tbl_test%';
 datname  | usename |       pid       | sessionid |        state        
----------+---------+-----------------+-----------+---------------------
 postgres | omm     | 139802072635136 |       143 | 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,143';
 pg_terminate_session 
----------------------
 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;