// system & session reference

SQL CURRENT_SCHEMA and SCHEMA_NAME()

An unqualified name such as orders is looked up in a default schema. Knowing which one explains most 'table does not exist' errors for tables that clearly exist.

カテゴリ
System & session
Returns
text
In this category
5 of 13

構文

SCHEMA_NAME()
current_schema
DATABASE()
SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')

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

エンジンサポート

エンジンSupportメモ
SQL Server Different name or syntax SCHEMA_NAME() with no argument is the caller's default schema
PostgreSQL はい current_schema, the first existing schema on search_path
MySQL Different name or syntax DATABASE(); a schema is a database
SQLite Not built in no schemas; attached databases act as prefixes
Oracle Different name or syntax SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')

例

PostgreSQL

SET search_path = missing_schema, public;
SELECT current_schema, current_schemas(false);  -- public, {public}

SQL Server

SELECT SCHEMA_NAME() AS default_schema;  -- dbo

MySQL

SELECT DATABASE() AS cur_schema;

Oracle

SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') AS cur_schema FROM dual;

知っておくと便利なこと

  • PostgreSQL resolves names through search_path, and current_schema is the first schema on it that exists. current_schemas(true) shows the full path, including the implicit pg_catalog.
  • SQL Server has no per-session switch: the default schema belongs to the database user (usually dbo) and changes only with ALTER USER ... WITH DEFAULT_SCHEMA.
  • Oracle's current schema starts as the login user. ALTER SESSION SET CURRENT_SCHEMA = hr changes name resolution but not privileges.

Questions about CURRENT_SCHEMA / SCHEMA_NAME

Is a schema the same as a database?

In MySQL, yes. In SQL Server and PostgreSQL a database contains schemas. In Oracle a schema is the set of objects a user owns.

How do I change the current schema?

PostgreSQL: SET search_path = sales, public. MySQL: USE sales. Oracle: ALTER SESSION SET CURRENT_SCHEMA = sales. SQL Server: qualify names, or change the user's default with ALTER USER ... WITH DEFAULT_SCHEMA = sales.

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.