Description
CREATE VIEW defines a view of a query.
The view is not physically materialized. Instead, a query
rewrite rule (an ON SELECT rule) is automatically generated to
support SELECT operations on views.
CREATE OR REPLACE VIEW is similar, but if a view
of the same name already exists, it is replaced. You can only replace
a view with a new query that generates the identical set of columns
(i.e., same column names and data types).
If a schema name is given (for example, CREATE VIEW
myschema.myview ...) then the view is created in the
specified schema. Otherwise it is created in the current schema (the one
at the front of the search path; see CURRENT_SCHEMA()).
The view name must be distinct from the name of any other view, table,
sequence, or index in the same schema.
Notes
Currently, views are read only: the system will not allow an insert,
update, or delete on a view. You can get the effect of an updatable
view by creating rules that rewrite inserts, etc. on the view into
appropriate actions on other tables. For more information see
CREATE RULE.
Use the DROP VIEW statement to drop views.
Usage
Create a view consisting of all Comedy films:
CREATE VIEW kinds AS
SELECT *
FROM films
WHERE kind = 'Comedy';
SELECT * FROM kinds;
code | title | did | date_prod | kind | len
-------+---------------------------+-----+------------+--------+-------
UA502 | Bananas | 105 | 1971-07-13 | Comedy | 01:22
C_701 | There's a Girl in my Soup | 107 | 1970-06-11 | Comedy | 01:36
(2 rows)
Compatibility
SQL92
SQL92 specifies some additional capabilities for the
CREATE VIEW statement:
CREATE VIEW view [ column [, ...] ]
AS SELECT expression [ AS colname ] [, ...]
FROM table [ WHERE condition ]
[ WITH [ CASCADE | LOCAL ] CHECK OPTION ]
The optional clauses for the full SQL92 command are:
- CHECK OPTION
This option is to do with updatable views.
All INSERT and UPDATE commands on the view will be
checked to ensure data satisfy the view-defining
condition. If they do not, the update will be rejected.
- LOCAL
Check for integrity on this view.
- CASCADE
Check for integrity on this view and on any dependent
view. CASCADE is assumed if neither CASCADE nor LOCAL is specified.
CREATE OR REPLACE VIEW is a
PostgreSQL language extension.