to_regclass Resolve Or NULL
Resolve a table name to an OID with to_regclass: unknown names return NULL instead of raising, enabling guard clauses in scripts.
Code
CREATE TABLE invoices_2026 (id int PRIMARY KEY);
-- 存在的表解析成 OID;不存在的名字返回 NULL 而不是报错
SELECT to_regclass('invoices_2026') AS existing,
to_regclass('public.invoices_2026') AS schema_qualified,
to_regclass('invoices_2030') AS missing;
-- 守卫用法:只有表真的存在时才做维护动作
DO $$
BEGIN
IF to_regclass('public.invoices_2026') IS NOT NULL THEN
RAISE NOTICE 'table exists, size check possible';
END IF;
END $$;
-- 迁移脚本:先确认基表再建索引,避免重复执行时报 already exists
SELECT to_regclass('public.invoices_2026') IS NOT NULL AS can_migrate;
DROP TABLE invoices_2026;How it works
The file runs SELECT / CREATE statements.
What the statements actually assemble: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
The first SELECT resolves three names through to_regclass: the bare invoices_2026 and the schema-qualified public.invoices_2026 both return an OID, while invoices_2030 returns NULL instead of raising an error. The DO block re-checks public.invoices_2026 and only fires RAISE NOTICE 'table exists, size check possible' when the lookup is not NULL, which is the guard-clause pattern for conditional maintenance. The migration query projects the same test as can_migrate, giving the script a boolean it can branch on before creating an index, and the file drops invoices_2026 at the end.
Key statements
SELECT to_regclass('invoices_2026') AS existing,
to_regclass('public.invoices_2026') AS schema_qualified,
to_regclass('invoices_2030') AS missing;
SELECT to_regclass('public.invoices_2026') IS NOT NULL AS can_migrate;
CREATE TABLE invoices_2026 (id int PRIMARY KEY);
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.