Presentation is loading. Please wait.

Presentation is loading. Please wait.

Materialized Views.

Similar presentations


Presentation on theme: "Materialized Views."— Presentation transcript:

1 Materialized Views

2 Oracle Database 10g: Implement and Administer a Data Warehouse 9-2
Objectives After completing this lesson, you should be able to do the following: Describe how summaries can be used to improve performance Differentiate materialized view types Explain materialized view integrity Create a materialized view List globalization implications for materialized views Oracle Database 10g: Implement and Administer a Data Warehouse 9-2

3 The Need for Summary Management
How can you improve query response time? Use indexes. Partition your data. Implement parallel execution. What about precomputing query results? Create summaries: Materialized views Automatically rewrite SQL applications. Automatically refresh data. The Need for Summary Management There are many well-known techniques you can use to increase query performance. For example, you can create additional indexes, or you can partition your data. Many data warehouses also use a technique called summaries. The basic process for a summary is to precompute the result of a long-running query and store this result in a database table called a summary table, which is comparable to a CREATE TABLE AS SELECT (CTAS) statement. Instead of precomputing the same query result many times, the user can directly access the summary table. Although this approach has the benefit of enhancing query response time, it also has many drawbacks. The user needs to be aware of the summary table’s existence in order to rewrite the query to use that table instead. Also, the data contained in a summary table is frozen, and must be manually refreshed whenever modifications occur on the real tables. With Oracle Database summary management, the end user no longer has to be aware of the summaries that have been defined. The DBA creates materialized views that are automatically used by the system when rewriting SQL queries. Using materialized views offers another advantage over manually creating summaries tables, in that the data can be refreshed automatically. Oracle Database 10g: Implement and Administer a Data Warehouse 9-3

4 Oracle Database 10g: Implement and Administer a Data Warehouse 9-4
The Need for Summary Management (continued) Note: The term summary comes from the fact that most of the time users in data warehouse environments compute expensive joins with aggregations. When creating summaries using materialized views in Oracle Database, you are not required to use joins or aggregations. Full Notes Page Oracle Database 10g: Implement and Administer a Data Warehouse 9-4

5 Using Summaries to Improve Performance
Special types of aggregate views Improve query execution time by precalculating expensive joins and aggregation operations before execution and storing results in a database table Created using a schema object called a materialized view Using Summaries to Improve Performance Summaries are aggregate views that are created to improve query execution times. When you use a summary, the results of joins and aggregate operations are calculated before query execution and stored in a database table. In an Oracle database, summaries are implemented with a materialized view. Oracle Database 10g: Implement and Administer a Data Warehouse 9-5

6 Oracle Database 10g: Implement and Administer a Data Warehouse 9-6
Using Summaries Original query by user: DBA creates summary table: New query by user using summary table: SELECT c.cust_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_id; CREATE TABLE cust_sales_sum AS SELECT c.cust_id, SUM(amount_sold) AS amount FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_id; Using Summaries Before the introduction of materialized views in Oracle Database, organizations using summaries spent a significant amount of time creating summaries manually. They had to identify which summaries to create, index the summaries, update them, and advise their users on which ones to use. In the example in the slide, the DBA creates a summary table called CUST_SALES_SUM, to improve the performance of the initial query shown. The DBA informs the users of its existence, and users then query the summary table rather than executing the original query. The time required to execute the SQL query by using the summary table is minimal compared to the original SQL query. However, users must be made aware of summary tables, and they need to rewrite their applications to use them. In addition, the DBA must manually refresh the summary tables to keep them up-to-date with the corresponding original tables. SELECT * FROM cust_sales_sum; Oracle Database 10g: Implement and Administer a Data Warehouse 9-6

7 Using Materialized Views for Summary Management
DBA creates materialized view: User issues original query: Query is rewritten by the Oracle server: CREATE MATERIALIZED VIEW cust_sales_mv ENABLE QUERY REWRITE AS SELECT c.cust_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_id; SELECT c.cust_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_id; Using Materialized Views for Summary Management Summary management in Oracle Database eases the workload of the database administrator and eliminates the need for end users to be aware of the summaries that have been defined. The database administrator creates one or more materialized views, which are the equivalent of summary tables. The advantage of using a materialized view rather than a CTAS is that a materialized view not only materializes the result of a query into a database table, but also generates metadata information used by the query rewrite engine to automatically rewrite the SQL query to use the summary tables. Materialized views within the data warehouse are transparent to the end user and the database application. Also, a materialized view optionally offers another important possibility: refreshing data automatically. In the slide example, the user is able to execute the original query after the DBA created the materialized view called CUST_SALES_MV. Whenever the user or application executes the SQL query, Oracle Database transparently rewrites it to use the materialized view. The query response time is the same as the CTAS approach, but the application need not be rewritten. The rewrite phase is automatically handled by the system. Also, the SQL statement that defines the materialized view does not have to match the SQL statement of the query itself. SELECT * FROM cust_sales_mv; Oracle Database 10g: Implement and Administer a Data Warehouse 9-7

