// system & session reference

SQL Server OBJECT_ID function

OBJECT_ID('dbo.orders', 'U') returns the table's object id, or NULL when no such table exists. It is the usual existence check in SQL Server scripts.

类别
System & session
Returns
int, or NULL
In this category
8 of 13

语法

OBJECT_ID('[database.]schema.name' [, 'type'])

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL Different name or syntax to_regclass('schema.name') returns NULL when missing
MySQL Not built in no function; query information_schema.tables
SQLite Not built in no function; query sqlite_schema
Oracle Not built in no function; query user_objects or all_objects

示例

SQL Server

SELECT CASE WHEN OBJECT_ID('dbo.orders', 'U') IS NULL THEN 'missing' ELSE 'exists' END AS orders_table;

SQL Server

CREATE TABLE #work (id INT);
SELECT CASE WHEN OBJECT_ID('tempdb..#work') IS NULL THEN 0 ELSE 1 END AS in_tempdb;  -- 1

PostgreSQL

SELECT to_regclass('public.orders') IS NOT NULL AS orders_exists;

SQLite

SELECT count(*) AS orders_exists FROM sqlite_schema WHERE type = 'table' AND name = 'orders';

值得了解

  • OBJECT_ID('orders') looks in the current database and your default schema. Qualify the name, OBJECT_ID('dbo.orders'), and pass a type ('U' table, 'V' view, 'P' procedure) so a view with the same name does not count.
  • Temporary tables live in tempdb: OBJECT_ID('tempdb..#work') finds #work, while OBJECT_ID('#work') run from another database returns NULL.
  • For drop-if-exists, DROP TABLE IF EXISTS (SQL Server 2016+, PostgreSQL, MySQL, SQLite, Oracle 23ai) replaces the OBJECT_ID check.
  • PostgreSQL's to_regclass('orders') returns NULL for a missing table, while the cast 'orders'::regclass raises an error.

Questions about OBJECT_ID

How do I check if a table exists in MySQL?

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'orders'.

How do I check if a table exists in Oracle?

SELECT COUNT(*) FROM user_tables WHERE table_name = 'ORDERS'. Oracle stores unquoted names in upper case, so a lower-case literal finds nothing.

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.