You are on page 1of 21

Materialized view

A materialized view is a database object that contains the results of a query. They are local copies of data located remotely, or are used to create summary tables based on aggregations of a table's data. Materialized views, which store data based on remote tables are also, now as snapshots. A materialized view can query tables, views, and other materialized views. !ollectively these are called master tables "a replication term# or detail tables "a data warehouse term#. $or replication purposes, materialized views allow you to maintain copies of remote data on your local node. These copies are read%only. &f you want to update the local copies, you have to use the Advanced 'eplication feature. (ou can select data from a materialized view as you would from a table or view. $or data warehousing purposes, the materialized views commonly created are aggregate views, single%table aggregate views, and join views. &n this article, we shall see how to create a Materialized )iew and discuss 'efresh *ption of the view. &n replication environments, the materialized views commonly created are primary ey, rowid, and sub query materialized views. Primary Key Materialized Views The following statement creates the primary% ey materialized view on the table emp located on a remote database. +,-. !'/AT/ MAT/'&A-&0/1 )&/2 mv3emp3p '/$'/+4 $A+T +TA'T 2&T4 +(+1AT/ 5/6T +(+1AT/ 7 89:; 2&T4 <'&MA'( =/( A+ +/-/!T > $'*M emp?remote3db@ Materialized view created. 5oteA 2hen you create a materialized view using the $A+T option you will need to create a view log on the master tables"s# as shown belowA +,-. !'/AT/ MAT/'&A-&0/1 )&/2 -*B *5 emp@ Materialized view log created. Rowid Materialized Views The following statement creates the rowid materialized view on table emp located on a remote databaseA +,-. !'/AT/ MAT/'&A-&0/1 )&/2 mv3emp3rowid '/$'/+4 2&T4 '*2&1 <age 8 of C8

A+ +/-/!T > $'*M emp?remote3db@ Materialized view log created. Subquery Materialized Views The following statement creates a subquery materialized view based on the emp and dept tables located on the remote databaseA +,-. !'/AT/ MAT/'&A-&0/1 )&/2 mv3empdept A+ +/-/!T > $'*M emp?remote3db e 24/'/ /6&+T+ "+/-/!T > $'*M dept?remote3db d 24/'/ e.dept3no D d.dept3no# '/$'/+4 !-AE+/ Frefresh FfastGcompleteGforceH Fon demand G commitH Fstart with dateH FneIt dateH Fwith Jprimary eyGrowidKHH The refresh option specifiesA The refresh method used by *racle to refresh data in materialized view, whether the view is primary ey based or row%id based. The time and interval at which the view is to be refreshed. Refresh Method - !ST "lause The $A+T refreshes use the materialized view logs "as seen above# to send the rows that have changed from master tables to the materialized view. (ou should create a materialized view log for the master tables if you specify the '/$'/+4 $A+T clause. +,-. !'/AT/ MAT/'&A-&0/1 )&/2 -*B *5 emp@ Materialized view log created. Materialized views are not eligible for fast refresh if the defined subquery contains an analytic function. Refresh Method - "#MP$%T% "lause The complete refresh re%creates the entire materialized view. &f you request a complete refresh, *racle performs a complete refresh even if a fast refresh is possible. Refresh Method - #R"% "lause

<age C of C8

2hen you specify a $*'!/ clause, *racle will perform a fast refresh if one is possible or a complete refresh otherwise. &f you do not specify a refresh method "$A+T, !*M<-/T/, or $*'!/#, $*'!/ is the default. PR&M!R' K%' and R#(&) "lause 2&T4 <'&MA'( =/( is used to create a primary ey materialized view i.e. the materialized view is based on the primary ey of the master table instead of '*2&1 "for '*2&1 clause#. <'&MA'( =/( is the default option. To use the <'&MA'( =/( clause you should have defined <'&MA'( =/( on the master table or else you should use '*2&1 based materialized views. <rimary ey materialized views allow materialized view master tables to be reorganized without affecting the eligibility of the materialized view for fast refresh. 'owid materialized views should have a single master table and cannot contain any of the followingA 1istinct or aggregate functions B'*E< L( +ubqueries , Moins N +et operations Timing the refresh The +TA'T 2&T4 clause tells the database when to perform the first replication from the master table to the local base table. &t should evaluate to a future point in time. The 5/6T clause specifies the interval between refreshes +,-. !'/AT/ MAT/'&A-&0/1 )&/2 mv3emp3p '/$'/+4 $A+T +TA'T 2&T4 +(+1AT/ 5/6T +(+1AT/ 7 C 2&T4 <'&MA'( =/( A+ +/-/!T > $'*M emp?remote3db@ Materialized view created. &n the above eIample, the first copy of the materialized view is made at +(+1AT/ and the interval at which the refresh has to be performed is every two days. +ummary Materialized )iews thus offer us fleIibility of basing a view on <rimary ey or '*2&1, specifying refresh methods and specifying time of automatic refreshes. **********************************************************3 8.O Materialized )iewsA A bit of bac ground & confess a wea ness for Materialized )iews. &t stri es me that they are amongst the cleverest, neatest, most productive features *racle has ever come up with, and they continue to impress me every time & use them, even though theyPve been around for many, many *racle versions "including a stint in ancient versions as something nown as a Qsnapshot tableP#. &f youPve not really wor ed with materialized views before, that older name for them gives a better idea to their true nature and function than the much seIier%sounding Qmaterialized viewP oneA they <age R of C8

are snapshots of data in QrealP tables as at a particular point of time. 2hatPs more "and their real reason for eIisting#, the snapshot that is stored can be the result of a compleI join or a set of aggregations of data. +o, for eIample, a very simple eIample might beA create materialized view emp3dept3mv as select e.empno, e.ename, d.dname, d.loc, e.sal from scott.emp e, scott.dept d where e.deptnoDd.deptno@ 5ote firstly that the object uses American spelling, so whereas & refer to them as QmaterialisedP, the +,- syntaI demands you use a QzP in their names. +econd, what you have just created here is a new table, in fact %but one which stores the result of a join between two other tables. (ou could actually have achieved almost eIactly the same thing by issuing this command insteadA create table emp3dept3join as select e.empno, e.ename, d.dname, d.loc, e.sal from scott.emp e, scott.dept d where e.deptnoDd.deptno@ &n either case, the select part of the syntaI could get an awful lot more compleI than the trivial eIample & have shown here, and hence the Qsnapshot tableP you create in either case would represent the stored results of more and more costly queries. That, in effect, is the principle reason for wanting to use materialised views in the first placeA they store the results of costly queries, so that you can then select directly from the stored results in the future, without the database having to bear the costs associated with re%performing the original query. Lut, you might reasonably as , if create table as select syntaI can effectively snapshot compleI query results, why was there felt to be a need for some new eIotic segment type called a materialised viewS 2hat can it do that good old !TA+ cannotS 2ell, the answer to that comes in two parts. $irst, with a !TA+ table copy, you have to now the copy eIists, and write your +,- to use it directly. That is, if a user issues a query along the lines of Qselect e.empno, d.loc from emp, dept...P, then the fact that there is an emp3dept3join table in my database is of no consequenceA the user is not as ing to query from that summarisation, so the query is resolved by re%performing the eIpensive join on the original, QrealP, tables. <ractically, that would mean that unless you re%wrote your entire application to be aware of the eIistence of summary !TA+ tables, theyPd never actually get used. A materialised view, however, can be used even if a user writes +,- which appears to reference the real tablesA the databasePs optimiser weighs up the costs of re%performing the joins "and possible aggregations# on the base tables, versus the costs of querying from the materialised view which stores the prior results of performing those operations... and if itPs cheaper to query from the materialised view, the optimiser will re%write the +,- issued by the user, automatically and transparentlyA materialised views could therefore be employed without re%writing a single line of application code. )ery niceT The second reason why materialised views are much more functional than !TA+%copied tables is to do with the fact that any snapshot or copy of a table or tables is bound, sooner or later to get out%of% date and will therefore, presumably, need to be brought bac up%to%date somehow. 2ith a !TA+% table, the only thing you can really do is thisA <age : of C8

truncate table emp_dept_join; insert into emp_dept_join select e.empno, e.ename, d.dname, d.loc, e.sal from scott.emp e, scott.dept d where e.deptno=d.deptno; At this point, of course, you are re%performing the original costly query %and you have to remember to do it manually. &f the base tables on which your copy is based are subject to a reasonable amount of 1M-, youPd behaving to re%perform this sort of synchronization so often, you probably would have been better off not having created the copy table in the first placeT And if you forget to re% synchronize the copy with its base tables, then users whose +,- statements ma e use of the copy table will be receiving inaccurate results. Ly contrast, a Materialized )iew can refresh itself, automatically, and "under certain circumstances# the nature of that refresh can be relatively trivial. &f you create another QeIoticP segment called a materialized view log, then the materialized view can capture the 1M- that gets performed to the original base tablesA the materialized view log is a bit li e a mini%online redo log that stores changes made only to the table its built on. At some point, the contents of the view log can then be QreplayedP to the materialized view itself, thus bringing it completely up%to%date. Must to show you these two ey functions of materialized views in action, herePs a simple eIample. $irst, a few necessary preliminariesA drop user scott cascade; Eser dropped. @?/rdbms/admin/utlsampl 1isconnected from *racle 1atabase 8Og /nterprise /dition 'elease 8O.8.O.C.O % <roduction 2ith the <artitioning, *-A< and 1ata Mining options sqlplus / as sysdba +,-><lusA 'elease 8O.8.O.C.O % <roduction on Mon $eb 8: O;AURA88 COOU !opyright "c# 8V;C, COO:, *racle. All rights reserved. grant create materiali ed !iew, query rewrite to scott@ Brant succeeded. grant select on dba_objects to scott; Brant succeeded. grant ad!isor to scott; Brant succeeded. connect scott/tiger !onnected. <age U of C8

4ere, &Pm clearing out +cott from my database so that & can be sure &Pm wor ing with a clean slate. & then re%create +cott using the utlsampl.sql script provided by *racle in the WrdbmsWadmin directory. & then finally grant the minimum set of privileges necessary to +cott so that the rest of what follows in this article will wor . & will pause at this point to confess that & have been guilty in the past %and in the first drafts of this paper% of simply granting the 1LA role to +cott. &t certainly ma es sure that the eIamples in the articles wor , but it is monstrously bad practice for any 1LA to follow. & should be setting a better eIample than that, so & have resolved that in this and all future papers & will ma e the effort to demonstrate the smallest set of privileges needed to ma e things wor . &n this case, the privileges fall into three groups. The grant of create materialized view and query rewrite are fundamental to what follows. 2ithout them, VVX of this article would be meaningless. The second grant, of select on 1LA3*LM/!T+ is admittedly a bit odd, and not particularly good 1LA practice %but it will let me create a large table with lots of rows and low cardinality for some columns very quic ly. &n a sense, itPs just a cosmetic grant of a privilege for mere convenience, and if you had an alternative table of similar size and cardinality qualities to use instead, you could manage perfectly well without it. The third privilege grant is of advisor, and that is a brand new, 8Og%specific privilege. &f you didnPt do it on your database, then just one "though very important# piece of the article concerning new 8Og functionality wonPt wor for you, but the bul of the article about materialized view functionality in general would still ma e sense. &n any case, my system and object privilege grants have been made, and &Pm ready to begin in earnestA drop table ob purge; drop table ob purge > /''*' at line 8A *'A%OOV:CA table or view does not eIist drop materiali ed !iew ob_sum; drop materiali ed !iew ob_sum > /''*' at line 8A *'A%8COORA materialized view Y+!*TTY.Y*L3+EMY does not eIist &Pve thrown in a couple of drop object 11- statements there as one further way of ensuring &Pm starting with a clean slate. They cause errors the first time you wor through this article, of course, because the first time through, no such objects eIist. +econd and subsequent wor %throughs would proceed without error at this point. create table ob as select " from dba_objects; Table created. alter table ob add #constraint ob_p$ primary $ey#object_id%%; Table altered. <age Z of C8

&'() create materiali ed !iew log on ob with rowid * #owner, object_name, subobject_name, object_id% including new !alues; Materialized view log created. +,-. create materialized view ob3sum C refresh on commit fast R enable query rewrite : as U select owner, count"># as counter from ob Z group by owner@ Materialized view created. & start out by creating a copy of a suitably large tableA 1LA3*LM/!T+ usually has several thousand records in it, so a copy of it called *L should be sufficient for my purposes. & add a primary ey constraint to the copied table, and then add on a materialised view log "so that the eventual materialised view will be able to refresh itself by re%applying base table 1M- thatPs been captured in the log#. $inally, & create the materialised view itself, including a demand that it identifies itself as being available for use if the optimiser is considering rewriting any user queries. -ine C of that piece of +,- also indicates that if a piece of 1M- is performed on the base table *L, then the materialised view is to bring itself up%to%date with that change as soon as it has been committed. 5ote that the materialised view merely records the count of the number of objects owned by each user. &t contains no joins to other tables, in other words, but it does store the results of a fairly hefty piece of summarisation, aggregation, grouping and sorting. 2ePll be able to see what all of that means in practical terms in just a moment, once & have given +cott the ability to inspect the eIecution plans the optimiser generates for his queries. That means & have first to run the utlIplan.sql script that *racle supplies "in 9rdbms9admin# to create a <-A53TAL-/ in +cottPs schemaA +,-. ?SWrdbmsWadminWutlIplan.sql Table created. 5ow & can see what eIecution plans various simple queries will generateA +,-. set autotrace trace eIplain +,-. select count"># from ob C where ownerD'+!*TT'@ /Iecution <lan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% O +/-/!T +TAT/M/5T *ptimizerDA--3'*2+ "!ostDR !ardD8 LytesDRO# 8 O +*'T "ABB'/BAT/# C 8 MAT3)&/2 '/2'&T/ A!!/++ "$E--# *$ '*L3+EM' "MAT3)&/2 '/2'&T/# "!ostDR !ardD8 LytesDRO# 5ote that my query says to select from *L. (et what does the eIecution plan revealS &t shows that we are really accessing the *L3+EM materialized view %and a minor new feature in 8Og is that the reason the query is going to use a completely different segment than the one it actually as ed to use is that there has been a MAT3)&/2 '/2'&T/. This is proof, in other words, that users can issue +,- that thin s itPs going to read from one table, but transparently end up loo ing at another, <age [ of C8

because the optimiser deems it cheaper to do so. That was the first of the two reasons why materialised views are such wonderful segments, youPll recall. +,-. insert into ob "owner, object3name, subobject3name, object3id# C values "'+!*TT','T/+T&5+/'T','5*5/',V;RZU#@ 8 row created. At this point, &Pve just inserted one new record into the base table, *L. & havenPt yet committed that insert. 'emembering that & told my materialised view only to bring itself up%to%date when & commit 1M- performed on the base table, this must mean that my materialised view should now be considered out%of%date. Although it is configurable "though eIplaining how is outside the scope of this article#, materialised views cannot generally be candidates for a bit of query rewriting by the optimiser if they are indeed nown to be out%of%date. My materialised view has therefore just been ruled out of consideration for future query rewrites by my little bit of base table 1M-, and & can test that this is the case easily enoughA +,-. select count"># from ob C where ownerD'+!*TT'@ /Iecution <lan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% O +/-/!T +TAT/M/5T *ptimizerDA--3'*2+ "!ostD8CV !ardD8 LytesD8[# 8 O +*'T "ABB'/BAT/# C 8 TAL-/ A!!/++ "$E--# *$ '*L' "TAL-/# "!ostD8CV !ardDZ LytesD8OC# This is eIactly the same query as & issued before, but this time the eIecution plan reveals that wePre going to select records out of the *L table itself, and not use the *L3+EM materialised view. This is proof therefore that an out%of%date materialised view is dismissed by the optimiser for query rewrite purposes. &ncidentally, you can now see why, when the materialised view is nown to be fully up%to%date, the optimiser is so een on ma ing use of itA the query previously reported a total cost of QRP, whereas if the base table has to be used, the cost shoots up to 8CV. That means my silly, simple, materialised view is nevertheless performing about :O times faster than the base tableA now you understand how these things can be so usefulT +,-. commit@ !ommit complete. select count"># from ob C where ownerD'+!*TT'@ /Iecution <lan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% O +/-/!T +TAT/M/5T *ptimizerDA--3'*2+ "!ostDR !ardD8 LytesDRO# 8 O +*'T "ABB'/BAT/# C 8 MAT3)&/2 '/2'&T/ A!!/++ "$E--# *$ '*L3+EM' "MAT3)&/2 '/2'&T/# "!ostDR !ardD8 LytesDRO# $inally, & commit my bit of pending 1M-, and then immediately re%issue eIactly the same query as before. The eIecution plan this time reveals that the materialised view is bac in business. ThatPs an indication that the commit must have caused the materialised view to bring itself bac up%to%date, at which point itPs a candidate for query rewrites once more. A more direct proof of the second of the <age ; of C8

ey features of materialised views %this ability of theirs to refresh themselves% can be seen easily li e soA +,-. set autotrace off +,-. select count"># from ob where ownerD'+!*TT'@ !*E5T"># %%%%%%%%%% V +,-. select counter from ob3sum where ownerD'+!*TT'@ !*E5T/' %%%%%%%%%% V +o far, at least, the two tablePs count of the number of objects owned by +cott is synchronised. +,-. insert into ob "owner, object3name, subobject3name, object3id# C values "'+!*TT','T/+T&5+/'T','5*5/',V;R[V#@ 8 row created. +,-. select count"># from ob where ownerD'+!*TT'@ !*E5T"># %%%%%%%%%% 8O +,-. select counter from ob3sum where ownerD'+!*TT'@ !*E5T/' %%%%%%%%%% V Lut as a result of the insert of one new record, the *L base tablePs count increases to 8O, whereas the count of objects in the materialised view *L3+EM remains at V. The materialised view is thus visibly PstaleP. +,-. commit@ !ommit complete. +,-. select count"># from ob where ownerD'+!*TT'@ !*E5T"># %%%%%%%%%% 8O +,-. select counter from ob3sum where ownerD'+!*TT'@ <age V of C8

!*E5T/' %%%%%%%%%% 8O *ne commit statement later, however, and the two objectsP counts agree once more. As demanded by the materialised viewPs definition, the commit causes the earlier insert to *L to be replayed to *L3+EM, thus re%synchronising the two objects. *L3+EM is considered QfreshP once more, and hence "as we saw# available for query rewrites. &Pve ta en quite a lot of time and space to eIplain the fundamentals of what materialised views are and how they wor because, without that level of basic understanding, hardly any of the incremental "but very nice# enhancements that we get in 8Og would ma e senseT Armed with that foundation% level nowledge, therefore, letPs now loo specifically at what has changed in 8Og. C.O 1LM+3A1)&+*' !reating materialised views loo s simple enough, at least when you consider the eIamples & used earlier. Lut it isnPt actually that easy. !onsider this simple eIampleA +,-. create materialized view emp3dept3mv C build immediate R refresh fast : enable query rewrite U as Z select e.ename, d.dname [ from emp e, dept d ; where e.deptnoDd.deptno@ from emp e, dept d > /''*' at line [A *'A%8COUCA cannot fast refresh materialized view +!*TT./M<31/<T3M) This is not the worldPs most compleI select statement, & thin you will agreeT (et it obviously contains sufficient compleIity to prevent a fast%refreshable materialised view being created based on it. This, indeed, has been one bugbear that has bedevilled attempts to implement materialised views in previous *racle versionsA their seemingly irrational disli e of being fast%refreshed "which, of course, they have to be able to do if they are to be ept nice and fresh at minimal cost#. All sorts of simple factors would trip them up and result in this sort of error, and it was something of an acquired s ill to wor out which ones were interfering at any one time. $ortunately, thatPs practically a thing of the past in 8Og. 2e have a new pac age 1LM+3A1)&+*' and a new procedure within that pac age called TE5/3M)&/2, which will not only ma e it clear why a proposed materialised view canPt be created, but will give you the +,- statements actually needed to create itT 4erePs how & might sort out that troublesome materialised view aboveA +,-. var hjr varcharC"RO# begin C dbms3advisor.tune3mview"Ahjr, R 'create materialized view emp3dept3mv build immediate refresh fast enable : query rewrite as select e.ename, d.dname from emp e, <age 8O of C8

U dept d where e.deptnoDd.deptno'#@ Z end@ [9 <-9+,- procedure successfully completed. The first line here simply declares a new bind variable, called hjr "you can call it anything you li e, of courseT#. ThatPs to act as the first of the TE5/3M)&/2+ parametersA it becomes the unique identifier for the eIplanations about how to ma e this materialised view wor when you inspect the relevant table. After that, you simply invo e the TE5/3M)&/2 procedure supplying the bind variable identifier and the eIact teIt of the proposed Qcreate materialized viewP +,- statement. *racle thin s about it for a moment or two, and then tells you the procedure finished successfully. At this point, you can inspect its wor li e soA set long ROOO set pagesize ROOO set linesize 8RC select > from user3tune3mview@ *25/' TA+=35AM/ A!T&*53&1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% +!'&<T3T(</ %%%%%%%%%%%%%% +TAT/M/5T %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +!*TT TA+=3U [ &M<-/M/5TAT&*5 !'/AT/ MAT/'&A-&0/1 )&/2 -*B *5 Y+!*TTY.Y1/<TY 2&T4 '*2&1 +!*TT TA+=3U ; &M<-/M/5TAT&*5 A-T/' MAT/'&A-&0/1 )&/2 -*B $*'!/ *5 Y+!*TTY.Y1/<TY A11 '*2&1 +!*TT TA+=3U V &M<-/M/5TAT&*5 !'/AT/ MAT/'&A-&0/1 )&/2 -*B *5 Y+!*TTY.Y/M<Y 2&T4 '*2&1 +!*TT TA+=3U 8O &M<-/M/5TAT&*5 A-T/' MAT/'&A-&0/1 )&/2 -*B $*'!/ *5 Y+!*TTY.Y/M<Y A11 '*2&1 +!*TT TA+=3U 88 &M<-/M/5TAT&*5 !'/AT/ MAT/'&A-&0/1 )&/2 +!*TT./M<31/<T3M) build immediate '/$'/+4 $A+T 2&T4 '* 2&1 /5AL-/ ,E/'( '/2'&T/ A+ +/-/!T +!*TT./M<.'*2&1 !8, +!*TT.1/<T.'*2&1 !C, Y+!* TTY.Y1/<TY.Y15AM/Y M8, Y+!*TTY.Y/M<Y.Y/5AM/Y MC $'*M +!*TT./M<, +!*TT.1/<T 24/'/ +!*TT.1/<T.1/<T5* D +!*TT./M<.1/<T5* <age 88 of C8

+!*TT TA+=3U 8C E51* 1'*< MAT/'&A-&0/1 )&/2 +!*TT./M<31/<T3M) Z rows selected. $irst of all, note how & set the +,-><lus \-*5B] environment variable to a suitably large figureA the +TAT/M/5T column in this view returns a !-*L, and therefore the teIt will be truncated unless you do that before you start. The other QsetP commands stop lines wrapping and page brea s cluttering up the display of the query results. +econdly, notice how the new E+/'3TE5/3M)&/2 view "therePs a 1LA3 equivalent, naturally# contains "in this case# five +,- statements which need to be issued to ma e the proposed materialised view actually wor able. There is also a siIth statement, which shows how you would drop the materialised view after it gets createdT &n theory, you could simply cut and paste each of the statements in turn "bar the last one, of courseT# into a +,- session, and that would get the materialised view created. Lut thirdA notice that these statements are all related to each other by being identified with the one Qtas nameP %in my case, they are all part of TA+=3U. & can use that information as an input to yet another new 8Og procedure that will generate a +,- script consisting of these individual +,statements for me, li e soA +,-. connect 9 as sysdba !onnected. +,-. create directory M(1&' as '!AW'@ 1irectory created. +,-. grant read, write on directory mydir to scott@ Brant succeeded. +,-. connect scott9tiger !onnected. +,-. eIec "dbms3advisor.get3tas 3script"'TA+=3U'#,'M(1&'','$&6M/.T6T'# <-9+,- procedure successfully completed. dbms3advisor.create3file

