// system & session reference

SQL DB_NAME and current_database()

Scripts that run against several databases often need to know which one they are in. Each engine has a function for it, and SQLite has none.

Categoria
System & session
Returns
text
In this category
3 of 13

Sintaxe

DB_NAME()
current_database()
DATABASE()
SYS_CONTEXT('USERENV', 'DB_NAME')

Each block is a separate form. The support table and the examples show which engine takes which.

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim DB_NAME(); DB_NAME(id) names another database
PostgreSQL Different name or syntax current_database()
MySQL Different name or syntax DATABASE() or its synonym SCHEMA(); NULL when no default database is selected
SQLite Not built in no name; PRAGMA database_list shows main and the file path
Oracle Different name or syntax SYS_CONTEXT('USERENV', 'DB_NAME') or ORA_DATABASE_NAME

Exemplos

SQL Server

SELECT DB_NAME() AS current_db, DB_NAME(1) AS first_db;  -- first_db is master

PostgreSQL

SELECT current_database();

MySQL

SELECT DATABASE(), SCHEMA();  -- the same name twice

Oracle

SELECT SYS_CONTEXT('USERENV', 'DB_NAME') AS db, SYS_CONTEXT('USERENV', 'CON_NAME') AS container FROM dual;

Bom saber

  • MySQL's DATABASE() is NULL until a default database is chosen with USE or in the connection settings.
  • In MySQL a database and a schema are the same thing, so DATABASE() and SCHEMA() agree. In SQL Server and PostgreSQL one database holds many schemas, and DB_NAME() says nothing about the schema.
  • Connected to an Oracle pluggable database, SYS_CONTEXT('USERENV', 'DB_NAME') returns the PDB name (FREEPDB1 on the Free image), not the container database's name.

Questions about DB_NAME / current_database

How do I list all databases?

SQL Server: SELECT name FROM sys.databases. PostgreSQL: SELECT datname FROM pg_database. MySQL: SHOW DATABASES. SQLite: PRAGMA database_list lists the attached files. Oracle: SELECT name FROM v$pdbs, which needs privileges on the view.

What is the SQLite equivalent?

A SQLite connection opens a file, not a named database. SELECT file FROM pragma_database_list WHERE name = 'main' returns its path, which is empty for an in-memory database.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

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.