Vous êtes sur la page 1sur 43

10g

Views Vs Materialized Views

Oracle Database Objects Oracle Objects that are associated with a particular schema. Objects in database that is used to store or reference data. Few Objects given below. Object TABLE VIEW SEQUENCE SYNONYMS INDEX CLUSTER PARTITIONS TRIGGERS
TABLE

Description Basic unit of stoage; composed of rows and columns Logically represents subsets of data from one or more tables Numeric value Generator Give alternative names to objects Improves Performance of queries Is made up group of tables that share same data blocks It allows a table index or IOT to be sub divided into pieces Triggers are PL/SQL code that is fired on a specified event

The most common object in all of the database is TABLE .


TABLE / RELATION

Emp Id

Name

Qualification

10000 10002 10003

WHITE SMITH RED

MBA MCA MBM


TUPLE/ROW

ATTRIBUTE / COLUMN

Data is stored in database as set of tables Database divided into number of tables. Tables are joined by relational links. Datas are stored as rows and columns in multiple tables. RDBMS stores data in tables with relationships to other tables. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Oracle Views Views are derived from tables. Views do NOT contain any data; but can be queried. Views are known as Logical Tables I.e. (Virtual Table). Data in a view can be updated or deleted, and new data inserted. SQL statements that is stored in memory so that it can easily be re-used. Views are defined by a query that extracts data from the tables (Base Tables) View details can be queried by USER_VIEWS/ALL_VIEWS/DBA_VIEWS. Why we need views Improve security. Protect data integrity. Reduce complexity. Rename table columns. Customize the data for the users. To create a view from emp table SQL> CREATE VIEW <view_name> AS SELECT <col_name1> , <col_name2>, FROM <table_name> ;

SQL> CREATE VIEW emp_view AS 2 SELECT id , name , qual , email FROM emp; create view command creates a new view for emp table. emp_view is the name of the view and emp is the base table. Once a view is created, a view can be used similar to a table.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Base table Vs emp_view desc emp ID NAME CITY QUAL SALARY EMAIL NUMBER VARCHAR2(15) VARCHAR2(15) VARCHAR2(15) NUMBER VARCHAR2(20) desc emp_view ID NAME QUAL EMAIL -

NUMBER VARCHAR2(15) VARCHAR2(15) VARCHAR2(20) -

Optional Method to create a View : SQL> CREATE VIEW emp_view 2 ( eid , ename , equal, email ) AS 3 SELECT id , name , qual , email FROM emp; ** Duplicate column names used for a view i.e. different from base table. ** Mechanism of Views Oracle stores a view's definition in the data dictionary as the text of the query that defines the view. When we want to reference a view; (sql statements) Oracle , merges the statement that (the reference view). Parses the merged statement in a shared SQL area. Executes the statement. Example Query SQL>SELECT * FROM view_emp WHERE empid BETWEEN 500 AND 1000; Oracle will transform the Query into following method; SQL>SELECT * FROM (select empid from emp) WHERE empid BETWEEN 500 AND 1000; Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Example for Creating View SQL>create table emp1 ( empid number , ename varchar(15) , 2 qual varchar(15) , dept varchar(15), 3 salary number(15) , bonus number ); Table created. Checking emp1 table details : SQL> select * from emp1;
EMPID ENAME QUAL DEPT SALARY BONUS

1000 1002 1003 1005 1009 1012 1015

Sam Sona Chris Maya Sony Rose Smith

mca mba mca msc mba ms mba

It Hr It It Hr It payroll

20000 25000 28000 25000 20000 30000 20000

4000 4200 4000 4300 3400 4000 4000

more rows are displayed Creating View for emp1 table SQL> create view emp1_view AS 2 select empid, ename, qual, dept from emp1 3 where empid between 1000 and 1010 ; View created. From this view ( emp1_view ), two operations were performed ; They are Hiding columns ( SALARY , BONUS ) and records > 1010 This information can be confirmed by dba_views ( text ) option; Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

View can be determined by : dba_views SQL> select view_name , text from dba_views where 2 VIEW_NAME='EMP1_VIEW';
VIEW_NAME TEXT

EMP1_VEW

select empid , ename , qual, dept from emp1 where empid between 1000 and 1010

Checking emp1_view (VIEW) details : SQL> select * from emp1_view; (records > 1010 was hiding )
EMPID ENAME QUAL DEPT

1000 1002 1003 1005 1009

sam sona chris maya sony

mca mba mca msc mba

it Hr It It Hr

ORA-01731: Circular view definition Encountered SQL>create or replace view emp1_view as 2 select from emp1_view with read only; create or replace view emp1_view as * ERROR at line 1: ORA-01731: circular view definition encountered
SOLUTION : We can't create an object that is based on the object. SAME OBJECT (same name) in the CREATE VIEW as in the SELECT. That is OPs

circular reference. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Options for creating Views


VIEW

Name of the View


FORCE

Creating a view regardless (in any case) of whether or not the base tables exist
NOFORCE

Default. Creates the view - If the base table(s) exist.


OR REPLACE

Re - create the view if it already exists without having to drop.


WITH READ ONLY

Ensures that no operations can be performed on this view.


ALIAS

Specifies names for the expressions selected by the views query. The no of aliases must match the no of expressions selected by the view.
CHECK OPTION