The first thing & did here was to ma e a quic detour to +(+Ps schema, so that & could create a new directory object. That will allow the database to write a teIt file out to the file system. & then granted a couple of object privileges to +cott so that he can actually ma e use of the new directory object. *bviously, if a directory object already eIists in your database, to which you have appropriate read and write access, then therePs no need to create a new one just to get this process wor ing. 2ith the directory object in place, & logged bac on as +cott and invo ed the 1LM+3A1)&+*' pac age once more, but this time its !'/AT/3$&-/ procedure. That ta es three essential arguments@ the tas name & mentioned earlier, the name of the directory object the +,- script is to be written to, and the desired name of the +,- script itself. 2hen this is eIecuted, *racle sweeps up <age 8C of C8

all +,- statements found in the E+/'3TE5/3M)&/2 view that share the specified tas name, and outputs them all to a teIt file that loo s a bit li e thisA host type cAWfiIme.tIt 'em +,- Access AdvisorA )ersion 8O.8.O.8 % <roduction 'em 'em EsernameA +!*TT 'em Tas A TA+=3U 'em /Iecution dateA 'em set feedbac 8 set linesize ;O set trimspool on set tab off set pagesize ZO whenever sqlerror !*5T&5E/ !'/AT/ MAT/'&A-&0/1 )&/2 -*B *5 Y+!*TTY.Y1/<TY 2&T4 '*2&1 @ A-T/' MAT/'&A-&0/1 )&/2 -*B $*'!/ *5 Y+!*TTY.Y1/<TY A11 '*2&1 @ !'/AT/ MAT/'&A-&0/1 )&/2 -*B *5 Y+!*TTY.Y/M<Y 2&T4 '*2&1 @ A-T/' MAT/'&A-&0/1 )&/2 -*B $*'!/ *5 Y+!*TTY.Y/M<Y A11 '*2&1 @ !'/AT/ MAT/'&A-&0/1 )&/2 +!*TT./M<31/<T3M) '/$'/+4 $A+T 2&T4 '*2&1 /5AL-/ ,E/'( '/2'&T/ A+ +/-/!T +!*TT./M<.'*2&1 !8, +!*TT.1/<T.'*2&1 !C, Y+!*TTY.Y1/<TY.Y15AM/Y M8 Y+!*TTY.Y/M<Y.Y/5AM/Y MC $'*M +!*TT./M<, +!*TT.1/<T 24/'/ +!*TT.1/<T.1/<T5* D +!*TT./M<.1/<T5*@ whenever sqlerror /6&T +,-.+,-!*1/ begin dbms3advisor.mar 3recommendation"'TA+=3U',8,'&M<-/M/5T/1'#@ end@ 9 <age 8R of C8

