Use the CREATE MATERIALIZED VIEW command to create or replace a sorted, projected, materialized view of a subset of the base tables columns. Each of these types of view projects a subset of the base table columns and is sorted on a specific set of the base table columns. The system persistently stores the view. It can be displayed by issuing the \dm command.
CREATE [OR REPLACE] MATERIALIZED VIEW <viewname> AS SELECT <col>[,<col>…]
FROM <table> [ORDER BY <order_col>[,<order_col>…]];
The CREATE MATERIALIZED VIEW command takes the following inputs:
| Input | Description |
|---|---|
| OR REPLACE | Replace an existing materialized view. Use this option to rebuild a view after its base table changes in some way or after you rename a database. |
| <viewname> | The name of the materialized view to be created. |
| <col> | The column or columns that comprise this view. You can specify up to 64 columns. |
| <table> | The table from which the view is created. |
| <order_col> | The column or columns on which to sort. |
The CREATE MATERIALIZED VIEW command has the following outputs:
| Output | Description |
|---|---|
| CREATE MATERIALIZED VIEW | The command was successful. |
| ERROR: Relation 'view' already exists. | A view with the specified name already exists in the database. |
You must be the admin user, or the owner of the database or schema where the materialized view is defined, or your account must have the Create Materialized View privilege. If you specify the OR REPLACE option, you must also have Alter privilege for thematerialized view or for the Materialized View object class.
MYDB.SCH1(USER)=> CREATE MATERIALIZED VIEW kinds AS SELECT t1 FROM
emp ORDER BY name;