Database Reference
In-Depth Information
Creating materialized views
Creating a materialized view is slightly different to regular views but populating it
is entirely different and requires a different mechanism. Unlike regular views that
bring the updated data, materialized views gets populated depending on how you
created them and you need a refresh mechanism to do this. Its syntax is as follows:
warehouse_db=# CREATE MATERIALIZED VIEW record.mat_view
AS SELECT * FROM warehouse_tbl
WITH NO DATA;
Using WITH NO DATA will decide whether a view should be
populated at creation time or not. If you opt WITH NO DATA ,
the materialized view will cannot be queried until REFRESH
MATERIALIZED VIEW is used.
We'll insert a few rows and try to access a materialized view as follows:
warehouse_db=# INSERT INTO warehouse_tbl
(warehouse_id, warehouse_name, year_created, street_address,
city, state, zip)
VALUES
(7, 'GMC', 2011, 'getsby Road', 'Fulton', 'NY', 4332);
warehouse_db=# INSERT INTO warehouse_tbl
(warehouse_id, warehouse_name, year_created, street_address,
city, state, zip)
VALUES
(8, 'Ford', 2012, 'fisa Road', 'Elmira', 'NY', 4333);
Now, use a SELECT command to check whether the records have been inserted
successfully as follows:
warehouse_db=# SELECT * FROM record.mat_view;
ERROR: materialized view "mat_view" has not been populated
HINT: Use the REFRESH MATERIALIZED VIEW command.
Execute the following command to resolve the preceding error:
warehouse_db=# REFRESH MATERIALIZED VIEW record.mat_view;
In PostgreSQL 9.4, you can query a materialized view while it's being refreshed for
new data from the parent table. Earlier versions prevented querying, as refreshing
acquires a lock. This can be done with the CONCURRENTLY keyword as follows:
warehouse_db=# REFRESH MATERIALIZED VIEW CONCURRENTLY mat_view;
 
Search WWH ::




Custom Search