Materialized View(MView) is the database object, which is used to store the data of query from other instances to reduce the I/O operations performed on the disc and to improve the overall performance of the query.
I/O Operation is one of the factors we need to consider while improving the performance of the query. I/O Operations are performed when we are using a DBLink to fetch the data of one instance from another instance. In Oracle Applications, usually, we fetch data from OLTP instance to ASCP instance using DBLink or vice versa.
After the Materialized View is created, there are two ways to refresh the Materialized View:
- Manual Refresh: MView can be refreshed on demand by using the standard package dbms_snapshot.refresh_mview
- Automatic Refresh: MView can be refreshed as soon as any changes are made in the table underlying the MView using “On Commit”
Types of Refresh:
- Complete(Full) – Whenever the base table is modified, MView will be truncated first and will be loaded with the data. As the name suggests, it is refreshed completely.
- Fast – Whenever the base table is modified, only the updated records are updated/inserted in the MView. We need “mvlog” file to make “Fast” refresh.
- Force – It will first try to do the “Fast” refresh. If for some reasons, “Fast” refresh fails then it will do the “Complete” refresh.
Syntax for MView:
CREATE MATERIALIZED VIEW department_mv
refresh complete on commit –Automatic Complete refresh
enable query rewrite
SELECT deptno, dept_name, SUM(salary)
GROUP BY deptno, dept_name;
To drop the MView, we can write:
DROP MATERIALIZED VIEW department_mv;
Few Points to Remember:
- Names of Base table and Materialized View cannot be the same
- Cannot perform DML Operations on MView directly.
- We can use truncate and drop
- If we truncate base table then MView will not refresh but if we delete records from base table then MView will be refreshed
- To get all the MViews, we can query: SELECT * FROM users_mview
- If the base table is dropped then the MView is still accessible.
Differences between View and MView:
- A view is the stored query in the database which gets executed when it is called. It does not store any data. MView stores the data of a query.
- The main purpose of View is for security purpose. For eg., if we want to give SELECT access to a certain number of columns of a table then we create a View. The main purpose of MView is to improve the performance of the query i.e. to reduce the I/O Operations performed in the database.
- We can perform DML Operations on View whereas we cannot perform DML Operations on MView.
- If the base table is dropped the view is also not accessible, however, MView is accessible.