CREATE VIEW

Function

CREATE VIEW creates a view. A view is a virtual table, not a base table. A database only stores the definition of a view and does not store its data. The data is still stored in the original base table. If data in the base table changes, the data in the view changes accordingly. In this sense, a view is like a window through which users can know their interested data and data changes in the database.

Precautions

Syntax

1
2
3
CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW view_name [ ( column_name [, ...] ) ]
    [ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ]
    AS query;

Parameters

Examples

Create a view consisting of columns whose spcname is pg_default:

1
2
CREATE VIEW myView AS
    SELECT * FROM pg_tablespace WHERE spcname = 'pg_default';

Run the following command to redefine the existing view myView and create a view consisting of columns whose spcname is pg_global:

1
2
CREATE OR REPLACE VIEW myView AS
    SELECT * FROM pg_tablespace WHERE spcname = 'pg_global';

Create a view consisting of rows with c_customer_sk smaller than 150:

1
2
3
CREATE VIEW tpcds.customer_details_view_v1 AS
    SELECT * FROM tpcds.customer
    WHERE c_customer_sk < 150;

Updatable Views

After the enable_view_update parameter is enabled, the INSERT, UPDATE, DELETE, and MERGE INTO statements can be used to update simple views. Only 8.1.2 or later supports updates using the MERGE INTO statement.

Views that meet all the following conditions can be updated:

If the definition of the updatable view contains a WHERE condition, the condition restricts the UPDATE and DELETE statements from modifying rows on the base table. If the WHERE condition is not met after the UPDATE statement is executed, the updated rows cannot be queried in the view. Similarly, If the WHERE condition is not met after the INSERT statement is executed, the inserted data cannot be queried in the view. To insert, update, or delete data in a view, you must have the corresponding permission on the view and tables.

Helpful Links

ALTER VIEW, DROP VIEW