8 Using Materialized Views for Summary Management
1 DBA creates materialized view. 2 End user queries tables and views. 3 Using Materialized Views for Summary Management (continued) In a typical use of summary management, the database administrator creates the materialized view. When the end user queries tables and views, the Oracle server’s query rewrite mechanism automatically rewrites the SQL query to use the summary table. The use of the materialized view is transparent to the end user or application querying the data. Oracle server rewrites SQL query to use materialized view. Oracle Database 10g: Implement and Administer a Data Warehouse 9-8

9 Summary Management Components
Mechanisms to define materialized views and dimensions Refresh mechanism to ensure that materialized views contain the latest data Query rewrite capability to transparently rewrite a query to use a materialized view SQL Access Advisor: Recommends materialized views and indexes to be created DBMS_ADVISOR.TUNE_MVIEW procedure: Shows you how to make your materialized view fast refreshable and use general query rewrite Summary Management Components The implementation of summary management in Oracle Database includes the use of the components listed in the slide. Oracle Database 10g: Implement and Administer a Data Warehouse 9-9

10 Using Summary Management
1. Use the SQL Access Advisor to determine how you will use materialized views. 2. Create materialized views and design how queries will be rewritten. 3. Use DBMS_ADVISOR.TUNE_MVIEW to obtain an optimized materialized view as necessary. Using Summary Management After your data has been transformed, staged, and loaded into the detail tables, you invoke the summary management process as described in the slide. Note: The SQL Access Advisor is discussed in detail in the lesson titled “Using the SQL Access Advisor” in this course. You can also learn more about DBMS_ADVISOR.TUNE_MVIEW in that lesson. Oracle Database 10g: Implement and Administer a Data Warehouse

11 How Many Materialized Views?
Query rewrite chooses which materialized view to use. One materialized view per query: Ideal for query performance Consumes too much disk space Not recommended One materialized view for multiple queries: One materialized view can be used to satisfy multiple queries Less disk space needed Less time needed to maintain materialized views How Many Materialized Views? If you decide to use summaries in your data warehouse, then an important question needs to be answered: How many materialized views should you create? The query optimizer automatically recognizes when an existing materialized view can and should be used to satisfy a request. It then transparently rewrites the request to use the materialized view. Queries go directly to the materialized view and not to the underlying detail tables. In general, rewriting queries to use materialized views rather than detail tables improves query response time. You need to determine which materialized views you should create. One possible scenario is to create a materialized view for each expected SQL query. Although this would be ideal for query response time, this technique is not recommended because you would need a lot of disk space to store the materialized views and time would be required to create and maintain them. When using query rewrite, create materialized views that satisfy the largest number of queries. Some examples follow on the next few pages. Oracle Database 10g: Implement and Administer a Data Warehouse

12 One Materialized View for Multiple Queries
CREATE MATERIALIZED VIEW cust_sales_mv2 ENABLE QUERY REWRITE AS SELECT cust_last_name, channel_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_last_name, s.channel_id; SELECT * FROM cust_sales_mv2; Query rewrite SELECT cust_last_name, channel_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_last_name, s.channel_id; One Materialized View for Multiple Queries This is one of the simplest examples. A materialized view called CUST_SALES_MV2 is created. The application executes exactly the same query as the one used to create the materialized view. During query rewrite, Oracle Database replaces the application’s query by a simple SELECT * FROM CUST_SALES_MV2 statement. Oracle Database 10g: Implement and Administer a Data Warehouse

13 One Materialized View for Multiple Queries
CREATE MATERIALIZED VIEW cust_sales_mv2 ENABLE QUERY REWRITE AS SELECT cust_last_name, channel_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_last_name, s.channel_id; SELECT cust_last_name, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY cust_last_name; SELECT cust_last_name, SUM(amount) FROM cust_sales_mv2 GROUP BY cust_id; One Materialized View for Multiple Queries (continued) The example in this slide uses the same materialized view as used in the previous example. The difference in this scenario is that the application query is not exactly the same as the query defining the materialized view. Note that the GROUP BY clauses are different. The application query groups data only by CUST_ID, whereas the materialized view groups data by CUST_ID and CHANNEL_ID. This means that the same customer can appear multiple times in the materialized view: one time for each different channel. The data requested by the application’s query can be computed by using the data stored in the materialized view. The example given in the slide explains one possible way to rewrite the application’s query by using the materialized view. Query rewrite Oracle Database 10g: Implement and Administer a Data Warehouse

14 One Materialized View for Multiple Queries
CREATE MATERIALIZED VIEW cust_sales_mv2 ENABLE QUERY REWRITE AS SELECT cust_last_name, channel_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_last_name, s.channel_id; SELECT channel_id, SUM(amount_sold) FROM sales GROUP BY channel_id; SELECT channel_id, SUM(amount) FROM cust_sales_mv2 GROUP BY channel_id; One Materialized View for Multiple Queries (continued) This example uses the same materialized view as the one created in the previous examples. This example is a bit more complex. Not only are the GROUP BY clauses different, but also the query of the application does not join the SALES table to the CUSTOMERS table. In this scenario, rewriting the query is possible only when there is a referential integrity constraint between SALES and CUSTOMERS that denotes an exact 1-to-N join relationship and a NOT NULL constraint on the CUST_ID column in the SALES table, avoiding the case where there would be a sales entry with no corresponding customers. In that case, the sales entry would not be stored in CUST_SALES_MV2, and the rewrite might have missed that row. Query rewrite Oracle Database 10g: Implement and Administer a Data Warehouse