TherePs nothing particularly clever hereA the +,- statements have been wrapped up nicely and formatted beautifully, of course. Lut otherwise, therePs nothing much here you couldnPt have gotten by simply cutting and pasting direct from E+/'3TE5/3M)&/2... eIcept for that last statement, which will change the +!'&<T3T(</ column in the E+/'3TE5/3M)&/2 column from &M<-/M/5TAT&*5 to &M<-/M/5T/1 %thus allowing you to distinguish between +,statements in that view which still need to be performed and those which have been performed. *f course, if you choose the cut%and%paste straight from the view technqiue, therePs nothing to stop you eIecuting something li e that last line yourself and achieving eIactly the same outcome. &n my case, having created a file called $&6M/.T6T, & can eIecute it as a +,- script li e soA +,-. ?!AWfiIme.tIt Materialized view log created. Materialized view log altered. Materialized view log created. Materialized view log altered. Materialized view created. <-9+,- procedure successfully completed. And suddenly, what had been impossible to create at the start of this section has clearly been created without fussA +,-. select > from emp3dept3mv@ !8 !C M8 MC %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% %%%%%%%%%% AAA<IoAA/AAAAAcAAA AAA<ImAA/AAAAAMAAL '/+/A'!4 +M&T4 AAA<IoAA/AAAAAcAAL AAA<ImAA/AAAAAMAA! +A-/+ A--/5 AAA<IoAA/AAAAAcAA! AAA<ImAA/AAAAAMAA! +A-/+ 2A'1 AAA<IoAA/AAAAAcAA1 AAA<ImAA/AAAAAMAAL '/+/A'!4 M*5/+ AAA<IoAA/AAAAAcAA/ AAA<ImAA/AAAAAMAA! +A-/+ MA'T&5 AAA<IoAA/AAAAAcAA$ AAA<ImAA/AAAAAMAA! +A-/+ L-A=/ AAA<IoAA/AAAAAcAAB AAA<ImAA/AAAAAMAAA A!!*E5T&5B !-A'= AAA<IoAA/AAAAAcAA4 AAA<ImAA/AAAAAMAAL '/+/A'!4 +!*TT AAA<IoAA/AAAAAcAA& AAA<ImAA/AAAAAMAAA A!!*E5T&5B =&5B AAA<IoAA/AAAAAcAAM AAA<ImAA/AAAAAMAA! +A-/+ TE'5/' AAA<IoAA/AAAAAcAA= AAA<ImAA/AAAAAMAAL '/+/A'!4 A1AM+ AAA<IoAA/AAAAAcAA- AAA<ImAA/AAAAAMAA! +A-/+ MAM/+ AAA<IoAA/AAAAAcAAM AAA<ImAA/AAAAAMAAL '/+/A'!4 $*'1 AAA<IoAA/AAAAAcAA5 AAA<ImAA/AAAAAMAAA A!!*E5T&5B M&--/' &t might not loo pretty %but at least it eIistsT (ou now, it is quite often the little, insignficant new features which go to ma e a new *racle version a must%have upgrade... and my belief is that 1LM+3A1)&+*'.TE5/3M)&/2 is one of them for 8Og. & myself have spent many a long hour, frustrated and irritated, at the intractable mysteries of getting materialised views to behave... and now here we have something that will write <age 8: of C8

the precise +,- statements needed to ma e it happen for you. That is, in a word, wonderful, if you as me. &n practice, it means those many sites who have not implemented materialised views as well or as comprehensively as they could have done because of the compleIity of doing so now have no eIcuse... and can eIpect a performance dividend accordingly. And one final wordA remember that the before you can ma e use of the 1LM+3A1)&+*' pac age, you need to be granted the new 8Og A1)&+*' system privilege "itPs number %CZR in the +(+T/M3<'&)&-/B/3MA< view if youPre interestedT# R.O Miscellaneous /nhancements R.8 '/2'&T/3*'3/''*' 4int The other enhancements to materialised views that 8Og brings are, by comparison, and in my estimation, much less significant, so & wonPt spend too much time discussing them here. *ne of the nice ones is thisA select 9>7 '/2'&T/3*'3/''*' >9 count"># from ob where ownerD'+!*TT'@ ThatPs a new hint which requires of the optimiser that it either re%writes a query so that it definitely uses the materialised view, or it raises an error and aborts the whole thing. Thus, using one of my earlier eIamples, & get thisA +,-. select 9>7 '/2'&T/3*'3/''*' >9 count"># from ob where ownerD'+!*TT'@ !*E5T"># %%%%%%%%%% 8O 8 row selected. ...and because of the hint there, & now without even loo ing that this query must have been re% written to use the *L3+EM materialised view. A final bit of proofA +,-. insert into ob "owner, object3name, subobject3name, object3id# C values "'+!*TT','T/+T&5+/'T','5*5/',V;R;O#@ 8 row created. +,-. select 9>7 '/2'&T/3*'3/''*' >9 count"># from ob where ownerD'+!*TT'@ select 9>7 '/2'&T/3*'3/''*' >9 count"># from ob where ownerD'+!*TT' > /''*' at line 8A *'A%RORVRA a query bloc in the statement did not rewrite 1isconnected from *racle 1atabase 8Og /nterprise /dition 'elease 8O.8.O.C.O % <roduction 2ith the <artitioning, *-A< and 1ata Mining options

