Skip to main content
A view is a stored and named selection query. By default, CockroachDB’s views are dematerialized: they do not store the results of the underlying queries. Instead, the underlying query is executed anew every time the view is used. CockroachDB also supports materialized views. Materialized views are views that store their selection query results.
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.

Why use views?

There are various reasons to use views, including:

Hide query complexity

When you have a complex query that, for example, joins several tables, or performs complex calculations, you can store the query as a view and then select from the view as you would from a standard table.

Example

Let’s say you’re using our sample startrek database, which contains two tables, episodes and quotes.
There’s 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:
Then, executing the query is as easy as SELECTing from the view:

Limit access to underlying data

When you do not want to grant a user access to all the data in one or more standard tables, you can create a view that contains only the columns and/or rows that the user should have access to and then grant the user permissions on the view.

Example

Let’s say you have a bank database containing an accounts table:
You want a particular user, bob, to be able to see the types of accounts each user has without seeing the balance in each account, so you create a view to expose just the type and email columns:
You then make sure bob does not have privileges on the underlying accounts table:
Finally, you grant bob privileges on the user_accounts view:
Now, bob will get a permissions error when trying to access the underlying accounts table but will be allowed to query the user_accounts view:

How views work

Creating views

To create a view, use the CREATE VIEW statement:
Any selection query is valid as operand to CREATE VIEW, not just simple SELECT clauses.

Listing views

Once created, views are listed alongside regular tables in the database:
To list just views, you can query the views table in the Information Schema:

Query a view

To query a view, target it with a table expression, for example using a SELECT clause, just as you would with a stored table:
SELECTing a view executes the view’s stored SELECT statement, which returns the relevant data from the underlying table(s). To inspect the SELECT statement executed by the view, use the SHOW CREATE statement:
You can also inspect the SELECT statement executed by a view by querying the views table in the Information Schema:

View dependencies

A view depends on the objects targeted by its underlying query. Attempting to rename an object referenced in a view’s stored query therefore results in an error:
Likewise, attempting to drop an object referenced in a view’s stored query results in an error:
You can drop or rename columns from a table on which a view is dependent, as long as the view does not depend on that column of the table. For example, because there is no view that depends on the num column of the episodes table, you can rename it to number:
Similarly, because no view depends on the title column of the episodes table, you can drop it. Note that to drop a column with data in it, you must first set sql_safe_updates = false.
When dropping a table or dropping a view, you can use the CASCADE keyword to drop all dependent objects as well:
CASCADE drops all dependent objects without listing them, which can lead to inadvertent and difficult-to-recover losses. To avoid potential harm, we recommend dropping objects individually in most cases.

Renaming views

To rename a view, use the ALTER VIEW statement:
It is not possible to change the stored query executed by the view. Instead, you must drop the existing view and create a new view.

Replace a view

To replace a view, use CREATE OR REPLACE VIEW:

Remove a view

To remove a view, use the DROP VIEW statement:

Materialized views

CockroachDB supports materialized views. A materialized view is a view that stores the results of its underlying query. When you select from a materialized view, the stored query data that is returned might be out-of-date. This contrasts with a standard (i.e., “dematerialized”) view, which runs its underlying query every time it is used, returning the latest results. In order to get the latest results from a materialized view, you must refresh the view, and then select from it. Because materialized views store query results, they offer better performance than standard views, at the expense of the additional storage required to store query results and the guarantee that the results are up-to-date.

Usage

Materialized views and standard views share similar syntax for creating, showing, renaming, and dropping. To create a materialized view, use a CREATE MATERIALIZED VIEW statement. For example, suppose that you have the sample bank database loaded to a CockroachDB cluster, and populated with some workload values:
To show existing materialized views, use a SHOW TABLES statement:
Now suppose you update the balance values of the bank table:
The changes can be seen in the table with a simple SELECT statement against the table:
Recall that materialized views do not automatically update their stored results. Selecting from overdrawn_accounts returns stored results, which are outdated:
To update the materialized view’s results, use a REFRESH statement:
To rename the materialized view, use ALTER MATERIALIZED VIEW:
To remove the materialized view, use DROP MATERIALIZED VIEW:

Add an index to a materialized view

To speed up queries on materialized views, you can add an index to the view.
  1. Create a materialized view of the MovR rides table where the revenue is less than $20.00:
  2. To see the plan for a select on this view, run:
    Notice that there are no statistics collected on the view.
  3. Create an index on the city column:
  4. To see the change in the plan after adding the index, run:

Known limitations

  • The optimizer may not select the most optimal query plan when querying materialized views because CockroachDB does not collect statistics on materialized views..
  • CockroachDB cannot refresh materialized views materialized views inside explicit transactions. Trying to refresh a materialized view inside an explicit transaction will result in an error.
    1. Start cockroach demo with the sample bank data set:
    2. Create the materialized view described in Usage.
    3. Start a new multi-statement transaction with BEGIN TRANSACTION:
    4. Inside the open transaction, attempt to refresh the view. This will result in an error.

Temporary views

CockroachDB supports session-scoped temporary views. Unlike persistent views, temporary views can only be accessed from the session in which they were created, and they are dropped at the end of the session. You can create temporary views on both persistent tables and temporary tables.
This feature is in preview and subject to change. To share feedback and/or issues, contact Support.
Temporary tables must be enabled in order to use temporary views. By default, temporary tables are disabled in CockroachDB. To enable temporary tables, set the experimental_enable_temp_tables session variable to on.

Details

  • Temporary views are automatically dropped at the end of the session.
  • A temporary view can only be accessed from the session in which it was created.
  • Temporary views persist across transactions in the same session.
  • Temporary views cannot be converted to persistent views.
  • Temporary views can be created on both persistent tables and temporary tables.
  • When you create a view on a temporary table, the view automatically becomes temporary.
Like temporary tables, temporary views are not in the public schema. Instead, when you create the first temporary table, view, or sequence for a session, CockroachDB generates a single temporary schema (pg_temp_<id) for all of the temporary objects in the current session for a database.

Usage

To create a temporary view, add TEMP/TEMPORARY to a CREATE VIEW statement. For example:

See also