15 Determining Which Materialized View to Create
One materialized view can be used to satisfy multiple queries. Multiple materialized views can satisfy the same query. A balance between performance and space usage must be found. Which materialized view should you create? Analyze your workload. Use the SQL Access Advisor. Use DBMS_MVIEW.EXPLAIN_REWRITE to see why a materialized view is used or ignored. Determining Which Materialized View to Create On the previous page, you learned that query rewrite can use the same materialized view to satisfy different queries. Conversely, different materialized views can satisfy one particular query. It may be difficult to identify the best materialized view to create given a set of queries. As a DBA, you must find a balance between query performance and disk space used to store the materialized views. You can use the SQL Access Advisor to determine the proper set of materialized views, materialized view logs, and indexes for a given workload. The SQL Access Advisor is discussed in detail in the lesson titled “Using SQL Access Advisor.” The DBMS_MVIEW.EXPLAIN_REWRITE procedure can also be used to learn more about what materialized views will be used or ignored in order to resolve a SQL query. This procedure is discussed in detail in the lesson titled “Refreshing Materialized Views.” Oracle Database 10g: Implement and Administer a Data Warehouse

16 Types of Materialized Views
Materialized views with aggregates: Materialized views containing only joins: CREATE MATERIALIZED VIEW cust_sales_mv AS ENABLE QUERY REWRITE AS SELECT c.cust_id, s.channel_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_id, s.channel_id; CREATE MATERIALIZED VIEW sales_products_mv AS ENABLE QUERY REWRITE AS SELECT s.time_id, p.prod_name FROM sales s, products p WHERE s.prod_id = p.prod_id(+); Types of Materialized Views The SELECT clause in the materialized view creation statement defines the data that the materialized view must contain. Only a few restrictions limit what can be specified. Any number of tables can be joined together. However, they cannot be remote tables if you want to take advantage of query rewrite. Besides tables, other elements such as views, inline views (subqueries in the FROM clause of a SELECT statement), subqueries in the WHERE clause, and materialized views can all be joined or referenced in the SELECT clause. In data warehouses, materialized views normally contain aggregates. This is the origin of the term summaries in data warehouses. Some materialized views contain only joins and no aggregates. The advantage of creating this type of materialized view is that expensive joins are precalculated. As explained later in this course, the distinction made between the types of materialized views is useful for describing capabilities and restrictions of materialized views regarding refresh and query rewrite. Oracle Database 10g: Implement and Administer a Data Warehouse

17 The Need for Nested Materialized Views
Typical data warehouse need: Create aggregate materialized views using different grouping columns on a single join. Maintaining the materialized views is time consuming because the underlying join is performed multiple times. SALES_TIME_PROD_MV SALES_PROD_TIME_MV SALES SALES The Need for Nested Materialized Views In a data warehouse, you typically create many aggregate materialized views on a single join. The diagram in the slide illustrates this situation with two materialized views created on the same join, while using different grouping columns. Incrementally, maintaining these distinct materialized aggregate views can take a long time, because the underlying join has to be performed many times. PRODUCTS TIMES PRODUCTS TIMES Same tables joined Different grouping columns Oracle Database 10g: Implement and Administer a Data Warehouse

18 Using Nested Materialized Views
Definition is based on another materialized view. Definition can also reference normal tables. SALES_TIME_PROD_MV SALES_PROD_TIME_MV SALES_PROD_TIME_JOIN Using Nested Materialized Views A nested materialized view is a materialized view whose definition is based on another materialized view. A nested materialized view can reference other relations in the database in addition to referencing materialized views. Contrast the diagram in this slide with the one in the previous slide illustrating the use of multiple materialized views. By using nested materialized views as shown in this slide, the join is performed just once. Incremental maintenance of single-table aggregate materialized views is very fast due to various refresh optimizations on this class of views. Note: Nested materialized views incur the space overhead of materializing the join and having a materialized view log in case of fast refresh. In contrast, using multiple non-nested materialized views does not have space requirements for the materialized view and its log, but they have relatively long refresh times due to multiple computations of the same join. Tables are joined one time. SALES PRODUCTS TIMES Oracle Database 10g: Implement and Administer a Data Warehouse

19 Nested Materialized Views: Restrictions
A nested materialized view cannot be a parent and a grandparent as shown: SALES_TIME_PROD_SUM Grandparent of PRODUCTS Parent of PRODUCTS SALES_TIMES_JOIN SALES TIMES PRODUCTS Nested Materialized Views: Restrictions Some restrictions exist on the way in which you can nest materialized views. You can nest a materialized view only if all the immediate dependencies of the materialized view do not have any dependencies among themselves. Thus, in the dependency tree, a materialized view can never be a parent as well as a grandparent of an object. The diagram in the slide illustrates an impermissible nested materialized view because SALES_TIME_PROD_SUM is both a parent and grandparent of the PRODUCTS table. Oracle Database 10g: Implement and Administer a Data Warehouse

