SQL Server
SELECT SUSER_SNAME() AS login_name, DB_NAME() AS database_name, @@SPID AS session_id;
USER_NAME() gives the database user (vs the login), ORIGINAL_LOGIN() the pre-execution-as login.
The identity card query: who am I logged in as, where am I, and what is my session id.
Filed under Sessions & admin
No portability at all: five function families. Oracle's SYS_CONTEXT is by far the richest, SQLite has almost nothing to report, and the rest each have a user/database/session triple with slightly different semantics.
Every engine has its own functions; there is zero shared syntax here. The concepts map cleanly though: user, database and session identifier.
SELECT SUSER_SNAME() AS login_name, DB_NAME() AS database_name, @@SPID AS session_id;
USER_NAME() gives the database user (vs the login), ORIGINAL_LOGIN() the pre-execution-as login.
SELECT current_user, session_user, current_database(), pg_backend_pid();
current_user is the effective role (after SET ROLE), session_user the original login; pg_backend_pid is the OS-level backend pid.
SELECT CURRENT_USER() AS account, USER() AS host_detail, DATABASE() AS db, CONNECTION_ID() AS session_id;
CURRENT_USER() shows the matched account, USER() includes the client host; CONNECTION_ID() matches ids used by KILL.
SELECT name, file FROM pragma_database_list;
Embedded database: no logins and no session ids. The database_list pragma names the open schemas (main, temp and any attached files) and their paths, which is as close as it gets.
SELECT USER AS username,
SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') AS current_schema,
SYS_CONTEXT('USERENV', 'SID') AS sid,
SYS_CONTEXT('USERENV', 'DB_NAME') AS db
FROM dual;
SYS_CONTEXT('USERENV', ...) is the general tool: also CLIENT_IDENTIFIER, CURRENT_SCHEMA, OS_USER and dozens more.
SQL Server separates server logins from database users; PostgreSQL separates session_user from effective current_user (SET ROLE); Oracle separates session user from current schema. MySQL's two functions capture the same distinction.
SQL Server @@SPID, MySQL CONNECTION_ID(), PostgreSQL pg_backend_pid(), Oracle SYS_CONTEXT('USERENV','SID').
Session id changes per pooled connection, so do not cache it; re-read it when you need it.
When a session holds locks or burns CPU and nothing else works, terminate it. The verbs differ per engine.
The first thing any support engineer asks for: exact engine and version. Every engine has a one-liner.
The who-is-connected view, including state and the current statement, needed before you kill anything.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.