// dialect comparison

Current user, database and session id in every SQL dialect

The identity card query: who am I logged in as, where am I, and what is my session id.

Filed under Sessions & admin

The verdict

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.

Where they differ

Every engine has its own functions; there is zero shared syntax here. The concepts map cleanly though: user, database and session identifier.

How each engine writes it

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.

PostgreSQL

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.

MySQL

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.

SQLite

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.

Oracle

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.

Questions that come up

user vs login?

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.

How do I get my session id for KILL?

SQL Server @@SPID, MySQL CONNECTION_ID(), PostgreSQL pg_backend_pid(), Oracle SYS_CONTEXT('USERENV','SID').

What if the connection is pooled?

Session id changes per pooled connection, so do not cache it; re-read it when you need it.

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.