<age 8U of C8

4ere, &Pve inserted another new row into the *L base table. That means "as we saw earlier# the materialised view is now stale and cannot be used for query rewrite purposes. 2hen & therefore re% issue the hinted select statement, this time it raises an error... and unceremoniously dumps me bac to the operating system whilst itPs at it, you might note. &Pm not convinced that the hint should actually cause a session to die li e that %to my way of thin ing, that's a bit drasticT% but at least the base table wasnPt actually used for the queryT That is a fairly major new feature in some respectsA what we have here is, for the first time, a mechanism which actively prevents the use of the base table for the query "in Vi, we only had a mechanism to prevent the use of the materialised view#. Biven that materialised views are li ely to be created as summaries and aggregates of huge tables in a data warehouse, the ability to prevent an inadvertent access to the huge base tables is capable of saving a massive amount of unwanted9unnecessary wor on the database. 1efinitely a good thing, therefore. Must be warned that if a query could potentially be re%written so that it refers to two or more materialised views, and the optimiser successfully uses just one of those materialised views, that counts as a successful re%write, and thus the error isnPt triggered... even though by not accessing the other materialised view, the query is now "presumably# doing massively eIpensive access to at least one base table. +tillA half a loaf is better than no bread whatever, so letPs not complain. R.C More $ast 'efreshes As &Pve mentioned elsewhere in this article, it has always been tric ier than it perhaps should have been to persuade a materialised view to fast refresh. All sorts of little things would stop them being able to do soA in ;i, for eIample, if you used the +,- eyword E5&*5 in your materialised viewPs defining select statement, that was enough to ill fast refreshing in its trac s. That particular restriction on when you could fast refresh was lifted in Vi, and 8Og continues the trend of removing obstacles which prevent fast refreshes from being possible. $or eIample, a materialised view that joins a table to itself can now be fast refreshable@ as can a materialised view built on a select statement that uses an inline view in the $'*M clause of the defining select statement. And so on and on... & wonPt bore you with the complete list of new occasions when fast refreshes are possible, because itPs tedious in the eItreme, and theyPre all accompanied by lots of caveats and provisos in any case. The general point, & thin , should simply be left at thisA more materialised views will be able to fast refresh in 8Og than in any previous *racle version. ThatPs good enough for me, at any rate. R.R 'eliable and !heaper 'efreshes 'efreshing a materialised view is, almost by definition, an eIpensive jobA we create them in the first place because the query they represent is considered eIpensive, yet refreshing them must inevitably require us to re%eIecute precisely that same eIpensive queryT This can be eItremely bad news indeed when you set about creating multiple summarisations of your base data %in other words, when you create multiple materialised views on the same base tables% because each and every one of them, when they refresh, will have to perform what we can assume will be massively eIpensive queries. At least, that was the way things were in Vi. $ortunately, the eIpense issue is somewhat alleviated in 8Og because it is now possible for a materialised view to be refreshed by having the query it is built on re%written so that the data can come from other materialised views rather than direct from the eIpensive%to%query base tables. <age 8Z of C8

