Creating a materialized view in Oracle involves specifying the SELECT statement for the data you want to store, along with various options for refresh and storage. Below is a step-by-step guide on how to create a materialized view in Oracle:
Steps to Create a Materialized View in Oracle
Ensure Necessary Privileges: Ensure you have the necessary privileges to create materialized views and the underlying objects (tables, views).
Basic Syntax: The basic syntax for creating a materialized view is as follows:
Explanation of the Options:
view_name
: Name of the materialized view.BUILD IMMEDIATE | BUILD DEFERRED
: Specifies when the data should be populated.BUILD IMMEDIATE
populates the view at creation, whileBUILD DEFERRED
waits until the first refresh.REFRESH [FAST | COMPLETE | FORCE]
:- FAST: Uses incremental changes (requires materialized view logs on base tables).
- COMPLETE: Rebuilds the entire materialized view.
- FORCE: Attempts
FAST
refresh but defaults toCOMPLETE
if conditions forFAST
are not met.
ON DEMAND | ON COMMIT
:- ON DEMAND: Refreshes the view only when explicitly requested.
- ON COMMIT: Automatically refreshes the view when a transaction that modified one of the underlying tables is committed.
WITH PRIMARY KEY | WITH ROWID
: Specifies how the rows in the materialized view are identified.WITH PRIMARY KEY
uses primary keys from the base tables, whileWITH ROWID
uses the rowids.
Materialized View Log:
For FAST
refresh, you need to create a materialized view log on the base table:
CREATE MATERIALIZED VIEW LOG ON sales WITH ROWID, PRIMARY KEY, SEQUENCE (product_id, quantity, sale_date) INCLUDING NEW VALUES;
Additional Examples:
Complete Refresh on Demand:
Refreshing the Materialized View:
To manually refresh the materialized view, use the following command:
EXEC DBMS_MVIEW.REFRESH('sales_mv');