20 Materialized View: Example
CREATE MATERIALIZED VIEW cust_sales_mv PCTFREE 0 TABLESPACE example STORAGE (INITIAL 1M NEXT 1M PCTINCREASE 0) BUILD DEFERRED REFRESH COMPLETE ENABLE QUERY REWRITE AS SELECT c.cust_id, s.channel_id, SUM(amount_sold) FROM sales s, customers c WHERE s.cust_id = c.cust_id GROUP BY c.cust_id, s.channel_id ORDER BY c.cust_id, s.channel_id; Name Storage options When to build it How to refresh the data Use this for query rewrite Detail query Detail tables Materialized View: Example For a complete description of the CREATE MATERIALIZED VIEW statement, refer to the Oracle Database SQL Reference guide. Unless the materialized view is based on a user-defined prebuilt table, it requires and occupies storage space in the database. Although query rewrite is enabled by default globally for the database, you must specify the ENABLE QUERY REWRITE clause if the materialized view is to be considered available for rewriting queries. This can be altered later using the ALTER MATERIALIZED VIEW statement. Note that you can enable query rewrite only if all user-defined PL/SQL functions in the materialized view are DETERMINISTIC. You can specify an ORDER BY clause in the CREATE MATERIALIZED VIEW statement. It is used only during the initial creation of the materialized view and is not considered part of the materialized view definition. Storing rows in a specified order may help query performance because it provides physical clustering of the data that is very useful when using indexes. MV keys Oracle Database 10g: Implement and Administer a Data Warehouse

21 Materialized Views Storage
When a materialized view is created, the following objects are created: A container table to store the materialized view rows The materialized view itself One index for materialized views with aggregates only The OBJECT_TYPE column of DBA_OBJECTS contains MATERIALIZED VIEW for the object. The container table has the same name as the materialized view object. A container table can be prebuilt. Materialized Views Storage When a materialized view is created, the following objects are created: A container table to store the materialized view rows The materialized view definition (At most) one index for materialized views with aggregates Note: Prebuilt tables are described later in this lesson. Oracle Database 10g: Implement and Administer a Data Warehouse

22 Estimating Materialized View Size
Statement ID for EXPLAIN PLAN > VARIABLE num_rows NUMBER; > VARIABLE mv_size NUMBER; EXEC DBMS_MVIEW.ESTIMATE_MVIEW_SIZE( 'simple_store', 'SELECT c.cust_state_province, ' ||- ' SUM(amount_sold) ' ||- 'FROM sales s, customers c ' ||- 'WHERE s.cust_id= c.cust_id ' ||- 'GROUP BY c.cust_state_province', :num_rows, :mv_size); Estimating Materialized View Size A materialized view occupies storage space in the database, so it is helpful to know how much space will be required before it is created. Rather than guess or wait until it has been created and then discover that insufficient space is available in the tablespace, use the DBMS_MVIEW.ESTIMATE_MVIEW_SIZE procedure. When you invoke this procedure, an estimate of the size in number of rows and bytes for the materialized view is returned. Estimated storage in bytes Estimated rows Oracle Database 10g: Implement and Administer a Data Warehouse

23 Specifying Build Methods
Two build methods are available when creating the materialized view: BUILD DEFERRED: Created but not populated BUILD IMMEDIATE: Created and populated The BUILD_MODE column in DBA_MVIEWS contains the method used. Specifying Build Methods BUILD DEFERRED: Create the materialized view definition but do not populate it with data. The materialized view is not eligible for query rewrite until it is populated during the next complete refresh. Until then, its status is UNUSABLE. BUILD IMMEDIATE: Create the materialized view and then populate it with data. This is the default value. Oracle Database 10g: Implement and Administer a Data Warehouse

24 Specifying Refresh Options
Specify how the materialized view should be refreshed from the detail tables: COMPLETE FAST FORCE NEVER The REFRESH_METHOD column in DBA_MVIEWS contains the option value. Specifying Refresh Options You specify how your materialized view should be refreshed from the detail tables by selecting one of the following options: COMPLETE: Refreshes by recalculating the detail query of the materialized view. This can be accomplished by deleting the table, or truncating it. Complete refresh re-executes the materialized view query, thereby completely recomputing the contents of the materialized view from the detail tables. FAST: Refreshes by incrementally adding the new data that has been inserted or updated into the tables. This option requires the use of information stored in materialized view logs or SQL*Loader direct-path or partition maintenance operation. FORCE (default): Applies FAST refresh if possible; otherwise, applies COMPLETE refresh NEVER: Prevents the materialized view from being refreshed with any refresh mechanism or procedure For detailed information about refresh options and procedures, see the lesson titled “Refreshing Materialized Views” in this course. Oracle Database 10g: Implement and Administer a Data Warehouse