The subtlety of this point is easily lost, so &Pll reiterate it in case you missed itT A materialised view is usually created as a selection of columns from base tables, but the optimiser in 8Og is willing to re% writing the very query that defines the contents of materialised view so that fresh data can be sourced from other materialised views, not the base tables themselves. &f a table has several materialised views built on it, for eIample, each a different form of summarisation compared with the rest "imagine summarising sales data by day, wee , month, quarter, state, region, store, salesman and so on#, then potentially only one of them has to be refreshed by going bac to the base table itselfA all the others could conceivably get their fresh data from that one source%refreshed materialised view. &f so, that would ma e refreshing the bul of the materialised views enormously cheaper. /Icellent newsT 5aturally, therePs a catchT To now that a summarisation of sales data by wee "say# can give you the data needed to refresh a summarisation of sales by month, you have to now that wee s are related to months. *racle has no such chronological understanding innately %but youPve been able to tell it about such relationships for many versions by creating objects called dimensions. Trouble is, dimensions are not enforced in the databaseA they merely declare that a relationship eIistsA nobody and nothing actually bothers to chec that itPs true. +imilarly, it has long been possible to create foreign and primary ey constraints which arenPt actually enabled, but which are merely flagged as being QreliableP "by setting the '/-( flag for them, in factT#. That is another form of merely declaring a relationship or quality to eIist, rather than having the database prove it for certain. 2ell, the catch with materialised views being able to refresh themselves from other materialised views is that %by default% they will ignore any relationship that is merely declared to eIist. Enless itPs strictly enforced "and dimensions, for eIample, simply cannot be#, then the optimiser wonPt use that relationship to determine whether a query rewrite for refresh purposes can ta e place. <ut into simple words, that means a materialised view of sales by month would not be able to use a materialised view summarising sales by wee as its source for a refresh because the dimension :alhing *racle that wee s and months are related is ign red8[by the optimiser for the refresh operatioj. That is good in one sense. An enforced relationship is nown, absolutely, to be accurate and reliable. A trusted relataojs"ip is only as reliable as the 1LA t"at set the '/-( flagT &f a materialised view were to use a trUsted relati9nship as the ^asis of determining where it shoudd get its fresh data from, and that relationship was in fact badly defined, or violated left, right and centre by the data, then the contents of the refreshed materialised view would end up logically corrupt. Esing only enforced relationships means that canPt happen. Lut the downside is that to definitely enforce a primary ey, for eIample, youPre going to need an indeIA and in a 1ata 2arehouse, thatPs not going to be a trivial little indeI. &tPs going to be a thumping great monster that consume huge amounts of dis space, and lots of !<E cycles as it is created and maintained. And as for dimensionsA well, they are only ever tpusted relationshiOs, so the default, striat policy meanR thXy can nevXr influence the refresh mechanism. $ortUnately, this behaviour is configurable, gtherwise the new feature of materialised tiews refr Xshing other materialised views would be a pretty lame one. +o, although the use of only genuifely% enforced relationshhps is t"e default bdhaviouC in 8Og, it can be changed li e soA cCeate iaterialized view +A-/+M) <age 8[ of C8

