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 withCREATE 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.
CREATE TABLE t AS... with the AS OF SYSTEM TIME clause to leverage historical reads to reduce contention and improve performance.
The default rules for column families apply.
Required privileges
The user must have theCREATE privilege on the parent database.
Synopsis
- Basic
- Expanded
Parameters
Known limitations
The primary key of tables created withCREATE 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, runcockroach 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
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:Populate CREATE TABLE AS with historical data using AS OF SYSTEM TIME
CockroachDB supports creating a table using historical data using the AS OF SYSTEM TIME clause. You can use this to create a new table based on the state of an existing table as of a specific timestamp in the past. This is useful for:
- Generating static datasets for reporting or analytical workloads without increasing contention on production tables or otherwise impacting performance.
- Analyzing data changes over time.
- Preserving historical data for regulatory or investigative purposes.
- Undoing an accidental table deletion.
The timestamp must be within the garbage collection (GC) window of the source table for the data to be available.
movr dataset at the most recent timestamp that can perform a follower read.
Undo an accidental table deletion
The following steps use a table from themovr dataset to show how to undo an accidental table deletion using CREATE TABLE AS... AS OF SYSTEM TIME.
-
Get a timestamp before the table is deleted in an upcoming step:
-
Wait a few seconds to simulate time passing (adjust as needed):
-
Drop the original table:
-
Restore the table using the
AS OF SYSTEM TIMEclause and the timestamp you obtained before dropping the table:
AS OF SYSTEM TIME.