25 Specifying Refresh Execution Modes
Two refresh execution modes: ON DEMAND: Manual ON COMMIT: Refresh done at transaction commit; only possible for fast-refreshable materialized views. In case of failure, subsequent refreshes are manual. Schedule: At regular intervals The REFRESH_MODE column in DBA_MVIEWS contains the refresh execution mode value. Specifying Refresh Execution Modes You specify how your materialized view should be refreshed by specifying one of the following refresh execution modes: ON COMMIT: Refresh occurs automatically when a transaction that modified one of the detail tables of the materialized view commits. This can be specified as long as the materialized view is fast refreshable. If a materialized view fails during refresh at commit time, the user must explicitly invoke the refresh procedure by using the DBMS_MVIEW package after addressing the errors specified in the trace files. Until this is done, the view is no longer refreshed automatically at commit time. ON DEMAND (default): Refresh occurs when the user demands it by using the DBMS_MVIEW package. This package provides several procedures and functions to manage materialized views, including the REFRESH, REFRESH_DEPENDENT, and REFRESH_ALL_MVIEWS procedures. If you do not specify ON COMMIT or ON DEMAND, you can schedule automatic refresh of a materialized view at a specific time with the START WITH and NEXT clauses. For example, it can be refreshed every Monday at 9:00 a.m. by using these clauses. For such refreshes to occur, the instance must initiate job processes with the JOB_QUEUE_PROCESSES parameter. Oracle Database 10g: Implement and Administer a Data Warehouse

26 Using Column Aliases in Materialized Views
SELECT s.time_id, c.time_id FROM sales s, products p, costs c WHERE s.prod_id = p.prod_id AND c.prod_id = p.prod_id AND p.prod_name IN (SELECT prod_name FROM products); Query rewrite CREATE MATERIALIZED VIEW sales_mv ENABLE QUERY REWRITE AS SELECT s.time_id sales_tid, c.time_id costs_tid FROM sales s, products p, costs c WHERE s.prod_id = p.prod_id AND c.prod_id = p.prod_id AND p.prod_name IN (SELECT prod_name FROM products); Using Materialized View Column Aliases When a materialized view is created, if its defining query contains same-name columns in its SELECT list, the name conflicts must be resolved by specifying unique aliases for those columns. However, using aliases in the SELECT list for name resolution may restrict the use of the full-text-match query rewrite. The full-text-match rewrite occurs only when the text of the materialized view’s defining query and the text of the input query are identical. If you specify SELECT aliases in the materialized view’s defining query and there are no aliases in the query, then the full-text-match comparison fails. In the example in the slide, even though the SALES_MV materialized view’s defining query is almost identical and logically equivalent to the input query, query rewrite does not happen. This is because of the failure of full-text-match rewrite, which is the only possible rewrite for this query because of the subquery in the WHERE clause. Oracle Database 10g: Implement and Administer a Data Warehouse

27 Using Materialized View Column Alias Lists
SELECT s.time_id, c.time_id FROM sales s, products p, costs c WHERE s.prod_id = p.prod_id AND c.prod_id = p.prod_id AND p.prod_name IN (SELECT prod_name FROM products); Query rewrite CREATE MATERIALIZED VIEW sales_mv (sales_tid, costs_tid) ENABLE QUERY REWRITE AS SELECT s.time_id, c.time_id FROM sales s, products p, costs c WHERE s.prod_id = p.prod_id AND c.prod_id = p.prod_id AND p.prod_name IN (SELECT prod_name FROM products); Using Materialized View Column Aliases (continued) Oracle Database 10g provides an optional column alias list with the CREATE MATERIALIZED VIEW statement. The column alias list explicitly resolves the column name conflicts without attaching aliases in the SELECT list of the materialized view. The syntax of the materialized view column alias list is identical to the syntax in the CREATE TABLE and CREATE VIEW statements. In this example, the defining query of SALES_MV now matches exactly with the query so full-text-match rewrite can take place. Note: When aliases are specified in both the SELECT list and the new alias list, the alias list supersedes the SELECT list. Oracle Database 10g: Implement and Administer a Data Warehouse

28 Registering User-Defined Materialized View Tables
Register existing materialized view tables with ON PREBUILT TABLE. The registered materialized view can be used for query rewrites. It can be maintained by refresh methods. Requirements: Table and materialized view have the same name. Column aliases in detail query must correspond. Column data types must match; can use the WITH REDUCED PRECISION clause. Table columns not referenced in the defining query are unmanaged columns. Table remains after the materialized view is dropped. Registering User-Defined Materialized Views Many existing database installations make extensive use of user-defined materialized views. In some cases, the existing materialized views are very large, making it desirable to register an existing materialized view table rather than regenerate the materialized view table from scratch. After it is registered, the materialized view can be used for query rewrites and maintained by the refresh methods. The user-defined materialized view table and the materialized view must have the same name and must be in the same schema. Each column alias in the subquery must correspond to a column name in the user-defined materialized view table. Corresponding columns in the detail tables must have exact matching data types unless the WITH REDUCED PRECISION clause is specified to allow the precision of columns in the detail tables to be compatible with that of the user-defined materialized view table columns. However, the user-defined materialized view table can contain unmanaged columns that are not referenced in the detail query of the materialized view. During a refresh operation, each unmanaged column is set to its default value. Therefore, the unmanaged columns cannot have NOT NULL constraints unless they also have default values. When you drop the materialized view, the table retains its identity and is not dropped. Oracle Database 10g: Implement and Administer a Data Warehouse