Ensures that no operations can be performed on this view.

View is based on underlying tables in the database so no data loss

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g VIEW

Views Vs Materialized Views

SQL> create view v1 as select * from garbage; create view v1 as select * from garbage * ERROR at line 1: ORA-00942: table or view does not exist Even we create a table named garbage , need to recreate a view.
FORCE

SQL> CREATE FORCE VIEW <view_name> AS SELECT < any valid select query >; SQL> create force view v1 as select * from garbage; Warning: View created with compilation errors. NOTE : If we create a table named garbage v1 view will execute and the view is automatically recompiled and becomes valid.
WITH READ ONLY

SQL> CREATE VIEW <view_name> AS SELECT <column_names> from <table_name> with READ ONLY ; SQL> create view v2 AS 2 select * from sample with read only; View created. SQL> insert into v2 values(1002, 'sona', '20000'); insert into v2 values(1002,'sona','20000') * ERROR at line 1: ORA-01733: virtual column not allowed here INSERT/UPDATE/DELETE data in the base tables, instead of the view. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g OR REPLACE

Views Vs Materialized Views

SQL> CREATE OR REPLACE VIEW <view_name> AS SELECT <column_names> from <table_name> ; SQL> create or replace view v2 as 2 select * from sample; View created. SQL> insert into v2 values(1002 , 'sona', '20000'); 1 row created.
ALIAS

Suppose we have three tables (emp , dept , payroll) for emp details TABLE FIELDS
Emp

FOR ( EMP , DEPT , PAYROLL )


Payroll

Dept

EID ENAME EDOB EGENDER EQUAL EMOBILE

EID DNAME DMANAGER DBAY_NO DCONTACT_NO

EID SALRY GRADE BONUS PFNO E_SAL_ACC

SQL> select e.eid, e.ename, e.edob, e.egender, e.equal ,emobile , 2 d.dname, d.dmanager , d.contact_no , 3 p.salary, p.grade , p.bonus , p.pfno as PF 4 from emp e , dept d , payroll p 5 where e.eid=d.eid and d.eid=p.eid; xxxxxxxxxxxxxxxxxxxxxxx

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

If I want to see details of employee ( emp , dept , payroll ) i have to give a long join query. Instead of giving this join query again and again, we can create a view on these tables by using a CREATE VIEW command. SQL> create view v3 AS 2 select e.eid, e.ename, e.edob, e.egender, e.equal , emobile ,

3 d.dname, d.dmanager, d.contact_no , 4 p.salary, p.grade , p.bonus , p.pfno as PF 5 from emp e , dept d , payroll p 6 where e.eid=d.eid and d.eid=p.eid with READ ONLY;
We dont have to give a join query, we can call just simple query as

SQL> select * from v2 We can perform some arithmetic calculation. SQL>Select avg(bonus) from v2; SQL> Select sum(salary) from v2; SQL>Select min(salary) from v2;
CHECK OPTION indicates that Oracle Database prohibits any changes to the

table or view that would produce rows that are not included in the subquery SQL> create view v4 as select e.eid , e.ename , e.edob, e.egender, e.equal , d.dname, d.dmanager , p.esalary, p.egrade , p.ebonus from emp e , dept d , payroll p where e.eid=d.eid and d.eid=p.eid with CHECK OPTION ; View created. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Removing a View

SQL>drop view <view_name> ; SQL>drop view emp_view ; View dropped. Listing Information about VIEWS
Useful_Views Description

DBA_VIEWS/USER_VIEWS DBA_CATALOG

Contains all views in the database Contains VIEWS/INDEX/CLUSTERS/SYNONYMS/SEQUENCES

V$FIXED_VIEW_DEFINATION Contains definition of fixed views To Get VIEW Defination : SQL> select text from DBA_VIEWS where OWNER = '<owner_name>' and VIEW_NAME = <view_name>'; SQL> select text from dba_views where owner='SONY' and VIEW_NAME='V3'; To know which columns are Updatable
SQL>SELECT * FROM USER_UPDATABLE_COLUMNS WHERE TABLE_NAME= XX ;

Whether a view is modifiable, we can check USER_UPDATABLE_COLUMNS.


POINTS TO NOTE (VIEWS)

We can hide certain columns in a table. Views can also be limited to read-only access. View is a virtual Table ; It takes the O/P of a query and treats like a table. A view contains no data. All the data (result) comes from base tables. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

All (DML) operations performed on a view actually affects the base-tables. To create a view in own schema should need (Create View Privilege ) Creating a view in another schema we need (Create Any View Privilege)

If view is( READ ONLY ) cant use DELETE/INSERT/UPDATE commands. The OR REPLACE option is used to create a view that already exists. This option is useful for modifying an existing view without drop.

Cannot REMOVE/MODIFY a row , if the view contains the following , Group Functions such as SUM/MIN/ MAX/AVG A GROUP BY clause. The DISTINCT keyword INLINE VIEW An inline view is basically a query inside another query, which makes it a subquery. i.e. ( SELECT statement inside another SELECT statement) .
IN-LINE VIEWS are commonly used to simplify complex queries by (removing

join operations ) and condense several separate queries into a single query. Example Query for INLINE VIEW :SQL> SELECT * FROM EMP E, 2 ( SELECT DEPT_NO FROM DEPT order by dept_no ) D 3 WHERE E.DEPT_NO = D.DEPT_NO;
INLINE VIEW is a SELECT statement in the FROM clause of another SELECT

