Skip to main content
The 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.
The 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 the CREATE on the parent database and the SELECT privilege on any table(s) referenced by the view.

Synopsis

Parameters

Example

This example highlights one key benefit to using views: simplifying complex queries. For additional benefits and examples, see .

Setup

The following examples use the . To follow along, run to start a temporary, in-memory cluster with the startrek schema and dataset preloaded:

Create a view

The sample startrek 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:
Alternatively, to make it much easier to run this complex query, you could create a view:
The view is then represented as a virtual table alongside other tables in the database:
Executing the query is as easy as 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, with CREATE OR REPLACE VIEW:

Create a view with invoker privileges

To make a view check privileges on the underlying tables as the querying user, include the :
To restore the default behavior later, use .

Create a view that references routines

Views can call both scalar and set-returning in their SELECT statements. The following example builds a view over a table and two UDFs. Create and populate a table:
Define a scalar and a set-returning UDF:
Create a view that references both functions:
Query the view:
Because the view depends on f_scalar and f_setof, attempting to rename either function returns an error:

Create a materialized view with historical data using AS OF SYSTEM TIME

You can create a materialized view using historical data with the clause. This is useful for reducing by performing a when populating the view.
Historical data is available only within the .
The following example creates a materialized view using the most recent data that is available for :
You can also specify an explicit timestamp:

See also