29 Partitioning and Materialized Views
Partitioning the fact tables: Improves the opportunity of fast refreshing the materialized view May enable Partition Change Tracking (PCT) refresh on the materialized view Partitioning the materialized view: Partition pruning can be used for query rewrite. Partitioning and Materialized Views Partitioning the fact tables also improves the opportunity of fast refreshing the materialized view because this may enable Partition Change Tracking (PCT) refresh on the materialized view. Partitioning a materialized view provides the benefit that PCT-based refresh can truncate the partition to efficiently maintain the materialized view. For additional information about Partition Change Tracking (PCT), see the lesson titled “Refreshing Materialized Views.” Oracle Database 10g: Implement and Administer a Data Warehouse

30 Partitioned Materialized View: Example
CREATE MATERIALIZED VIEW part_sales_mv PARALLEL PARTITION BY LIST (gid) (PARTITION g1 VALUES (0), PARTITION g2 VALUES (1), PARTITION g3 VALUES (3)) BUILD IMMEDIATE REFRESH COMPLETE ENABLE QUERY REWRITE AS SELECT prod_id,cust_id,time_id, GROUPING_ID(prod_id,cust_id,time_id) AS gid, sum(amount_sold) AS sum_sales FROM sales GROUP BY GROUPING SETS ((prod_id,cust_id,time_id), (prod_id,cust_id),(prod_id)); Partitioning Materialized View: Example Materialized views with multiple aggregate groups (using CUBE, ROLLUP, or GROUPING SETS for example) give their best performance when partitioned appropriately. The most effective partitioning scheme for these materialized views is to use LIST partitioning with the GROUPING_ID() column as the partition key. By partitioning the materialized views this way, you enable partition pruning for queries rewritten against this materialized view. Only relevant aggregate groups will be accessed depending on which group of rows the query is referring to. This greatly reduces the query processing cost. Note that this is only an example. Other types of materialized views can benefit from partitioning. Refer to the Oracle Database Data Warehousing Guide for additional examples. Oracle Database 10g: Implement and Administer a Data Warehouse

31 Using Enterprise Manager to Create Materialized Views
cr_mv_gen.gif Using Enterprise Manager to Create Materialized Views Access the Materialized Views page by clicking the Materialized Views link in the Materialized Views section of the Administration page. Click Create on the Materialized Views page to create a new materialized view. On the General page, provide the materialized view name, schema, and tablespace. Enter the query in the Materialized View Query box. Specify Refresh options on the Refresh page. Oracle Database 10g: Implement and Administer a Data Warehouse

32 Privileges Required to Create Materialized Views
Must be granted directly, not through roles To create a materialized view in your schema: CREATE MATERIALIZED VIEW, and CREATE [ANY] TABLE, and SELECT privilege on each detail table not owned To create a materialized view in another schema: CREATE ANY MATERIALIZED VIEW, and Materialized view owner must have Privileges Required to Create Materialized Views The privileges required to create a materialized view should be granted directly rather than through a role. Also, the user whose schema contains the materialized view must have sufficient quota in the target tablespace to store the materialized view’s container table or must have the UNLIMITED TABLESPACE system privilege. To create a materialized view in your own schema: You must have been granted the CREATE MATERIALIZED VIEW system privilege and either the CREATE TABLE or the CREATE ANY TABLE system privilege. You must also have access to any detail tables of the materialized view that you do not own, either through a SELECT object privilege on each of the tables or through the SELECT ANY TABLE system privilege. To create a materialized view in another user’s schema: You must have the CREATE ANY MATERIALIZED VIEW system privilege. The owner of the materialized view must have the CREATE TABLE system privilege. The owner must also have access to any detail tables of the materialized view that the schema owner does not own, and to any materialized view logs defined on those detail tables, either through a SELECT object privilege on each of the tables or through the SELECT ANY TABLE system privilege. Oracle Database 10g: Implement and Administer a Data Warehouse

33 Additional Privileges Required to Create Materialized Views
To create a materialized view refreshed at commit time: ON COMMIT REFRESH object privilege on each detail table not owned, or ON COMMIT REFRESH system privilege To enable query rewrite: Detail table owner must have QUERY REWRITE system privilege If you do not own detail tables: GLOBAL QUERY REWRITE system privilege or QUERY REWRITE on each detail table not owned SELECT WITH GRANT OPTION if materialized view is defined on a prebuilt table Additional Privileges Required to Create Materialized Views To create a REFRESH-ON-COMMIT materialized view, in addition to the privileges outlined on the previous page, you must have the ON COMMIT REFRESH object privilege on any detail tables that you do not own or you must have the ON COMMIT REFRESH system privilege. To create the materialized view with query rewrite enabled, in addition to the preceding privileges: The owner of the detail tables must have the QUERY REWRITE system privilege. If you are not the owner of the detail tables, you must have the GLOBAL QUERY REWRITE system privilege or the QUERY REWRITE object privilege on each table outside your schema. If the schema owner does not own the detail tables, then the schema owner must have the GLOBAL QUERY REWRITE privilege or the QUERY REWRITE object privilege on each table outside the schema. If you create the materialized view on a prebuilt table, you must have the SELECT WITH GRANT OPTION privilege on that table. Oracle Database 10g: Implement and Administer a Data Warehouse

