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.
- Categoria
- System & session
- Returns
int, or NULL- In this category
- 8 of 13
Sintaxe
OBJECT_ID('[database.]schema.name' [, 'type'])
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | 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 |
Exemplos
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';
Bom saber
- 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.
Related on SQLly
- Add a foreign key if it does not exist Snippet
- CREATE TABLE IF NOT EXISTS variants Snippet
- List columns of a table from system catalogs Snippet
- List indexes of a table with their columns Snippet
- List triggers on a table Snippet
- Table bloat estimate Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL.
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.