snippetsqlModerate
Use composite type to create new table
Viewed 0 times
newcreatetypecompositeusetable
Problem
In ORDBMS databases I have seen that complex types can be used:
And I can references those types when creating a new table, like:
How can I achieve the same in PostgreSQL?
create type name as( ...)And I can references those types when creating a new table, like:
create table example (row_name ref(name))How can I achieve the same in PostgreSQL?
Solution
You can use a typed table:
CREATE TYPE mytype AS (some_id int, some_col text);
CREATE TABLE example OF mytype (PRIMARY KEY (some_id));
I added a PK constraint (which you did not ask for).
The syntax is documented as second variant in the manual for
Creates a typed table, which takes its structure from the specified composite type (name optionally schema-qualified). A typed
table is tied to its type; for example the table will be dropped if
the type is dropped (with
When a typed table is created, then the data types of the columns are determined by the underlying composite type and are not specified
by the
defaults and constraints to the table and can specify storage
parameters.
There is also a code example at the end of the examples section.
But I have never used that myself. I prefer to have a template table and copy the structure with
CREATE TYPE mytype AS (some_id int, some_col text);
CREATE TABLE example OF mytype (PRIMARY KEY (some_id));
I added a PK constraint (which you did not ask for).
The syntax is documented as second variant in the manual for
CREATE TABLE, which also explains further down:OF type_nameCreates a typed table, which takes its structure from the specified composite type (name optionally schema-qualified). A typed
table is tied to its type; for example the table will be dropped if
the type is dropped (with
DROP TYPE ... CASCADE).When a typed table is created, then the data types of the columns are determined by the underlying composite type and are not specified
by the
CREATE TABLE command. But the CREATE TABLE command can adddefaults and constraints to the table and can specify storage
parameters.
There is also a code example at the end of the examples section.
But I have never used that myself. I prefer to have a template table and copy the structure with
CREATE TABLE tbl1 (LIKE template), leaving no ties to the template.Context
StackExchange Database Administrators Q#116087, answer score: 15
Revisions (0)
No revisions yet.