34 Globalization and Materialized Views
Materialized views use the settings in effect during materialized view creation. Always specify globalization parameters to ensure that correct results are returned. WHERE varchar_col = TO_DATE('01-FEB-02') TO_DATE('01-FEB-2002', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE = AMERICAN') Globalization and Materialized Views If the globalization parameters in the session where a materialized view was created are inconsistent with the ones in a session where the refresh or query rewrite operation associated with the materialized view is executed, the DML command may fail or return incorrect results. The example shown in the slide illustrates two possible problems: If the data type of VARCHAR_COL is VARCHAR2(20), the expression may not work correctly when the date format is changed between the materialized view creation and utilization. The TO_DATE('01-FEB-02') expression may produce an error if evaluated in a French environment. If the expressions associated with the materialized view always specify appropriate NLS parameters explicitly, the problem described above does not occur. For example, TO_DATE('01-FEB-2002','DD-MON-YYYY','NLS_DATE_LANGUAGE = AMERICAN') will always return the correct results. Oracle Database 10g: Implement and Administer a Data Warehouse

35 Globalization Parameters Significant for Materialized Views
NLS_LANGUAGE NLS_TIMESTAMP_TZ_FORMAT NLS_ISO_CURRENCY NLS_TIMESTAMP_FORMAT NLS_DUAL_CURRENCY NLS_TIME_TZ_FORMAT NLS_DATE_LANGUAGE NLS_TIME_FORMAT NLS_DATE_FORMAT NLS_NUMERIC_CHARACTERS NLS_CALENDAR NLS_TERRITORY NLS_CURRENCY NLS_SORT NLS_COMP Globalization Parameters of Significance Not all globalization parameters are significant for materialized views. For example, when character data is processed in the server, the database character set is used. If the character set of a session is different from the database character set, characters that are specified or displayed in the session are automatically converted to and from the database character set. Consequently, no NLS character set parameter associated with materialized views is globalization sensitive. Oracle Database 10g: Implement and Administer a Data Warehouse

36 Adding Comments to Materialized Views
Adding a comment for an existing materialized view: Viewing comments: COMMENT ON MATERIALIZED VIEW cust_sales_mv IS 'sales materialized view'; SELECT mview_name, comments FROM user_mview_comments WHERE mview_name = 'CUST_SALES_MV'; Adding Comments to Materialized Views You can add a comment to a materialized view using the COMMENT ON MATERIALIZED VIEW statement. Query the USER/DBA/ALL_MVIEW_COMMENTS views to display the comments. Note: In Oracle Database 10g, you cannot use the COMMENT ON TABLE command for the materialized view container table as was allowed with previous releases. Use the COMMENT ON MATERIALIZED VIEW statement as shown in the slide. Oracle Database 10g: Implement and Administer a Data Warehouse

37 Altering Materialized Views
Changing the refresh option and refresh mode: Recompiling the materialized view: Enabling or disabling its use for query rewrite: ALTER MATERIALIZED VIEW cust_sales_mv REFRESH FAST ON COMMIT; ALTER MATERIALIZED VIEW cust_sales_mv COMPILE; ALTER MATERIALIZED VIEW cust_sales_mv DISABLE QUERY REWRITE; Altering Materialized Views For a materialized view to be altered, it must be in your own schema, or you must have the ALTER ANY MATERIALIZED VIEW system privilege. You can make the following modifications to a materialized view : Change the refresh options (FAST/FORCE/COMPLETE/NEVER). When you specify FAST refresh at create time, the Oracle server verifies that the materialized view is fast refreshable. It does not make this verification when changing it. If the materialized view is not fast refreshable, the Oracle server returns an error when you attempt to refresh it. Change the refresh mode (ON COMMIT/ON DEMAND). Recompile it. Enable or disable its use for query rewrite. Oracle Database 10g: Implement and Administer a Data Warehouse

38 Altering Materialized Views
Allocating an extent: Modifying the logging attribute: ALTER MATERIALIZED VIEW cust_sales_mv ALLOCATE EXTENT; ALTER MATERIALIZED VIEW cust_sales_mv NOLOGGING; Altering Materialized Views In addition, you can change some physical attributes of the materialized view as follows: Its PARALLEL clause, to change the degree of parallelism Extent allocation for the container object PCTFREE, PCTUSED, INITRANS, and other storage characteristics Logging attribute CACHE characteristics Note: You can also use the ALTER TABLE command to make these modifications, even if the materialized view was not created on a prebuilt table. All other changes to the materialized view are made by dropping and then re-creating the materialized view. For a complete reference on the subject, refer to the Oracle Database SQL Reference guide. Oracle Database 10g: Implement and Administer a Data Warehouse

39 Maintaining Partitions of a Materialized View
ALTER MATERIALIZED VIEW sales_mv TRUNCATE PARTITION year_1995; ALTER MATERIALIZED VIEW sales_mv DROP PARTITION year_1994; ALTER MATERIALIZED VIEW fact_mv EXCHANGE PARTITION year_2001 WITH TABLE sales_2001; Maintaining Partitions of a Materialized View In Oracle Database 10g, you can TRUNCATE, DROP, and EXCHANGE partitions. With this feature, you do not need to execute ALTER TABLE statements directly against the materialized view container table to perform these partition maintenance operations. Oracle Database 10g: Implement and Administer a Data Warehouse

40 Dropping Materialized Views
You must be the owner or you must have the DROP ANY MATERIALIZED VIEW system privilege. You must have privileges to drop underlying objects. Drop a materialized view using the DROP MATERIALIZED VIEW command: If the materialized view was created on a prebuilt container table, the table is retained. DROP MATERIALIZED VIEW cust_sales_mv; Dropping Materialized Views Use the DROP MATERIALIZED VIEW statement to drop a materialized view as shown in the following example: DROP MATERIALIZED VIEW sales_sum; This statement drops the SALES_SUM materialized view including its container table. If the materialized view was prebuilt on a table, then the table is not dropped, but it can no longer be maintained with the refresh mechanism or used by query rewrite. The materialized view must be in your own schema or you must have the DROP ANY MATERIALIZED VIEW system privilege. You also need all the necessary privileges to drop all objects created by the CREATE MATERIALIZED VIEW command, including the container table and the index created to support fast refreshes on the materialized view. Oracle Database 10g: Implement and Administer a Data Warehouse

41 Viewing Staleness Information
Materialized view may diverge from the detail tables. Query the STALENESS column in DBA_MVIEWS: FRESH STALE UNUSABLE UNKNOWN UNDEFINED Viewing Staleness Information A materialized view is automatically revalidated when it is referenced. You can determine whether a materialized view is “fresh” or “stale” by querying the STALENESS column of the DBA_MVIEWS view. It contains the following values: FRESH: Materialized view is a read-consistent view of the current state of its detail tables. STALE: Materialized view is out of date because one or more of its detail tables has changed. If the materialized view was FRESH before it became STALE, it is a read-consistent view of a former state of its masters. UNUSABLE: Materialized view is not a read-consistent view of its detail tables from any point in time. (True for materialized views defined with the BUILD DEFERRED clause.) UNKNOWN: The Oracle server does not know whether the materialized view is in a read-consistent view of its detail tables from any point in time. (True for materialized views created on prebuilt tables.) UNDEFINED: The materialized view has remote masters. The concept of staleness is not defined for such materialized views. Oracle Database 10g: Implement and Administer a Data Warehouse

42 Materialized View Integrity
QUERY_REWRITE_INTEGRITY: Initialization parameter controls materialized view integrity. Parameter values: ENFORCED TRUSTED STALE_TOLERATED Materialized View Integrity By default, the QUERY_REWRITE_INTEGRITY initialization parameter is set to ENFORCED. In this mode, all constraints must be validated. If you define constraints with ENABLE NOVALIDATE RELY, certain types of query rewrite might not work. To enable query rewrite in an environment where constraints have not been validated, you should set the integrity level to a lower level of granularity such as TRUSTED or STALE_TOLERATED. The QUERY_REWRITE_INTEGRITY initialization parameter accepts the following values: ENFORCED: The Oracle server enforces and guarantees consistency and integrity. This is the default. TRUSTED: The Oracle server allows rewrites using relationships that have been declared, but are not enforced by the Oracle server. STALE_TOLERATED: The Oracle server allows rewrites using unenforced relationships. Materialized views are eligible for rewrite even if they are known to be inconsistent with their detail tables. Oracle Database 10g: Implement and Administer a Data Warehouse

43 Invalidating Materialized Views
Automatic invalidation during dependency changes Automatic revalidation during: Refresh Query rewrite STATUS column in DBA_OBJECTS: INVALID VALID COMPILE_STATE in DBA_MVIEWS: NEEDS_COMPILE Manual revalidation with: ALTER MATERIALIZED VIEW COMPILE Invalidating Materialized Views Dependencies related to materialized views are automatically maintained to ensure correct operation. When a materialized view is created, the materialized view depends on the detail tables referenced in its definition. Any DML operation, such as an INSERT, DELETE, or UPDATE, or a DDL operation on any dependency in the materialized view causes it to become invalid. This state can be viewed in DBA_OBJECTS or in DBA_MVIEWS. Revalidation will automatically occur whenever you refresh your materialized view or whenever query rewrite is used. Until then, your materialized view status remains the same. For testing purposes, you may want to revalidate your materialized view manually if, for example, the COMPILE_STATE column of DBA_MVIEWS contains NEEDS_COMPILE. Use the ALTER MATERIALIZED VIEW COMPILE statement to revalidate the materialized view manually. Note: If the COMPILE_STATE column contains NEEDS COMPILE, the other columns in the view may not reflect the true status. Oracle Database 10g: Implement and Administer a Data Warehouse

44 Oracle Database 10g: Implement and Administer a Data Warehouse 9-44
Summary In this lesson, you should have learned how to: Use summaries in a data warehouse environment Differentiate types of materialized views Create a materialized view Use the QUERY_REWRITE_INTEGRITY parameter Oracle Database 10g: Implement and Administer a Data Warehouse

45 Oracle Database 10g: Implement and Administer a Data Warehouse 9-45
Practice 9: Overview This practice covers the following topics: Creating materialized views on prebuilt tables Estimating the number of rows of a potential materialized view Creating new materialized views Viewing objects created when materialized views are created Oracle Database 10g: Implement and Administer a Data Warehouse

46


Download ppt "Materialized Views."

Similar presentations


Ads by Google