CREATE VIEW

The CREATE VIEW statement creates a new view, which is a stored query represented as a virtual table.

Note:

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

Synopsis

CREATEVIEWview_name(name_list)ASselect_stmt

Parameters

ParameterDescription
view_nameThe name of the view to create, which must be unique within its database and follow these identifier rules. When the parent database is not set as the default, the name must be formatted as database.name.
name_listAn 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_stmtThe selection query 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.

Example

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

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:

  1. > SELECT startrek.episodes.season, count(*)
  2. FROM startrek.quotes
  3. JOIN startrek.episodes
  4. ON startrek.quotes.episode = startrek.episodes.id
  5. GROUP BY startrek.episodes.season;
  1. +--------+----------+
  2. | season | count(*) |
  3. +--------+----------+
  4. | 2 | 76 |
  5. | 3 | 46 |
  6. | 1 | 78 |
  7. +--------+----------+
  8. (3 rows)

Alternatively, to make it much easier to run this complex query, you could create a view:

  1. > CREATE VIEW startrek.quotes_per_season (season, quotes)
  2. AS SELECT startrek.episodes.season, count(*)
  3. FROM startrek.quotes
  4. JOIN startrek.episodes
  5. ON startrek.quotes.episode = startrek.episodes.id
  6. GROUP BY startrek.episodes.season;
  1. CREATE VIEW

The view is then represented as a virtual table alongside other tables in the database:

  1. > SHOW TABLES FROM startrek;
  1. +-------------------+
  2. | table_name |
  3. +-------------------+
  4. | episodes |
  5. | quotes |
  6. | quotes_per_season |
  7. +-------------------+
  8. (4 rows)

Executing the query is as easy as SELECTing from the view, as you would from a standard table:

  1. > SELECT * FROM startrek.quotes_per_season;
  1. +--------+--------+
  2. | season | quotes |
  3. +--------+--------+
  4. | 2 | 76 |
  5. | 3 | 46 |
  6. | 1 | 78 |
  7. +--------+--------+
  8. (3 rows)

See also

Was this page helpful?
YesNo