CREATE TABLE statement creates a new table in a database.
Required privileges
To create a table, you must have one of the following:- Membership to the
adminrole for the cluster - Membership to the owner role for the database
- The
CREATEprivilege on the database
Syntax
Parameters
Defines the table as a session-scoped temporary table.Note: The
LOCAL, GLOBAL, and UNLOGGED options are no-ops, allowed by the parser for PostgreSQL compatibility.Create a new table only if a table of the same name does not already exist in the database. If one does exist, do not return an error.Note:
IF NOT EXISTS checks the table name only; it does not check if an existing table has the same columns, indexes, constraints, etc., of the new table.The name of the table to create, which must be unique within its database. When the parent database is not set as the default, the name must be formatted as
database.name.Avoid using the name excluded for any of your tables, as itβs used internally by UPSERT and INSERT ON CONFLICT statements.A comma-separated list of column definitions. Each column requires a name/identifier and data type.You can optionally specify column qualifications such as:
- Column-level constraints
- Collations
- Column family assignments
DEFAULTexpressionsON UPDATEexpressions- Identity columns
NOT VISIBLEproperty
An optional, comma-separated list of table-level constraints. Constraint names must be unique within the table.Supported constraints:
PRIMARY KEYUNIQUECHECKFOREIGN KEY
An optional, comma-separated list of index definitions. For each index, the column(s) to index must be specified; optionally, a name can be specified.Index names must be unique within the table.
Examples
Create a table
Create a table with secondary and GIN indexes
Create a table with a foreign key constraint
Foreign key constraints guarantee a column uses only values that already exist in the column it references.ON DELETE CASCADE specifies that when a row referenced by a foreign key constraint is deleted, all dependent rows are also deleted.
Create a table with a check constraint
Create a table with an identity column
Identity columns are populated with values from a sequence:Create a table from a SELECT statement
UseCREATE TABLE AS to create a new table from the results of a SELECT statement:
See also
- ALTER TABLE
- DROP TABLE
- CREATE INDEX
- SHOW TABLES
- SHOW COLUMNS