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

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 view 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.

Required privileges

The user must have the CREATE privilege on the parent database.

Synopsis

create_table_as syntax diagram

Parameters

Limitations

The default rules for column families apply. The primary key 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 Specify a primary key.

Examples

Setup

To follow along, run cockroach demo to start a temporary, in-memory cluster with the movr 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 primary key of a new table created from a selection query:

Define column families

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

See also