I have the following line in a CREATE TABLE statement:
field1_id bigint DEFAULT nextval('table1_field1_id_seq'::regclass) NOT NULL,
What does regclass mean in the above? Is it an absolute requirement to add ::regclass?
N.B: I had seen the Postgresql documentation link which tells about regclass, but couldn’t understand it.
No, you do not need the cast to
regclasswhen calling a function likenextvalthat accepts aregclassparameter, as there is an implict cast fromtexttoregclass. In some other contexts an explicit cast toregclassmay be required.Explanation:
::regclassis a cast, like::integer.regclassis a “magic” data type; it’s actually an alias foroid, or “object identifier”. See Object identifier types in the documentation. Casting toregclassis a shortcut way of saying “this the name of a relation, please convert it to the oid of that relation”. Casts toregclassare aware of thesearch_path, unlike queryingpg_classfor a relation’soiddirectly, so casting to regclass isn’t exactly equivalent to subqueryingpg_class.Tables are relations. So are sequences, and views. So you can get the oid of a view or sequence by casting to regclass too.
There are implicit casts defined for
texttoregclass, so if you omit the explicit cast and you’re calling a function that acceptsregclassthe cast is done automatically. So you do not need it in, for example,nextvalcalls.There are other places where you may. For example you can’t compare
textdirectly withoid; so you can do this:but not this:
Just for fun I tried to write a query that performed the equivalent operation of casting to
regclass. Don’t use it, it’s mostly for fun, and as an attempt to demo what’s actually happening. Unless you’re really interested in how Pg’s guts work you can stop reading here.As I understand it,
'sequence_name'::regclass::oidis roughly equivalent to the following query:except that it’s a lot shorter and a lot faster. See System information functions for the definition of
current_schemas(...), etc.In other words:
pg_classfor relations with matching names and associate each with its namespace (schema)search_path