statement. INLINE VIEWS are different from views and are not database objects. It exists only during query execution. Because it is temporary. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views


to produce a

An in-line

view

selects data from one or more tables

temporary i.e. ( virtual) table. ( In-line view also one type of sub query). Advantage Better Query Performance and Better Visibility of code. MATERIALIZED VIEWS - (SNAP SHOT) Before starting Materialized View (MV) , let us oracle 8i. SNAPSHOT A Copy of a Table on a Remote Database. "SNAPSHOTS" were redefined as "MATERIALIZED VIEWS " from 8i.
CREATE SNAPSHOT CREATE MATERIALIZED VIEW

CREATE SNAPSHOT LOG

CREATE MATERIALIZED VIEW LOG

DBA_SNAPSHOTS

DBA_MVIEWS

If we create a Snapshot or Materialized View , now Oracle shows " Materialized View created " instead of " Snapshot Created ". Materialized View (MV) A Materialized View is a Oracle Database Object and it contains query results. Materialized Views store data based on Remote Tables (snapshots). A materialized view (MV) is similar to a view but the data is actually stored on disk. Materialized views are just to make a snapshot of the table available on remote system. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

A materialized view provides indirect access to table data by storing the results of a query in a separate schema object. We can define materialized view on BASETABLE/PARTITIONED TABLE/VIEW and can define one or more indexes on the materialized view. It is mostly used in warehouses to increase the speed of queries on very large databases. A materialized view can query tables, views, and other materialized views. Collectively these are called MASTER TABLES - (Replication Term). In replication environments, the materialized views (mv) commonly created. They are Primary key , subquery , materialized views . When we creating materialized view, Oracle creates one internal table and at least one index , and may create one view. Oracle Database uses these objects to maintain the materialized view data. A materialized view (MV) can be stored in base table(s) in the same database or in a different database. If the materialized view will access (remote database objects), we need to start by creating a database link ( DB LINK ) to the remote database. Why use Materialized Views? To increase the speed of queries on very large databases. To reduce network loads.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

To Create Materialized View in Own Schema, Should need CREATE MATERIALIZED VIEW System Privilege. To Create Materialized View in another Users Schema, Should need CREATE ANY MATERIALIZED VIEW System Privilege. Creating Simple Materialized View SQL> CREATE MATERIALIZED VIEW <mv_name> AS SELECT <col_name_1, .. col_name_n> FROM <table_name>; SQL> CREATE MATERIALIZED VIEW mv1 AS SELECT * FROM emp; CREATE MATERIALIZED VIEW mv1 AS SELECT * FROM emp

* ERROR at line 1: ORA-01031: insufficient privileges NOTE : Here , user should need create MATERIALIZED VIEW System Privilege (MV) Granted to rose SQL> grant CREATE MATERIALIZED VIEW to rose; Grant succeeded.

SQL>CREATE MATERIALIZED VIEW mv1 AS SELECT * FROM emp ; CREATE MATERIALIZED VIEW mv1 AS SELECT * FROM emp * ERROR at line 1: ORA-12014 : table 'EMP' does not contain a primary key constraint This error will appear on 10g R2 basic version on 10.2.0.1 - Please upgrade your database to higher version to 10.2.0.5 , If you are getting above error.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

SQL> alter table emp add(constraint pk1 primary key(eid)); Table altered. Trying to create MATERIALIZED VIEW SQL> CREATE MATERIALIZED VIEW mv1 AS SELECT * FROM emp; Materialized view created. Checking USER_MVIEWS SQL> select BUILD_MODE , UPDATABLE from user_mviews;
BUILD_MOD U

IMMEDIATE

SQL> select mview_name, query from user_mviews where owner='ROSE';


MVIEW_NAME QUERY

MV1

SELECT * from emp

Different Kind of Materialized views Oracle offers different kind of materialized views for replication and non replication situations. PRIMARY KEY MATERIALIZED VIEW SUB QUERY MATERIALIZED VIEW ROWID MATERIALIZED VIEW OBJECT MATERIALIZED VIEW COMPLEX MATERIALIZED VIEW In replication environment , commonly created following materialized views. They are PRIMARY KEY , ROWID , SUBQUERY (MVS). Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Types of Materialized Views A M.View can be either READ-ONLY , UPDATABLE, OR WRITEABLE. Users cannot perform data manipulation language (DML) statements on readonly materialized views, but they can perform DML on updatable and writeable Materialized views. There are Three types of Materialized views : Read only Materialized View Updateable Materialized View Writeable Materialized View Refreshing Materialized Views Two (2) types of refresh mode and four (4) types of refresh types. Materialized View Refresh Modes ON COMMIT ON DEMAND (default) Materialized View Refresh Types COMPLETE Refresh Mode When creating a Materialized View , we have to specify the option whether the refresh occurs ON DEMAND or ON COMMIT.
ON COMMIT - When data (transaction) is committed in the master

FAST FORCE (default) NEVER

table , the materialized view gets updated automatically.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

ON DEMAND (default) - To refresh a materialized view need to

execute the package DBMS_MVIEW.REFRESH to update the view.


DBMS_MVIEW Package Provides 3 types of refresh operations.

