CREATE VIEW statement creates a new view, which is a stored query represented as a virtual table.
By default, views created in a database cannot reference objects in a different database. To enable cross-database references for views, set the
sql.cross_db_views.enabled cluster setting to true.CREATE VIEW statement performs a schema change. For more information about how online schema changes work in CockroachDB, see Online Schema Changes.
Required privileges
The user must have theCREATE privilege on the parent database and the SELECT privilege on any table(s) referenced by the view.
Synopsis
Parameters
Support for temporary views is in preview.
Example
Setup
The following examples use thestartrek demo database schema.
To follow along, run cockroach demo startrek to start a temporary, in-memory cluster with the startrek schema and dataset preloaded:
Create a view
The samplestartrek database contains two tables, episodes and quotes. The table also contains a foreign key constraint, between the episodes.id column and the quotes.episode column. To count the number of famous quotes per season, you could run the following join:
SELECTing from the view, as you would from a standard table:
Replace an existing view
You can create a new view, or replace an existing view, withCREATE OR REPLACE VIEW:
Create a materialized view with historical data using AS OF SYSTEM TIME
New in v25.2: You can create a materialized view using historical data with the AS OF SYSTEM TIME clause. This is useful for reducing contention by performing a follower read when populating the view.
Historical data is available only within the garbage collection window.