refresh complete on demand using trusted constraints as select wea no, sum"sales# NOom sales group by wee no@

<age 8; of C8

...and the magic words t"ere are E+&5B T'E+T/1 !*5+T'A&5T+. ThatPs the opposite of the default setting, which hs E+&

<age 8V of C8

B /5$*'!/1 !*5+T'A&5T+.

<age CO of C8

Trying to sum up a subtle and compleI point in as few words as possible, thereforeA /5$5'!/1 !*5+T'A&5T+ is the default setting, and means matdrialised view refreshes only use totally, 8OOX peliable information as the source of their data when they get refreshed. Lut some relationships "dimensions are the classic eIample# can never be used to influence the query rewriting process with this set. And other relationships may be very costly to genuinely enforce "indeIes on primary eys, for eIample#. (ou gain reliability at the cost of performance, basically. &f you use T'E+T/1 !*5+T'A&5T+, by contrast, then things li e dimensions really can be used to influence the rewriting process, and performance will probably be better without massive indeIes "for eIample# slowing you down. 'ewrites are more li ely to happen at this setting, too, so maintenance of the materialised views themselves will be quic er and cheaper. Lut this setting does mean, remember, that the contents of the materialised views are only as good as the competence of the 1LA who declares relationships to be trustworthy in the first place. &f he or she gets it wrong, your materialised views are effectively corrupt and theyPll need to be rebuilt from scratch at some point "which is, of course, a very eIpensive operation#. :.O !onclusion &Pll leave this discussion of 8Og new features for materialised views there, not because there arenPt any more of them "there areT# but because they are all infinitely more obscure than even the last point there about the trusted versus enforced constraints settingT These things are really important to 1ata 2arehouse specialists, but whenever they start discussing them, they ris leaving those of us who arenPt in that particular line of business scratching our heads wondering what language these people are tal ingT &f the subtleties of some of those miscellaneous new features passed you by, therefore, donPt panic. !ontent yourself, perhaps, with the thought that they simply mean materialised views got smarter, subtler and cheaper to use in 8Og. 'emember too the real punch%line for materialised views in 8OgA than s to 1LM+3A1)&+*', they practically write themselves these days, so you really donPt need to be a master of syntaI peculiarities to ma e use of them. That is, & again remind you, in my opinion at least practically worth the upgrade license fees by itselfT

<age C8 of C8