DBMS_MVIEW.REFRESH | DBMS_MVIEW.REFRESH_ALL_MVIEWS DBMS_MVIEW.REFRESH_DEPENDENT - Refreshing list of MVies or


All Mviews that depend on specified Master table

Oracle recommends ON COMMIT fast refresh rather than ON DEMAND. Refresh Clause for Refresh Types REFRESH PART HAS SOME OPTIONS Following below [ REFRESH [ FAST | COMPLETE | FORCE ] [ ON DEMAND | COMMIT ] [ start with date ] [ next date ] [ with { PRIMARY KEY | ROWID } ]] As I said , Oracle maintains the data in materialized views by refreshing them changes are made to the master tables. Oracle can refresh a M.view can be (incremental) FAST | COMPLETE | FORCE. The refresh option specifies , The refresh method is using to refresh data in Materialized View; Whether the view is Primary key based or Row-id based. The time and interval at which the view is to be refreshed. PRIMARY KEY is the default option.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Refresh Method FAST Clause Fast refresh is most efficient way of maintaining data. When using this method, it brings changed data from master site to local materialized view. All changed informations are maintained in MView LOGS. DIRECT LOADER log or MView logs keeps a record of Changes to the Master table. Syntax FAST Refresh SQL> CREATE MATERIALIZED VIEW <schema.name> PCTFREE <integer> PCTUSED <integer> TABLESPACE <tablespace_name> BUILD IMMEDIATE REFRESH <FAST | FORCE> ON < COMMIT | DEMAND > < USING INDEX | USING NO INDEX > INITRANS <integer> STORAGE CLAUSE AS (<SQL statement>); Example for FAST Refresh SQL> CREATE MATERIALIZED VIEW MVSAMPLE TABLESPACE USERS REFRESH FAST ON COMMIT AS SELECT * from sales; Materialized View LOG Materialized View log should be created for Master Tables. Each Materialized View log is associated with a single master table. Materialized View log resides in the same database. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

