Skip to main content
The CREATE TABLE... AS creates a new table from a . The CREATE TABLE AS statement performs a schema change. For more information about how online schema changes work in CockroachDB, see .

Intended use

Tables created with CREATE TABLE... AS are intended to persist the result of a query for later reuse. This can be more efficient than a when the following two conditions are met:
  • The result of the query is used as-is multiple times.
  • The copy needs not be kept up-to-date with the original table over time.
When the results of a query are reused multiple times within a larger query, a view is advisable instead. The query optimizer can “peek”into the view and optimize the surrounding query using the primary key and indices of the tables mentioned in the view query. A view is also advisable when the results must be up-to-date; a view always retrieves the current data from the tables that the view query mentions.
The default rules for apply.

Required privileges

The user must have the CREATE on the parent database.

Synopsis

create_table_as syntax diagram

Parameters

Known limitations

The of tables created with CREATE TABLE... AS is not automatically derived from the query results. You must specify new primary keys at table creation. For examples, see .

Examples

Setup

To follow along, run to start a temporary, in-memory cluster with the sample dataset preloaded:

Create a table from a SELECT query

Change column names

This statement creates a copy of an existing table but with changed column names:

Create a table from a VALUES clause

Create a copy of an existing table

When a table copy is created this way, the copy is not associated to any primary key, secondary index, or constraint that was present on the original table.

Specify a primary key

You can specify the of a new table created from a selection query:

Define column families

You can define the of a new table created from a selection query:

See also