CREATE VIEW statement creates a new , 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 to true.CREATE VIEW statement performs a schema change. For more information about how online schema changes work in CockroachDB, see .
Required privileges
The user must have theCREATE on the parent database and the SELECT privilege on any table(s) referenced by the view.
Synopsis
Parameters
| Parameter | Description |
|---|---|
MATERIALIZED | Create a . |
IF NOT EXISTS | Create a new view only if a view of the same name does not already exist. If one does exist, do not return an error. Note that IF NOT EXISTS checks the view name only. It does not check if an existing view has the same columns as the new view. |
OR REPLACE | Create a new view if a view of the same name does not already exist. If a view of the same name already exists, replace that view. In order to replace an existing view, the new view must have the same columns as the existing view, or more. If the new view has additional columns, the old columns must be a prefix of the new columns. For example, if the existing view has columns a, b, the new view can have an additional column c, but must have columns a, b as a prefix. In this case, CREATE OR REPLACE VIEW myview (a, b, c) would be allowed, but CREATE OR REPLACE VIEW myview (b, a, c) would not. |
view\_name | The name of the view to create, which must be unique within its database and follow these . When the parent database is not set as the default, the name must be formatted as database.name. |
name\_list | An optional, comma-separated list of column names for the view. If specified, these names will be used in the response instead of the columns specified in AS select\_stmt. |
AS select\_stmt | The to execute when the view is requested. Note that it is not currently possible to use \* to select all columns from a referenced table or view; instead, you must specify specific columns. |
opt\_temp | Defines the view as a session-scoped temporary view. For more information, see . Support for temporary views is . |
Example
Setup
The following examples use the . To follow along, run to start a temporary, in-memory cluster with thestartrek 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:

