When the data in the base tables is updated, the data in the materialized view may become inconsistent with that in the base tables. To maintain the data in the materialized view, OceanBase Database refreshes the materialized view.
OceanBase Database supports full refreshes and incremental refreshes for materialized views, and supports manual and automatic refreshes.
Note
Refreshing a materialized view also automatically updates all its indexes.
Full refresh
OceanBase Database performs a full refresh by using remote refresh. Specifically, a hidden table is created, a refresh statement is executed on the hidden table, and the original table is then switched with the hidden table. Therefore, a full refresh operation requires additional space and will fully rebuild the indexes (if any).
Considerations
- A full refresh can be a very time-consuming process, especially when a large amount of data needs to be read and processed. Therefore, you should always consider the time required for a full refresh before you execute the operation.
- A full refresh is allowed only if the columns of the base table match the columns of the materialized view. If they do not match, a full refresh is not allowed.
- If a materialized view is fully refreshed, all dependent materialized views (nested materialized views) must be fully refreshed before any incremental refreshes can be performed. Otherwise, an error will be returned.
Incremental refresh
Currently, incremental refresh of materialized views supports SQL statements of the following types: non-aggregated single-table queries, aggregated single-table queries, multi-table joins, joined aggregated queries, and UNION ALL queries. For SQL statements that do not fall into these five categories, incremental refresh is not supported. For more information about the requirements for incremental refresh SQL statements, see the following description.
Notice
- Because the
REFRESH FASTmethod uses the records in the materialized view log to determine the content to be incrementally refreshed, you must create a materialized view log (mlog) for the base table before you create a materialized view for incremental refresh.- For more information about how to create an mlog, see Materialized view log.
- OceanBase Database supports automatic management of mlogs. If you enable automatic mlog management, you do not need to create an mlog for the base table before you create a materialized view for incremental refresh. OceanBase Database automatically creates the corresponding mlog or updates the existing mlog table definition to include the columns required by the newly created materialized view. For more information, see Automatic management of materialized view logs.
- All columns used in the materialized view for incremental refresh must be included in the mlog.
Incremental refresh of a non-aggregated table
Example of incremental refresh of a non-aggregated table
Create the
tbl1table.CREATE TABLE tbl1 (col1 INT PRIMARY KEY, col2 INT, col3 INT, col4 INT);Create a materialized view log on the
tbl1table.CREATE MATERIALIZED VIEW LOG ON tbl1 WITH SEQUENCE (col2, col3, col4) INCLUDING NEW VALUES;Create an incremental refresh materialized view
mv_tbl1based on thetbl1table.CREATE MATERIALIZED VIEW mv_tbl1 REFRESH FAST ON DEMAND AS SELECT col1, col2 FROM tbl1;
Incremental refresh of a single table aggregate view
The following requirements must be met for incremental refresh of a single table aggregate view:
The
FROMtable must be a base table, not an inline view or a regular view.Note
Nested materialized views do not support real-time materialized views. Therefore, when the
FROMtable is a materialized view, real-time materialized views cannot be used.Only one table exists in the
FROMclause.An mlog is created on the
FROMtable, and all columns used in the view exist in the mlog.The view definition does not contain subqueries.
Window functions are not supported.
The view definition does not contain the
ROLLUP,HAVING,DISTINCT,ORDER BY,LIMIT, orFETCHclause.If the query contains the
DISTINCTkeyword, the output columns of the materialized view that can be incrementally updated must be unique. In this case, you can directly disable theDISTINCTkeyword or remove it.A statement without the
GROUP BYclause must be a scalar aggregate.For a materialized view with the
GROUP BYclause, only theSUMandCOUNTaggregate functions are supported, and only simple columns can be used in the aggregate functions. TheGROUP BYclause must meet the following requirements:Aggregate function The SELECT clause must contain the dependent column. COUNT( expr ) N/A SUM ( expr ) COUNT( expr ) or expr is not null AVG ( expr ) SUM ( expr ),COUNT( expr ) STDDEV ( expr ) SUM ( expr ),COUNT( expr ),SUM ( expr * expr ) VARIANCE ( expr ) SUM ( expr ),COUNT( expr ),SUM ( expr * expr ) Other aggregate functions that can be split into SUM and COUNT... (The calculation method may change, which may affect the precision.) SUM (col1),COUNT(col1) MAX(expr)/MIN(expr) COUNT(expr) - The
GROUP BYclause must be a standardGROUP BYclause and cannot contain theROLLUPorHAVINGclause. - The
SELECTclause must contain all columns in theGROUP BYclause. - The aggregate function cannot contain the
DISTINCTkeyword. - In addition to the aggregate function columns, the
SELECTclause must contain the corresponding dependent columns and theCOUNT(*)column. For example, if theSUM(expr)aggregate function is used, theCOUNT(*)andCOUNT(expr)columns must also be included.
- The
Requirements for incremental refresh of a MIN/MAX aggregate view:
Notice
Materialized views that use the MIN or MAX function do not support real-time materialized views.
If the requirements for incremental refresh of a single table aggregate view are met, the requirements for using the MAX and MIN aggregate functions are as follows: an index with the GROUP BY columns as the prefix must exist on the base table of the materialized view.
Note
In OceanBase Database, the parameters of the MIN and MAX aggregate functions can be non-basic columns, and the GROUP BY columns can be non-basic columns.
Example of incremental refresh of a single-table aggregate materialized view
Create a table named
test_tbl1.CREATE TABLE test_tbl1 (col1 INT PRIMARY KEY, col2 INT, col3 INT, col4 INT);Create a materialized view log on the
test_tbl1table.CREATE MATERIALIZED VIEW LOG ON test_tbl1 WITH SEQUENCE (col2, col3, col4) INCLUDING NEW VALUES;Create a materialized view that is refreshed incrementally.
Create a materialized view named
mv1_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view selects thecol2column from thetest_tbl1table and calculates the aggregate results ofcount(*),count(col3), andsum(col3), grouped by the values of thecol2column. The materialized view is namedmv1_test_tbl1.CREATE MATERIALIZED VIEW mv1_test_tbl1 REFRESH FAST ON DEMAND AS SELECT col2, count(*) cnt, count(col3) cnt_col3, sum(col3) sum_col3 FROM test_tbl1 GROUP BY col2;Create a materialized view named
mv2_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view calculates the aggregate results ofcount(*),count(col3), andsum(col3)from thetest_tbl1table. The materialized view is namedmv2_test_tbl1.CREATE MATERIALIZED VIEW mv2_test_tbl1 REFRESH FAST ON DEMAND AS SELECT count(*) cnt, count(col3) cnt_col3, sum(col3) sum_col3 FROM test_tbl1;Create a materialized view named
mv3_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view calculates the results ofcount(col3)andsum(col3)from thetest_tbl1table. The materialized view is namedmv3_test_tbl1.CREATE MATERIALIZED VIEW mv3_test_tbl1 REFRESH FAST ON DEMAND AS SELECT count(col3) cnt_col3, sum(col3) sum_col3 FROM test_tbl1;Create a materialized view named
mv4_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view selects thecol2andcol3columns from thetest_tbl1table and calculates the aggregate results ofcount(*),count(col3), andsum(col3), grouped by the values of thecol2andcol3columns. The materialized view is namedmv4_test_tbl1.CREATE MATERIALIZED VIEW mv4_test_tbl1 REFRESH FAST ON DEMAND AS SELECT col2, col3, count(*) cnt, count(col3) cnt_col3, sum(col3) sum_col3 FROM test_tbl1 GROUP BY col2, col3;Create a materialized view named
mv5_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view selects thecol2column from thetest_tbl1table and calculates the aggregate results ofcount(*),count(col3),sum(col3), andavg(col3), and also calculates some custom columnscalcol1andcalcol2, grouped by the values of thecol2column. The materialized view is namedmv5_test_tbl1.CREATE MATERIALIZED VIEW mv5_test_tbl1 REFRESH FAST ON DEMAND AS SELECT col2, count(*) cnt, count(col3) cnt_col3, sum(col3) sum_col3, avg(col3) avg_col3, avg(col3) * sum(col3)/col2 calcol1, col2+sum(col3) calcol2 FROM test_tbl1 GROUP BY col2;Create a materialized view named
mv6_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view selects thecol2column from thetest_tbl1table and calculates the aggregate results ofcount(*),count(col3),sum(col3),count(col3*col3),sum(col3*col3), andSTDDEV(col3), grouped by the values of thecol2column. The materialized view is namedmv6_test_tbl1.CREATE MATERIALIZED VIEW mv6_test_tbl1 REFRESH FAST ON DEMAND AS SELECT col2, count(*) cnt, count(col3) cnt_col3, sum(col3) sum_col3, count(col3*col3) cnt_col3_2, sum(col3*col3) sum_col3_2, STDDEV(col3) stddev_col3 FROM test_tbl1 GROUP BY col2;Create a materialized view by using the
MAXandMINaggregate functions.Create an index named
idx_test_tbl1on thetest_tbl1table based on thecol1andcol2columns. The index is namedidx_test_tbl1.CREATE INDEX idx_test_tbl1 ON test_tbl1(col1, col2);Create a materialized view named
mv7_test_tbl1. Specify the incremental refresh method for the materialized view and allow manual refresh. The query part of the materialized view selects thecol1andcol2columns from thetest_tbl1table and calculates the aggregate results ofcount(*), the sum of the minimum value ofcol3and the maximum value ofcol4in each group, and groups the data by the combination ofcol1andcol2. The materialized view is namedmv7_test_tbl1.CREATE MATERIALIZED VIEW mv7_test_tbl1 REFRESH FAST ON DEMAND AS SELECT col1, col2, count(*) cnt, MIN(col3) + MAX(col4) AS min_max_val FROM test_tbl1 GROUP BY col1, col2;
Use non-basic columns in the
GROUP BYclause.Create a table named
m_tbl1.obclient> CREATE TABLE m_tbl1(col1 INT PRIMARY KEY, col2 DATETIME, col3 INT, col4 INT, col5 INT, col6 INT);Create a materialized view log on the
m_tbl1table. The materialized view log is namedm_tbl1.obclient> CREATE MATERIALIZED VIEW LOG ON m_tbl1 WITH PRIMARY KEY, ROWID, SEQUENCE (col2, col3, col4, col5, col6) INCLUDING NEW VALUES;Create an index named
idx1_m_tbl1on them_tbl1table based on thecol3and(DATE(col2))columns. The index is namedidx1_m_tbl1.obclient> CREATE INDEX idx1_m_tbl1 ON m_tbl1(col3, (DATE(col2)));Create a materialized view named
m_tbl1_mv1that is refreshed incrementally. The materialized view is namedm_tbl1_mv1.obclient> CREATE MATERIALIZED VIEW m_tbl1_mv1 REFRESH FAST ON DEMAND AS SELECT col3, DATE(col2) gby_2, COUNT(*) cnt, MAX(col4) max_c4, MIN(col5 + col6) min_c5_c6 FROM m_tbl1 GROUP BY col3, DATE(col2);
Incremental refresh of a materialized view with multiple tables joined
The following requirements must be met for incremental refresh of a materialized view with multiple tables joined:
The
FROMclause must specify base tables, not inline views.The
FROMclause must specify at least two tables.Notice
- The incremental refresh feature of materialized views in OceanBase Database supports outer joins (
LEFT JOIN/RIGHT JOIN). - Outer join limitations: The join tree must be a left-deep join tree where
INNER JOINis performed first andLEFT JOINis performed later. - If the
SELECTclause of the incremental refresh materialized view contains theLEFT JOINoperator, you cannot specify a primary key (PRIMARY KEY) or unique index (UNIQUE INDEX) when you create the materialized view. This is to avoid refresh exceptions caused by constraint conflicts. - Aggregated materialized views with outer joins do not support real-time materialized views.
- The incremental refresh feature of materialized views in OceanBase Database supports outer joins (
Materialized log tables must be created for all tables specified in the
FROMclause, and all columns used in the materialized view must exist in the materialized log tables.The materialized view definition must not contain subqueries.
The materialized view definition must not contain the
ROLLUP,HAVING,WINDOW FUNCTION,DISTINCT,ORDER BY,LIMIT, orFETCHclause.The materialized view definition must not contain expressions that generate unstable output values, such as
ROWNUM,RAND, orSYSDATE.
Example
Create the base tables
t1andt2.CREATE TABLE t1(c1 INT PRIMARY KEY, c2 INT, c3 INT);CREATE TABLE t2(c1 INT PRIMARY KEY, c4 INT, c5 INT);Create materialized log tables for the
t1andt2tables.CREATE MATERIALIZED VIEW LOG ON t1 WITH PRIMARY KEY, ROWID, SEQUENCE (c2) INCLUDING NEW VALUES;CREATE MATERIALIZED VIEW LOG ON t2 WITH PRIMARY KEY, ROWID, SEQUENCE (c4) INCLUDING NEW VALUES;Create the materialized view
mv1_t1_t2for the join of thet1andt2tables.CREATE MATERIALIZED VIEW mv1_t1_t2 REFRESH FAST AS SELECT t1.c1 t1c1, t1.c2, t2.c1 t2c1, t2.c4 FROM t1 JOIN t2 ON t1.c1=t2.c1;
Note
- To improve the performance of simple join materialized views in incremental refresh and real-time materialized views, we recommend that you create indexes for the materialized view and its base tables as follows:
- Create indexes for the join keys of each table to improve the join performance in incremental updates and real-time materialized views.
- Create indexes for the primary key columns of the base tables in the materialized view.
- As the number of tables joined in the materialized view increases, the performance of incremental refresh and real-time materialized view queries usually decreases.
Here is an example of creating indexes for the materialized view and its base tables:
(Optional) Execute the following statement to delete the test data.
You can skip this step if the following database objects do not exist.
DROP MATERIALIZED VIEW LOG ON t1; DROP TABLE IF EXISTS t1; DROP MATERIALIZED VIEW LOG ON t2; DROP TABLE IF EXISTS t2; DROP MATERIALIZED VIEW rt_mv1;Execute the following statement to create the
t1table and theidx_t1_c2index.CREATE TABLE t1(c1 INT PRIMARY KEY AUTO_INCREMENT, c2 INT, c3 INT, c4 INT, c5 INT); CREATE INDEX idx_t1_c2 ON t1(c2);Execute the following statement to create the
t2table and theidx_t2_c3index.CREATE TABLE t2(c1 INT PRIMARY KEY AUTO_INCREMENT, c2 INT, c3 INT, c4 INT, c5 INT); CREATE INDEX idx_t2_c3 ON t2(c3);Execute the following statement to create materialized log tables for the
t1andt2tables.CREATE MATERIALIZED VIEW LOG ON t1 WITH PRIMARY KEY, ROWID, SEQUENCE (c2, c3, c4) INCLUDING NEW VALUES; CREATE MATERIALIZED VIEW LOG ON t2 WITH PRIMARY KEY, ROWID, SEQUENCE (c2, c3, c4) INCLUDING NEW VALUES;Execute the following statement to create the real-time materialized view
rt_mv1.CREATE MATERIALIZED VIEW rt_mv1 NEVER REFRESH ENABLE ON QUERY COMPUTATION DISABLE QUERY REWRITE AS SELECT t1.c1 AS t1_c1, t2.c1 AS t2_c1, t1.c2 AS t1_c2, t2.c2 AS t2_c2, t1.c3 AS t1_c3, t2.c3 AS t2_c3 FROM t1, t2 WHERE t1.c2 = t2.c3;Execute the following statement to create indexes for the primary key columns of the base tables in the materialized view.
CREATE INDEX idx_mv_t1_c1 ON rt_mv1(t1_c1); CREATE INDEX idx_mv_t2_c1 ON rt_mv1(t2_c1);
Incremental refresh of aggregated views across multiple tables
The requirements for incremental refresh of aggregated views across multiple tables are as follows:
- The requirements for incremental refresh of aggregated views across multiple tables are the union of the requirements for incremental refresh of aggregated views on a single table and incremental refresh of joined views across multiple tables.
- Incremental refresh is supported for aggregated views with outer joins. The limitations for outer joins in aggregated views are the same as those for non-aggregated outer-joined materialized views. The limitations for the aggregated part are the same as those for inner-joined aggregated views. However, aggregated views with outer joins do not support the
MINandMAXaggregate functions, and do not support real-time materialized views.
Example of incremental refresh of aggregated views across multiple tables
Create the base tables
t3andt4.CREATE TABLE t3(c1 INT, c2 INT, c3 INT, c4 INT, PRIMARY KEY(c1));CREATE TABLE t4(c1 INT, c2 INT, c3 INT, c4 INT, PRIMARY KEY(c1));Create materialized view logs on tables
t3andt4.CREATE MATERIALIZED VIEW LOG ON t3 WITH PRIMARY KEY, ROWID, SEQUENCE(c2, c3, c4) INCLUDING NEW VALUES;CREATE MATERIALIZED VIEW LOG ON t4 WITH PRIMARY KEY, ROWID, SEQUENCE(c2, c3, c4) INCLUDING NEW VALUES;Create a real-time materialized view
mv1_t3_t4for incremental refresh of the aggregated join between tablest3andt4.CREATE MATERIALIZED VIEW mv1_t3_t4 REFRESH FAST ENABLE ON QUERY COMPUTATION AS SELECT t3.c1, COUNT(*) cnt, COUNT(t4.c4) cnt_c4, SUM(t4.c4) sum_c4, AVG(t4.c4) avg_c4 FROM t3, t4 WHERE t3.c2 = t4.c3 GROUP BY t3.c1;
Incremental refresh of a set query
A materialized view that uses a UNION ALL set query supports incremental refresh. An incremental refresh of a set query allows you to use any materialized view that supports incremental refresh in the branches of the UNION ALL set query except for an excepted join materialized view.
The following conditions must be met for an incremental refresh of a set query:
A materialized view that uses a set query does not support real-time materialized views.
The top-level query is
UNION ALL, and the view definition does not contain subqueries or clauses such asORDER BY,LIMIT, orFETCH.The output columns at the same projection position in each branch of the
UNION ALLset query must be of the same type. You cannot forcibly convert the column types of the subqueries to the same type by using theCASTfunction.For example, in a materialized view that joins multiple tables, the primary keys of the joined tables must appear in the
SELECTclause. TheSELECToutput columns cannot be forcibly converted to the same type by using theCASTfunction due to theUNION ALLset query.The same type or value of a constant must exist at the same projection position in each branch of the
UNION ALLset query. The constant is used to distinguish the branches.
Example
Create the base tables
ua_tbl1andua_tbl2.CREATE TABLE ua_tbl1 (col1 INT PRIMARY KEY, col2 INT, col3 INT, col4 INT);CREATE TABLE ua_tbl2 (col1 INT PRIMARY KEY, col2 INT, col3 INT, col4 INT);Create materialized view logs on the tables
ua_tbl1andua_tbl2.CREATE MATERIALIZED VIEW LOG ON ua_tbl1 WITH PRIMARY KEY, ROWID, SEQUENCE (col2, col3, col4) INCLUDING NEW VALUES;CREATE MATERIALIZED VIEW LOG ON ua_tbl2 WITH PRIMARY KEY, ROWID, SEQUENCE (col2, col3, col4) INCLUDING NEW VALUES;Create the materialized view
mv_ua_tbl1_tbl2that supports incremental refresh of a set query.CREATE MATERIALIZED VIEW mv_ua_tbl1_tbl2 REFRESH FAST ON DEMAND AS SELECT a.col1 as a_c1, b.col1 as b_c1, 1 marker, a.col2 val FROM ua_tbl1 a INNER JOIN ua_tbl2 b ON a.col2 = b.col3 UNION ALL SELECT col1 a_c1, col2 b_c1, 2 marker, count(*) val FROM ua_tbl1 GROUP BY col1, col2;
Parallelism control mechanism for materialized view refresh
OceanBase Database provides a parallelism control mechanism for materialized view refresh. If you explicitly specify the parallelism for a refresh operation, the specified value will be used. If you do not explicitly specify the parallelism, you can configure the system variable mview_refresh_dop to set the parallelism for the current session.
Set mview_refresh_dop
mview_refresh_dop is a system variable in OceanBase Database that controls the default parallelism for materialized view refresh operations. By appropriately setting its value, you can significantly improve the refresh efficiency and optimize the database performance.
When mview_refresh_dop is set to 0 or 1, parallel refresh is disabled. For more information about the system variable mview_refresh_dop, see mview_refresh_dop.
Here are some examples:
Set the parallelism for the current session to 5.
SET mview_refresh_dop = 5;Set the parallelism for all sessions to 5.
SET GLOBAL mview_refresh_dop = 5;Notice
Setting the value of a global variable does not take effect on the current session. You must log in again to create a new session for the setting to take effect.
View the parallelism of a materialized view
Query the DBA_MVIEWS view to obtain the background refresh parallelism of a materialized view.
Note
When you query the
DBA_MVIEWSview, you can only view the parallelism specified for the materialized view.- If the
REFRESH_DOPfield is not 0, the background refresh task of the materialized view will use the parallelism specified byREFRESH_DOP. - If
REFRESH_DOPis 0, the globalmview_refresh_dopvalue will be used.
Here are some examples:
Create a materialized view named
mv0_t1.CREATE MATERIALIZED VIEW mv0_t1 REFRESH COMPLETE ON DEMAND START WITH sysdate() NEXT sysdate() + INTERVAL 10 SECOND AS SELECT c1, c2 FROM t1;Query the DBA_MVIEWS view to obtain the background refresh parallelism of the
mv0_t1materialized view.SELECT OWNER, MVIEW_NAME,REFRESH_DOP FROM oceanbase.DBA_MVIEWS WHERE OWNER = 'db_test' AND MVIEW_NAME = 'mv0_t1';The returned result is as follows:
+---------+------------+-------------+ | OWNER | MVIEW_NAME | REFRESH_DOP | +---------+------------+-------------+ | db_test | mv0_t1 | 0 | +---------+------------+-------------+ 1 row in setChange the parallelism of the
mv0_t1materialized view to 8.ALTER MATERIALIZED VIEW mv0_t1 PARALLEL 8;Query the DBA_MVIEWS view to obtain the background refresh parallelism of the
mv0_t1materialized view.SELECT OWNER, MVIEW_NAME,REFRESH_DOP FROM oceanbase.DBA_MVIEWS WHERE OWNER = 'db_test' AND MVIEW_NAME = 'mv0_t1';The returned result is as follows:
+---------+------------+-------------+ | OWNER | MVIEW_NAME | REFRESH_DOP | +---------+------------+-------------+ | db_test | mv0_t1 | 8 | +---------+------------+-------------+ 1 row in set
- If the
Query the DBA_MVREF_RUN_STATS view to obtain the historical refresh parallelism of a materialized view.
Here are some examples:
SELECT REFRESH_ID, MVIEWS, PARALLELISM FROM oceanbase.DBA_MVREF_RUN_STATS WHERE MVIEWS = 'db_test.mv0_t1' ORDER BY REFRESH_ID;The returned result is as follows:
+------------+----------------+-------------+ | REFRESH_ID | MVIEWS | PARALLELISM | +------------+----------------+-------------+ | 4928139 | db_test.mv0_t1 | 5 | | 4928218 | db_test.mv0_t1 | 5 | | 4928310 | db_test.mv0_t1 | 8 | | 4928397 | db_test.mv0_t1 | 8 | | 4928485 | db_test.mv0_t1 | 8 | +------------+----------------+-------------+ 5 rows in set
Manually refresh a materialized view
If the refresh mode of a materialized view is ON DEMAND, you can manually refresh the materialized view by using the DBMS_MVIEW package. For a materialized view defined for incremental refresh, you can manually refresh it as a full refresh.
Note
Only the owner or tenant administrator can refresh a materialized view.
Refresh a materialized view by using the REFRESH procedure
DBMS_MVIEW.REFRESH (
IN mv_name VARCHAR(65535), -- Name of the materialized view
IN method VARCHAR(65535) DEFAULT NULL, -- Refresh option.
-- f: fast refresh
-- ?: force refresh
-- C|c: complete refresh
-- A|a: always refresh, equivalent to C
IN refresh_parallel INT DEFAULT 0); -- Refresh parallelism
Here is an example:
Insert three rows into the
test_tbl1table. The following sample code shows how to do this:INSERT INTO test_tbl1 VALUES (1, 1, 1, 1),(2, 2, 2, 2),(3, 3, 3, 3);View the information about the materialized view
mv1_test_tbl1. The following sample code shows how to do this:SELECT * FROM mv1_test_tbl1;The returned result is as follows:
Empty setManually refresh the materialized view
mv1_test_tbl1by using theDBMS_MVIEW.REFRESHprocedure. The following sample code shows how to do this:Refresh the materialized view by using the refresh option specified for the materialized view:
CALL DBMS_MVIEW.REFRESH('mv1_test_tbl1');Refresh the materialized view by using the specified refresh option:
CALL DBMS_MVIEW.REFRESH('mv1_test_tbl1', 'c');
View the information about the materialized view
mv1_test_tbl1. The following sample code shows how to do this:SELECT * FROM mv1_test_tbl1;The returned result is as follows:
+------+------+----------+----------+ | col2 | cnt | cnt_col3 | sum_col3 | +------+------+----------+----------+ | 1 | 1 | 1 | 1 | | 2 | 1 | 1 | 2 | | 3 | 1 | 1 | 3 | +------+------+----------+----------+ 3 rows in set
Set the refresh parallelism for manually refreshing a materialized view
You can set the default refresh parallelism for manually refreshing a materialized view by setting the system variable mview_refresh_dop.
You can also explicitly set the refresh parallelism for the current refresh by specifying the refresh_parallel parameter when calling the DBMS_MVIEW.REFRESH function.
Notice
If you do not explicitly specify the refresh parallelism and the value of the mview_refresh_dop variable is 0 or 1, no parallel refresh is performed.
Here is an example:
Set the current session parallelism to 5. The following sample code shows how to do this:
SET mview_refresh_dop = 5;Manually refresh the materialized view:
Explicitly set the refresh parallelism to 8. The current refresh parallelism is 8.
CALL DBMS_MVIEW.REFRESH('mv1', 'c', 8);Do not explicitly set the refresh parallelism. The current refresh parallelism is 5, which is the value of the session variable.
CALL DBMS_MVIEW.REFRESH('mv1', 'c');
Automatic refresh of materialized views
When you create a materialized view, if you specify the START WITH datetime_expr and NEXT datetime_expr clauses, the system automatically creates a background refresh task for the materialized view when the conditions are met.
Note
You can view the background refresh tasks of materialized views in the DBA_SCHEDULER_JOBS view. For more information about how to query materialized views, see Query materialized views.
Parallelism of automatic refresh of materialized views
You can specify the parallelism for background refresh of materialized views in the following two ways:
Note
The following parallelism options are listed in order of decreasing priority.
Specify the parallelism (Table DOP) when you create a materialized view.
Here is an example:
CREATE MATERIALIZED VIEW mv_t1 PARALLEL 8 REFRESH COMPLETE ON DEMAND START WITH sysdate() NEXT sysdate() + INTERVAL 10 SECOND AS SELECT c1, c2 FROM t1;Set the global session variable
mview_refresh_dopas the refresh parallelism.Automatic refresh operations are performed by internal sessions. To make the setting of the global session variable mview_refresh_dop effective for internal sessions, you must set it at the global level.
Notice
If you do not explicitly specify the parallelism when you create a materialized view and the value of the
mview_refresh_dopvariable is 0 or 1, the background refresh task does not enable parallel refresh.Here is an example:
Set the global session parallelism to 5.
SET GLOBAL mview_refresh_dop = 5;Create a materialized view:
If you specify the parallelism as 8 when you create a materialized view, the background refresh task uses 8 as the refresh parallelism.
CREATE MATERIALIZED VIEW mv1_t1 PARALLEL 8 REFRESH COMPLETE ON DEMAND START WITH sysdate() NEXT sysdate() + INTERVAL 10 SECOND AS SELECT c1, c2 FROM t1;If you do not specify the parallelism when you create a materialized view, the background refresh task uses the value of the
mview_refresh_dopvariable, which is 5, as the refresh parallelism.CREATE MATERIALIZED VIEW mv2_t1 REFRESH COMPLETE ON DEMAND START WITH sysdate() NEXT sysdate() + INTERVAL 10 SECOND AS SELECT c1, c2 FROM t1;
Refresh nested materialized views
Note
OceanBase Database allows you to create a nested materialized view based on a materialized view without a primary key.
Notice
Real-time materialized views cannot be created as nested materialized views. In other words, you cannot specify the ENABLE ON QUERY COMPUTATION clause when you create a nested materialized view.
Refresh rules for nested materialized views
The refresh methods supported by nested materialized views are the same as those supported by non-nested materialized views, including full refresh and incremental refresh. Although refreshing a nested materialized view only requires the user tables and materialized views (along with their mlogs) that it directly depends on, its data consistency relies on the materialized views it is based on. This means that to ensure the data of a nested materialized view remains up-to-date through refresh, the data of the materialized views it depends on must also be up-to-date, requiring them to be refreshed first.
For example, consider the following scenario: materialized view mv1 is built on tables tbl1 and tbl2, materialized view mv2 is built on materialized view mv1 and table tbl3, and materialized view mv3 is built on materialized views mv1 and mv2. If we refresh mv1, mv2, and mv3 in that order, we can ensure the overall data consistency of the nested materialized views. However, if we refresh mv2 first and then mv1, the data in mv2 will not be the latest (it will lag behind mv1). Similarly, if we refresh mv3 first and then mv2, the data in mv3 will not be the latest (it will lag behind mv2).
OceanBase Database supports cascading refreshes for nested materialized views. Cascading refreshes are divided into cascading inconsistent refreshes and cascading consistent refreshes:
Cascading inconsistent refresh: Refreshes all materialized views that the nested materialized view depends on, starting from the bottom up. Each materialized view's refresh does not guarantee data consistency, and the data points read from the base tables are inconsistent. Cascading inconsistent refreshes are suitable for batch synchronization scenarios, such as when a business party synchronizes data from the upstream at regular intervals. After data synchronization is complete, a cascading inconsistent refresh can be performed to ensure the eventual consistency of the materialized views.
Cascading consistent refresh: Snapshot-consistent cascading refresh, which ensures that after the entire cascading refresh is completed, the data points of all base tables that the upper-level materialized views depend on are consistent. Cascading consistent refreshes are suitable for real-time data synchronization scenarios. We ensure that after each cascading refresh, the data snapshots in the materialized views are at the same data point.
Nested materialized view refresh example
If a materialized view is fully refreshed, any dependent materialized views must be fully refreshed before they can be incrementally refreshed. Otherwise, an error will occur.
Here is an example:
Create the
tbl1table and insert one row of data.CREATE TABLE tbl1(id INT, name VARCHAR(30), PRIMARY KEY(id));INSERT INTO tbl1 VALUES (1, 'jack');Create the
tbl2table and insert one row of data.CREATE TABLE tbl2(id INT, age INT, PRIMARY KEY(id));INSERT INTO tbl2 VALUES (1, 21);Create materialized view logs on the
tbl1andtbl2tables.CREATE MATERIALIZED VIEW LOG ON tbl1 WITH PRIMARY KEY (name) INCLUDING NEW VALUES;CREATE MATERIALIZED VIEW LOG ON tbl2 WITH PRIMARY KEY (age) INCLUDING NEW VALUES;Create the
mv1materialized view based on thetbl1andtbl2tables.CREATE MATERIALIZED VIEW mv1 (PRIMARY KEY (id1, id2)) REFRESH FAST ON DEMAND AS SELECT tbl1.id id1, tbl2.id id2, tbl1.NAME, tbl2.AGE FROM tbl1, tbl2 WHERE tbl1.id = tbl2.id;Create a materialized view log on the
mv1materialized view.CREATE MATERIALIZED VIEW LOG ON mv1 WITH PRIMARY KEY (name, age) INCLUDING NEW VALUES;Create a materialized view (
mv2) based on themv1materialized view.CREATE MATERIALIZED VIEW mv2 REFRESH FAST AS SELECT COUNT(*) cnt, COUNT(AGE) age_cnt, SUM(AGE) age_sum FROM mv1;Query the data in the
mv1materialized view.SELECT * FROM mv1;The returned result is as follows:
+------+------+------+------+ | id1 | id2 | NAME | AGE | +------+------+------+------+ | 1 | 1 | jack | 21 | +------+------+------+------+ 1 row in setQuery the data in the
mv2materialized view.SELECT * FROM mv2;The returned result is as follows:
+------+---------+---------+ | cnt | age_cnt | age_sum | +------+---------+---------+ | 1 | 1 | 21 | +------+---------+---------+ 1 row in setInsert one row of data into the
tbl1andtbl2tables.INSERT INTO tbl1 VALUES (2, 'rose');INSERT INTO tbl2 VALUES (2, 19);Incrementally refresh the
mv1materialized view.CALL dbms_mview.refresh('mv1', 'f');Query the data in the
mv1materialized view.SELECT * FROM mv1;The returned result is as follows:
+------+------+------+------+ | id1 | id2 | NAME | AGE | +------+------+------+------+ | 1 | 1 | jack | 21 | | 2 | 2 | rose | 19 | +------+------+------+------+ 2 rows in setIncrementally refresh the
mv2materialized view.CALL dbms_mview.refresh('mv2', 'f');Query the data in the
mv2materialized view.SELECT * FROM mv2;The returned result is as follows:
+------+---------+---------+ | cnt | age_cnt | age_sum | +------+---------+---------+ | 2 | 2 | 40 | +------+---------+---------+ 1 row in setInsert one row of data into the
tbl1andtbl2tables.INSERT INTO tbl1 VALUES (3, 'mary');INSERT INTO tbl2 VALUES (3, 25);Fully refresh the
mv1materialized view.CALL dbms_mview.refresh('mv1', 'c');Query the data in the
mv1materialized view.SELECT * FROM mv1;The returned result is as follows:
+------+------+------+------+ | id1 | id2 | NAME | AGE | +------+------+------+------+ | 1 | 1 | jack | 21 | | 2 | 2 | rose | 19 | | 3 | 3 | mary | 25 | +------+------+------+------+ 3 rows in setIncrementally refresh the
mv2materialized view.CALL dbms_mview.refresh('mv2', 'f');The returned result is as follows:
ERROR 9760 (HY000): cannot fast refresh materialized viewNotice
Since
mv1has been fully refreshed, an error will occur if you directly incrementally refreshmv2. You must fully refreshmv2first.Query the data in the
mv2materialized view.SELECT * FROM mv2;The returned result is as follows:
+------+---------+---------+ | cnt | age_cnt | age_sum | +------+---------+---------+ | 2 | 2 | 40 | +------+---------+---------+ 1 row in setFully refresh the
mv2materialized view.CALL dbms_mview.refresh('mv2', 'c');Query the data in the
mv2materialized view.SELECT * FROM mv2;The returned result is as follows:
+------+---------+---------+ | cnt | age_cnt | age_sum | +------+---------+---------+ | 3 | 3 | 65 | +------+---------+---------+ 1 row in set
Refresh statistics of materialized views
OceanBase Database can collect and save statistics of materialized view refresh operations, which can be queried by using specific views. Current and historical statistics of materialized view refresh operations are stored in the database. By analyzing historical statistics of materialized view refresh operations, you can understand and analyze the performance of materialized view refreshes in the database.
The statistics of materialized view refreshes serve the following purposes:
Reporting: Provides an overview of current and historical statistics of materialized view refresh operations, including the actual time required for refresh execution, to track and monitor refresh performance.
Diagnostics: Enables effective analysis of materialized view refresh performance by using detailed current and historical statistics. For example, if a materialized view refresh takes a long time, the statistics can help identify whether the performance degradation is due to increased system load or a larger amount of data changes.
Collect statistics of materialized views
OceanBase Database collects statistics of materialized views. You can use the analyze table statement or the call dbms_stats.gather_table_stats('database_name', 'table_name') procedure to collect statistics.
For more information about how to collect statistics of tables and columns, see GATHER_TABLE_STATS.
For more information about how to manage the collection and retention of statistics of materialized view refresh operations, see DBMS_MVIEW_STATS overview.
View the refresh information of materialized views
| View | Description |
|---|---|
| DBA_MVIEWS | Displays information about materialized views. |
| DBA_MVREF_STATS_SYS_DEFAULTS | System-wide default values for the statistics attributes of materialized view refresh history. |
| DBA_MVREF_STATS_PARAMS | Displays the refresh statistics attributes associated with each materialized view. |
| DBA_MVREF_RUN_STATS | Displays information about each refresh run of a materialized view, identified by REFRESH_ID. |
| DBA_MVREF_STATS | Displays basic timing statistics for materialized view refreshes. |
| DBA_MVREF_CHANGE_STATS | Displays statistics related to materialized view refreshes. |
| DBA_MVREF_STMT_STATS | Displays information associated with refresh statements. |
| DBA_SCHEDULER_JOBS | Displays information about all scheduler jobs in the database. |
