PostgreSQL Composite Types
Summary: in this tutorial, you will learn how to define PostgreSQL composite types to represent the structure of a row or record.
In PostgreSQL, composite types allow you to define custom data types with multiple fields. These fields can be any built-in or user-defined types, including other composite types.
Defining PostgreSQL composite types
To define a composite type, use the CREATE TYPE
statement followed by the type name and a list of fields with their corresponding data types.
Here’s the basic syntax for defining a composite type:
In this syntax:
- First, specify the name of the composite type (
type_name
) after theCREATE TYPE
keywords. - Second, define a list of fields of the composite type along with their respective data types.
For example, the following statement defines the address type that stores address information including street, city, state, zip code, and country:
After defining a composite type, you can use it as a data type of a table column.
For example, the following statement creates a table called contacts
whose type of address
column is the address_type
:
Please note that when creating a table, PostgreSQL implicitly creates a corresponding composite type. In this example, PostgreSQL automatically creates the contacts
composite type.
Inserting values into a composite column
To construct a composite value, you use the ROW
expression syntax:
In this syntax, the ROW
keyword is optional when you have multiple fields in the expression. Therefore, you can simplify the composite value as follows:
To indicate a NULL
, you can use the NULL
keyword:
Alternatively, you can omit it in the expression:
For example, the following statement inserts a new row into the contacts
table:
In this example, we use the following composite value to insert into the address
column:
The following statement inserts a value into individual fields of the address
column:
In this statement, we use the column name, followed by a dot, and field name to indicate the field of a composite type.
Querying composite values
The following statement retrieves the rows from the contacts
table:
Output:
To query individual fields of a composite type, you use the following syntax:
For example, the following statement retrieves the id, name, city, state, and zip code of contacts:
Output:
If you retrieve all fields from a composite value, you can use the asterisk (*
) shorthand:
Output:
Updating composite values
The following example updates the country of the contact id 2 to USA
:
Output:
In this example, you cannot put the parentheses around the column name of the composite type after the SET
keyword.
Summary
- Composite types allow you to define custom data types that include multiple fields.