SQL session ID: @@SPID and CONNECTION_ID()
The session id links your connection to the server's activity views, lock listings and kill commands.
- Categoria
- System & session
- Returns
integer- In this category
- 7 of 13
Sintaxe
@@SPID
pg_backend_pid()
CONNECTION_ID()
SYS_CONTEXT('USERENV', 'SID')
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | @@SPID; matches session_id in sys.dm_exec_sessions |
| PostgreSQL | Different name or syntax | pg_backend_pid(); matches pid in pg_stat_activity |
| MySQL | Different name or syntax | CONNECTION_ID(); matches ID in the process list |
| SQLite | Not built in | no server, no session id |
| Oracle | Different name or syntax | SYS_CONTEXT('USERENV', 'SID'); matches SID in v$session |
Exemplos
SQL Server
SELECT session_id, login_name, status FROM sys.dm_exec_sessions WHERE session_id = @@SPID;
PostgreSQL
SELECT pid, usename, state FROM pg_stat_activity WHERE pid = pg_backend_pid();
MySQL
SELECT id, user, command FROM information_schema.processlist WHERE id = CONNECTION_ID();
Oracle
SELECT SYS_CONTEXT('USERENV', 'SID') AS sid FROM dual;
Bom saber
- Ids are reused after a connection closes, so an id identifies a live session, not a user or a request over time.
- With a connection pool the id belongs to the pooled connection. Two requests from different users can run on the same id one after the other.
- This is the number you pass to KILL (SQL Server, MySQL) or pg_terminate_backend (PostgreSQL); Oracle's ALTER SYSTEM KILL SESSION also needs SERIAL#. Check it twice: ending your own session is an easy mistake.
Questions about @@SPID / CONNECTION_ID
How do I see what other sessions are running?
SQL Server: sys.dm_exec_requests joined to sys.dm_exec_sql_text. PostgreSQL: the query column of pg_stat_activity. MySQL: SHOW PROCESSLIST or performance_schema.threads. Oracle: v$session joined to v$sql.
Is @@SPID unique?
Only among sessions connected at the same time. After a disconnect the same number is handed to a new session.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.