// dialect comparison

KILL, pg_terminate_backend and friends in every SQL dialect

When a session holds locks or burns CPU and nothing else works, terminate it. The verbs differ per engine.

Filed under Sessions & admin

The verdict

One job, four syntaxes: KILL by id twice, pg_terminate_backend as a function, ALTER SYSTEM KILL SESSION with a composite id. Killing usually rolls back the victim's open transaction, so check rollback progress before assuming nothing happened.

Where they differ

All four server engines can kill a session; SQLite has no server, so you close the offending connection from the application side.

How each engine writes it

SQL Server

KILL 52;

Session id from sys.dm_exec_sessions. KILL 52 WITH STATUSONLY shows rollback progress; killing a session rolls back its transaction, which can take a while.

PostgreSQL

SELECT pg_terminate_backend(12345);

Hard kill; pg_cancel_backend(pid) first sends a cancel that lets the session clean up gracefully. pg_stat_activity lists the pids.

MySQL

KILL 12345;

KILL CONNECTION 12345 is explicit; KILL QUERY 12345 aborts only the running statement, keeping the connection. Ids from SHOW PROCESSLIST.

SQLite

-- no server-side sessions; close the connection in your code

The library owns the connection; interrupt long queries with sqlite3_interrupt() or by closing the handle. Nothing to do on the server.

Oracle

ALTER SYSTEM KILL SESSION '123,4567';
-- sid, serial# from v$session

Takes sid,serial# because sids are reused. The session is marked killed and cleaned up shortly after; add IMMEDIATE to roll back and release it at once.

Questions that come up

Kill or cancel?

Prefer cancel (pg_cancel_backend, KILL QUERY) when you only want to stop a statement; terminate drops the connection and rolls back everything.

Why does Oracle need the serial number?

Oracle reuses sids after sessions exit; sid plus serial# uniquely identifies one incarnation of a session.

Can I kill my own session?

PostgreSQL allows pg_terminate_backend(pg_backend_pid()) and MySQL allows KILL CONNECTION_ID(). SQL Server refuses (Cannot use KILL to kill your own process) and Oracle raises ORA-00027; disconnect from the client instead.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.