The Materialized view log is a schema object that records changes to a master tables data so that a materialized view defined on the master table can be refreshed. Materialized view logs are used to track changes (insert, update and delete to a table. (Mview logs keeps a recoed of changes to the masters tables). Creating a MView LOG As i said , we should create a materialized view log for the master tables if we specify the REFRESH FAST clause. SQL> CREATE MATERIALIZED VIEW LOG on <master_tab_name> SQL> CREATE MATERIALIZED VIEW LOG on sales; Drop MView LOG
DROP MATERIALIZED VIEW LOG statement removes a MView LOG.

SQL> DROP MATERIALIZED VIEW LOG on <master_tab_name> SQL> DROP MATERIALIZED VIEW LOG on sales; In fast refresh , If there is any change in the base table, It requires LOG table. It is known as Mview LOG. The name of the LOG table will be MLOG$_ MLOG$_<table_name> RUPD$_<table_name> RUPD$ <table_name>s is a TEMPORARY UPDATABLE SNAPSHOT log created for Java RepAPI. RUPD$_ is used to support updateable materialized views, which are only possible on log tables with primary keys and obviously used by oracle. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Checking Table details SQL> select * From tab; TNAME TABTYPE CLUSTERID TAB1 TABLE

Creating Materialized View SQL> create materialized view mv1 2 refresh fast on commit as select * from tab1; select * From tab1 * ERROR at line 2 : ORA-23413: table "ROSE"."TAB1" does not have a materialized view log Creating Materialized View LOG SQL> create materialized view log on tab1; Materialized view log created. Again , Creating Materialized View SQL> create materialized view mv1 2 refresh fast on commit as select * from tab1; Materialized view created. Again , Creating Materialized View SQL> select * from tab; TNAME MLOG$_TAB1 RUPD$_TAB1 TAB1 MV1 TABTYPE CLUSTERID TABLE TABLE TABLE TABLE
hang

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Refresh Method COMPLETE Clause The COMPLETE REFRESH re-creates the entire materialized view. This method can be used for small tables. This can be very expensive operation in case of large n of rows. It takes long time to perform. As I said , this method re-creates the entire MView, but we can request to perform fast refresh is possible. From 10g , complete refresh of single materialized view does delete instead of truncate. To force the refresh to do truncate instead of delete, must be set ATOMIC_REFRESH=FALSE if ATOMIC_REFRESH is set to TRUE DELETE (Default)
ATOMIC_REFRESH = TRUE , If a single MView is being COMPLETE REFRESHED, It will be deleted (row-by-row) and whole data will be

inserted. Undo will be generated. If a group of MView is being is COMPLETE REFRESHED then the list of MViews is refreshed in a single transaction. All MViews are updated to a single point in time. If the refresh fails for any of the them , none of the Materialized Views are updated. Example SQL> EXEC DBMS_MVIEW.REFRESH( list => 'mv1' , method => 'c', 2 atomic_refresh => TRUE); list => Mviews that want to refresh. 'F' or 'f' => a fast refresh, 'C' or 'c' => a complete re-fresh, and '?' => a default refresh.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

If ATOMIC_REFRESH is set to FALSE TRUNCATED


ATOMIC_REFRESH = FALSE , If a single materialized view is being

complete refreshed, the materialized view will be truncated. The refresh will go faster, and no undo will be generated. If a group of materialized views are being complete refreshed, each one will be truncated and refreshed individually in a separate transaction.

Replication uses job queues for data refreshes. The number of job queue processes must be set 1 or greater. To get maximum efficiency in
COMPLETE REFRESH then set it's PCTFREE to 0 and PCTUSED to 99.

SQL> EXEC DBMS_MVIEW.REFRESH( list => 'mv1' , method => 'c', 2 atomic_refresh => FALSE); Syntax COMPLETE Refresh SQL> CREATE MATERIALIZED VIEW <schema.name> PCTFREE <integer> PCTUSED <integer> TABLESPACE <tablespace_name> BUILD IMMEDIATE REFRESH <COMPLETE> START WITH <DATE> NEXT <date_calculation> FOR UPDATE AS (<SQL statement>);

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Example for COMPLETE Refresh SQL> CREATE MATERIALIZED VIEW MV2 TABLESPACE USERS REFRESH COMPLETE AS SELECT * from tab1; To Refresh this View SQL> EXEC DBMS_MVIEW.REFRESH(mv2 ,c) Query to Check : SQL> SELECT mview_name, refresh_mode, refresh_method, last_refresh_type, last_refresh_date FROM user_mviews; Refresh Method FORCE Clause
FORCE , the materialized view will attempt fast refresh. If fast refresh is not

possible , then oracle performs complete refresh. If we do not specify a refresh method ( FAST, COMPLETE, or FORCE ), FORCE is the default. Syntax FORCE Refresh SQL> CREATE MATERIALIZED VIEW <schema.name> PCTFREE <integer> PCTUSED <integer> TABLESPACE <tablespace_name> BUILD IMMEDIATE REFRESH <FORCE> ON <COMMIT | DEMAND > AS (<SQL statement>);
Determines if a FAST refresh is possible, otherwise performs a COMPLETE refresh.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Example for FORCE Refresh SQL> CREATE MATERIALIZED VIEW MV3 REFRESH FORCE as select * from tab3; To Refresh SQL> EXEC DBMS_MVIEW.REFRESH ( LIST =>MV3); SQL> EXEC DBMS_MVIEW.REFRESH ( LIST =>MV3 , METHOD => ? ); Query to Check : SQL> SELECT mview_name, refresh_mode, refresh_method, last_refresh_type, last_refresh_date FROM user_mviews; Materialized view refresh is slow Why ? Check the size of MView log. It should be truncated after every refresh. Check the network connectivity using ping command and should able to see no time gap between packets transfer. Check the size of original table. if MView log size is more than original table, then its clear that problem is with MView log. Additional Parameters for Materialized Views Primary Key and rowId Clause
WITH PRIMARY KEY is used to create a primary key materialized view. The MView is based on the Primary key of the master table instead of ROWID. PRIMARY KEY is the default option. To use the PRIMARY KEY clause should

have defined PRIMARY KEY on the master table. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

A ROWID MView is based on the Physical row identifiers (rowids) of the rows in a master. ROWID MViews based on single table that do not have a Primary key. ROWID MViews cannot contain following options , DISTINCT or AGGREGATE FUNCTIONS and SET OPERATIONS GROUP BY or CONNECT BY CLAUSES SUBQUERIES , JOINS but PRIMARY KEY option does allow DISTINCT and AGGREGATE FUNCTIONS, as well as GROUP BY, JOINS, and SET OPERATORS. Rowid MViews are not eligible for fast refresh after a master table reorganization until a complete refresh has been performed. Timing the Refresh
START WIH Clause

A Datetime Expression for first automatic refresh time.


START WIH Clause

A Datetime Expression for interval between automatic refreshes. If we specify ON COMMIT or ON DEMAND , we cannot specify START
WITH Clause or NEXT Clause. START WITH clause tells the database when to perform the first replication

from the master table. It should evaluate to a future point in time. If we specify a START WITH value but omit the NEXT value, then the database refreshes the MView only once. The NEXT CLAUSE specifies the interval between refreshes. START WITH [NEXT] <date> - Refreshes start at a specified date/time and continue at regular intervals. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Examples for START WITH Clause and NEXT Clause SQL> CREATE MATERIALIZED VIEW MY_VIEW REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 2 AS SELECT * FROM <table_name>; The first copy of the MView is made at SYSDATE (immediately) and next refresh has to be performed is every two days. (NEXT SYSDATE +2) Example for Every two mins SQL> CREATE MATERIALIZED VIEW MY_VIEW REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 2 / (24*60) AS SELECT * FROM <table_name>; Example for Every 30 Seconds SQL> CREATE MATERIALIZED VIEW MY_VIEW REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 30/(24*60*60) AS SELECT * FROM <table_name>; Using Index Clause
USING INDEX clause can be used to specify the storage clause for index that

will be created on MView. If USING INDEX is not specified, then default values are used for the index. Oracle uses the default index to speed up incremental (FAST) refresh of the materialized view. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Using No - Index Clause


USING NO INDEX

prevents the creation of the DEFAULT INDEX and also

cannot specify storage clause and tablespace clause. we can create an alternative index explicitly by using the CREATE INDEX Statement. Build Option The build_clause specifies when to populate the MView

Build IMMEDIATE - (Default)


IMMEDIATE indicates that the MView is to be populated immediately. DEFERRED DEFERRED indicates that the MView is to be populated by the

next

REFRESH operation. The first (deferred) refresh must always be a complete refresh. Tablespace <ts_name>
MView will be created in Specified tablespace. If we omit this clause, then

Oracle Database creates the MView in the default tablespace of the schema. Query Rewrite Clause
QUERY REWRITE Clause specifies whether the MView is eligible to be used

for Query rewrite. Query rewrite is disabled by default, so must specify this clause to make materialized views eligible for QUERY REWRITE. One of the advantages of query rewrite clause is our queries will automatically start using it (like index) without doing any changes. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Why we need Query Rewrite When base tables contain large amount of data, it is an expensive and time consuming process to compute the required aggregates or compute joins between these tables In such cases, queries can take minutes or even hours to return the answer , because MView contain already pre-computed aggregates and joins, so Oracle suggests an extremely powerful process called query rewrite to get quickly answer. What is Query Rewrite One of the Major benefits of creating and maintaining MViews is the ability to take advantage of Query rewrite. If we issue a SQL statement with complex calculation and aggregation to base table. In such case to get faster result Optimizer will "rewrite" our statement and build an execution plan that will use MView , instead of base table. That is Query rewrite. A Materialized View is enabled for query rewrite, then .. Cannot include CURRENT_TIME/SYSDATE/USER ; SQL> create materialized view mview1 enable QUERY REWRITE 2 as select no , name , sysdate from tab2; as select no , name , sysdate from tab2 * ERROR at line 2: ORA-30353: expression not supported for query rewrite When does oracle rewrite a Query ? A query is rewritten only when a certain number of conditions are met: Query rewrite must be enabled for the session. A MView must be enabled for Query rewrite.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Query Rewrite requires following Parameters OPTIMIZER_MODE=ALL_ROWS (default) , FIRST_ROWS , CHOOSE JOB_QUEUE_INTERVAL=3000 JOB_QUEUE_PROCESSES= 1 or > 1 QUERY_REWRITE_ENABLED = true QUERY_REWRITE_INTEGRITY= ENFORCED COMPATIBLE = atleast 8.1.5.0 The QUERY_REWRITE_INTEGRITY parameter is optional, but must be set to (stale_tolerated, trusted, or enforced ) if it is specified. How Oracle Rewrites Query :Query rewrite is available with CBO (Cost-Based Optimization). The Optimizer uses different methods to rewrite a query. When creating a MView , We can verify what types of Query rewrite are possible by calling following procedures. DBMS_MVIEW.EXPLAIN_MVIEW DBMS_ADVISOR.TUNE_MVIEW Once the MView has created , use DBMS_MVIEW.EXPLAIN_REWRITE to find out if (or why not) it will rewrite a specific query. i.e. we need to be careful in some cases Query rewrite is not possible. Query Rewrite Restrictions Query rewrite is not possible with all MViews. If query rewrite is not occurring
DBMS_MVIEW.EXPLAIN_REWRITE provides why a specific query is not

eligible for rewrite clause. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Why a specific query is not eligible for rewrite clause. SQL> alter session set query_rewrite_enabled=false; Session altered. SQL> exec dbms_mview.explain_rewrite('select * from emp','M1'); PL/SQL procedure successfully completed. SQL> SELECT message FROM rewrite_table ORDER BY sequence; MESSAGE QSM-01150: query did not rewrite QSM-01001: query rewrite not enabled

A MView definition includes any number of aggregations (SUM, COUNT(x), COUNT(*), COUNT(DISTINCT x), AVG, VARIANCE, STDDEV, MIN, and MAX). It can also include any number of joins. Query undergoes to several check Whether the Query rewrite is possible or not - (Already discussed)
Mview should have sufficient data to answer the query.

Generate Plan

Compare Plan Cost and Pick the best

Query Result Query is rewritten Generate Plan

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Cost Based Optimization Query rewrite is available with CBO. When a query is rewritten , Oracle's CBO compares the cost of the and original query and rewritten query then CBO chooses the cheaper execution plan. The optimizer uses two different methods to recognize when to rewrite a query. Two (2) types of Query rewrite methods are .. TEXT MATCH REWRITE and GENERAL QUERY REWRITE If the TEXT MATCH REWRITE method fails, the optimizer uses the more General method for query rewrite clause.. Text - match Rewrite most simple rewrite mechanism is the text match rewrite. The Query rewrite engine uses two text match methods. They are , FULL / PARTIAL - TEXT MATCH REWRITE The first method (FULL TEXT MATCH) the entire SQL text of the query is compared the entire text of the MView definition.(i.e. entire SELECT expressionn ignoring whit spaces.). When full text match fails, The Optimizer then attempts a PARTIAL TEXT MATCH. In this method (second) Text starting with the FROM clause of a query is compared against the text starting with the FROM clause of a MView definition . General Query Rewrite When TEXT match rewrite fails , the optimizer uses the more General

method. which it compares joins, selections, data columns, grouping columns, and aggregate functions between the query and MViews. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Aggregations and Transformations Materialized views can be used to improve the performance of a variety of queries, including those performing aggregations and transformations. Explain Plan before M.View Creation ; SQL> set timing on; SQL> set autotrace on explain;

Create a materialized view to perform the aggregation in advance, making sure to specify the ENABLE QUERY REWRITE clause.

USER is "SYS" SQL>alter system set query_rewrite_enabled='TRUE' scope=SPFILE; SQL> Grant query rewrite to rose; SQL> @$ORACLE_HOME/rdbms/admin/utlxrw.sql; Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Creating Materialized View with Query Rewrite clause

Here , the aggregation takes 00:055 seconds . The very same statement now takes way less time! Why is that so ? Why Query results takes less time ? Many queries will take less time the second time running them. After the first execution there may be many, or even all, of the rows in the buffer cache. Then the second run will not do any, or as much physical IO but will get the data from the buffer cache. SQL> ALTER SESSION SET OPTIMIZER_MODE = FIRST_ROWS; SQL> alter session set query_rewrite_enabled=true; SQL> execute dbms_stats.gather_table_stats ('user_name', 'mv_name); Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Following init parameters should be set query_rewrite_enabled = True query_rewrite_integrity = enforced|trusted|stale_tolerated SQL>ALTER SESSION SET QUERY_REWRITE_INTEGRITY = TRUSTED; SQL> SELECT name, value FROM gv$parameter WHERE 2 name LIKE '%rewrite%'; The same query is now rewritten to take advantage of the pre-aggregated data in the MView, instead of the session doing the work for itself. SQL> set autotrace on; SQL> select count(*), sum(quan_sold), sum(amt_sold) from sales;
COUNT(*) SUM(QUAN_SOLD) SUM(AMT_SOLD)

6000000 Execution Plan

12000000

720480000

Elapsed: 00:00:00.03 Plan hash value: 2958490228 -------------------------------------------------------------------------------------------------| Id | Operation | Name|Rows |Bytes| Cost (CPU)| Time ------------------------------------------------------------------------------------------------0| SELECT STATEMENT | | 1 | 40 | 3 (0) | 00:00 :01

1| MAT_VIEW REWRITE ACCESS FULL | MV1 | 1 | 40 | 3 (0) | 00:00 :01 Need to execute the utlxrw.sql script to create table REWRITE_TABLE before executing
DBMS_ADVISOR.TUNE_MVIEW. Be sure all required privileges

before executing Query Rewrite clause. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Uses of Materialized Views Straight forward and is answered in a single word Performance Faster Response Less Writes Less Physical Reads Decreased CPU consumption Avoiding network i/o Useful Views dba_mviews dba_base_table_mviews dba_mview_comments dba_mview_detail_relations dba_mview_joins dba_mview_keys dba_mview_logs dba_mview_refresh_times dba_tune_mview To know last refresh happened on MViews SQL> select MVIEW_NAME, to_char(LAST_REFRESH_DATE,'YYYY-MM-DD HH24:MI:SS') from dba_mviews; SQL> select NAME, to_char(LAST_REFRESH,'YYYY-MM-DD HH24:MI:SS') from dba_mview_refresh_times; ** dba_mview_analysis ** we can check here also. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Materialized View Options Read - Only Materialized Views Updateable Materialized Views Writeable Materialized Views A MView can be either read-only, updatable, or writeable. Users cannot perform data manipulation language (DML) statements on read-only

MViews, but they can perform DML on UPDATABLE and WRITEABLE MViews.

A MView can be READ-ONLY during creation by omitting the FOR UPDATE clause. Updatable materialized views enable you to decrease the load on master sites because users can make changes to the data at the MView site. SQL> create materialized view LOCALMV 2 refresh force start with SysDate next SysDate + 7 3 for update as select * from BOOKSHELF@REMOTE_CONNECT; Read-Only : This type of MVs cannot send data back to the server Master tables. These server only one way communication i.e. from server to the client. Updatable : MView can send the data, changed locally, back to the server. Primary key Materialized View using DBLINK SQL> CREATE MATERIALIZED VIEW MVIEW1 REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 1/48 WITH PRIMARY KEY AS SELECT * FROM <table_name>@remote_dblink; Primary key MViews are the default type of materialized views in Oracle. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

SQL> show user; USER is "SYS" SQL> grant connect ,resource to rose identified by rose; Grant succeeded. SQL> grant create database link , create materialized view to rose; Grant succeeded.

SQL> show user; USER is "ROSE" SQL> create database link link1 connect to 2 sam identified by sam 3 using 'orclprod'; tns alias Database link created. SQL> select DB_LINK , USERNAME , CREATED from user_db_links;
DB_LINK USERNAME CREATED

LINK1.REGRESS.RDBMS.DEV.US.ORACLE.COM SAM

05-JUN-13

USER is "ROSE" SQL> create materialized view mv1 2 refresh fast start with sysdate 3 next sysdate + 1/48 4 with primary key as 5 select * from sam.emp1@link1; remote db link name Materialized view created.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

SQL> select * from sam.tab1@link1;


NO NAME CITY

** **

***** *****

******** ********

QUERY REWRITE CLAUSE MATERIALIZED VIEW

SQL> create materialized view emp_mv build immediate refresh FORCE ON DEMAND ENABLE QUERY REWRITE as select deptno, sum(sal) as sal_by_dept from emp group by deptno;
ROWID MATERIALIZED VIEW

Specify WITH ROWID to create a rowid materialized view. Rowid materialized views must be based on a single table. Rowid MViews are not eligible for fast refresh after a master table reorganization until a complete refresh has been performed. SQL> CREATE MATERIALIZED VIEW mv_rowid REFRESH WITH ROWID AS SELECT * FROM emp@remote_dblink; A ROWID MViews is based on the physical row identifiers (rowids) of the rows in a master. ROWID MViews cannot contain , DISTINCT OR AGGREGATE FUNCTIONS GROUP BY SUBQUERIES, JOINS AND SET OPERATIONS Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Primary key and Rowid Clause


WITH PRIMARY KEY is used to create a primary key materialized view i.e. the MView is based on the primary key of the master table instead of ROWID (for

ROWID clause). PRIMARY KEY is the default option. PRIMARY KEY clause you should have defined PRIMARY KEY on the master table or else should use ROWID based materialized views.
SUB QUERY MATERIALIZED VIEW

SQL> CREATE MATERIALIZED VIEW mv_empdept AS SELECT * FROM emp@remote_db e WHERE EXISTS ( SELECT * FROM dept@remote_db d WHERE e.dept_no = d.dept_no); When we create the MView, Oracle Database executes this subquery and places the results in the MVie. This subquery is any valid SQL sub query.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Materialized View Recall Master tables are the Base for Materialized Views. The From clause of the query in M.view , can tables, views and other materialized views). This objects are called as Master Tables in Replication Term. Which databases containing master tables are called Master databases. Materialized Views are required mainly for summarize, compute , replicate and distribute data. Summarizing the data in the table. Replication of data from one location (database) to another location (database).When we are replicating the table from remote location to local location- our queries can access the same data from location location. IN OLTP env, purpose of the MV is to increase query execution performance A materialized view definition can include aggregation, such as SUM MIN, MAX, AVG, COUNT(*), COUNT(x), COUNT(DISTINCT), VARIANCE or STDDEV, one or more tables joined together COST BASED optimization can use materialized views to improve query

performance. The optimizer transparently rewrites the request to use materialized view. Queries are directed to materialized view and not to underlying detail tables. In replication environments, the materialized views commonly created are primary key, rowid, object, and subquery materialized views.
REFRESH : ON DEMAND CLAUSE

DBA need to schedule a job , which will do the refresh of MView periodically. In this clause , Mview will be refreshed by calling DBMS_MVIEW procedure.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

REFRESH : ON COMMIT CLAUSE

When commit happens every time , MView gets updated which is going to take a time because the database performs the refresh operation as part of commit process.
NOTE : If we specify ON COMMIT or ON DEMAND then cant specify START WITH or NEXT.

Some companies use fast refresh materialized views on remote databases in order to improve performance and security when using distributed computing for online transaction processing. Materialized views are similar to indexes in several ways: They consume storage space. They must be refreshed when the data in their master tables changes. They improve the performance of SQL execution when they are used for query rewrites. Their existence is transparent to SQL applications and users. Materialized views can be accessed directly using a SELECT statement. Depending on the types of refresh that are required, they can also be accessed directly in an INSERT, UPDATE, or DELETE statement. We can define a materialized view on a partitioned table and one or more indexes on the materialized view. DBMS_MVIEW.EXPLAIN_MVIEW and DBMS_ADVISOR.TUNE_MVIEW provide insight and advice on materialized views. While these features can help to get an optimal materialized view. Query rewrite is the process of modifying a query to use the view rather than the base table. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

Optimizer rewrites the queries in order to utilize materialized views.


(The

users don't even know the MV exists , they just write their queries against

the base tables. Then, Oracle can rewrite those queries to get the data from any available MVs when that is possible. The users aren't querying the MVs; they are querying the base tables like they always do.)
GLOBAL_QUERY_REWRITE and QUERY_REWRITE system privileges allows

user to enable materialized views. There are two relevant parameters need to set in order for Query Rewrite QUERY_REWRITE_ENABLED QUERY_REWRITE_INTEGRITY
QUERY_REWRITE_ENABLED :

Unless the value of this parameter is set to TRUE , Query rewrites will not take place FALSE (default).
QUERY_REWRITE_INTEGRITY

This parameter controls how Oracle rewrites queries. It has three(3) values. ENFORCED | TRUSTED | STALE TOLERATED By default, the integrity level is set to ENFORCED. In this mode, all

constraints must be validated. Queries will be rewritten using only constraints and rules that are enforced and guaranteed by Oracle.
STALE TOLERATED : In this mode , the optimizer uses materialized views

that are valid but contains FRESH data as well as stale data (out - of- sync with the details). This mode offers the maximum rewrite capability but Slightly out-of-sync answer is acceptable. Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

10g

Views Vs Materialized Views

TRUSTED - Queries will be rewritten using the constraints that are enforced by

Oracle, as well as any relationships existing in the data that we have told oracle about, but are not enforced by the database.

SQL> alter session set query_rewrite_enabled=true; SQL> alter session set query_rewrite_integrity=enforced; Views Vs Materialized Views View is a virtual table , doesnt require storage. Materialized views are schema objects with storage. Views can be useful to simplify the SQL statements Cant implement constraints/triggers/indexes on the views and can be indexed and partitioned. Views can be used to security by restricting access to predetermined set of rows or columns. Materialized views generally used in Dataware housing applications or reporting purpose where performance is a major concern. Views are derived from base tables. We can define a materialized view on a base table , partitioned table or view.

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu