How to determine the OID of a Postgres table?

To get a table OID, cast to the object identifier type regclass (while connected to the same DB):

SELECT 'mytbl'::regclass::oid;

This finds the first table (or view, etc.) with the given name along the search_path or raises an exception if not found.

Schema-qualify the table name to remove the dependency on the search path:

SELECT 'myschema.mytbl'::regclass::oid;

In Postgres 9.4 or later you can also use to_regclass('myschema.mytbl'), which doesn’t raise an exception if the table is not found:

  • How to check if a table exists in a given schema

Then you only need to query the catalog table pg_attribute for the existence of the column:

SELECT TRUE AS col_exists
FROM   pg_attribute 
WHERE  attrelid = 'myschema.mytbl'::regclass
AND    attname="mycol"
AND    NOT attisdropped  -- no dropped (dead) columns
-- AND    attnum > 0     -- no system columns (you may or may not want this)
;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)