Basic Materialized Views
-
Upload
bala-kulandai -
Category
Documents
-
view
21 -
download
0
description
Transcript of Basic Materialized Views
-
Home(https://docs.oracle.com/)/Database(https://docs.oracle.com/en/database/)/OracleDatabaseOnlineDocumentation11gRelease1(11.1)(../../index.htm)/DataWarehousingandBusinessIntelligence(../../nav/portal_6.htm)
DatabaseDataWarehousingGuide
()
()()
8()BasicMaterializedViewsThischapterdescribestheuseofmaterializedviews.Itcontainsthefollowingtopics:
OverviewofDataWarehousingwithMaterializedViews
TypesofMaterializedViews
CreatingMaterializedViews
RegisteringExistingMaterializedViews
ChoosingIndexesforMaterializedViews
DroppingMaterializedViews
AnalyzingMaterializedViewCapabilities
()
OverviewofDataWarehousingwithMaterializedViews()()()Typically,dataflowsfromoneormoreonlinetransactionprocessing(OLTP)databaseintoadatawarehouseonamonthly,weekly,ordailybasis.Thedataisnormallyprocessedina()stagingfile(glossary.htm#i997125)before
(//docs.oracle.com/en/)
SignIn(http://www.oracle.com/webapps/redirect/signon?nexturl=http://docs.oracle.com/cd/B28359_01/server.111/b28313/basicmv.htm)
-
beingaddedtothedatawarehouse.Datawarehousescommonlyrangeinsizefromtensofgigabytestoafewterabytes.Usually,thevastmajorityofthedataisstoredinafewverylargefacttables.
Onetechniqueemployedindatawarehousestoimproveperformanceisthecreationofsummaries.Summariesarespecialtypesofaggregateviewsthatimprovequeryexecutiontimesbyprecalculatingexpensivejoinsandaggregationoperationspriortoexecutionandstoringtheresultsinatableinthedatabase.Forexample,youcancreateasummarytabletocontainthesumsofsalesbyregionandbyproduct.
ThesummariesoraggregatesthatarereferredtointhisbookandinliteratureondatawarehousingarecreatedinOracleDatabaseusingaschemaobjectcalled()amaterializedview(glossary.htm#i997008).Materializedviewscanperformanumberofroles,suchasimprovingqueryperformanceorprovidingreplicateddata.
Inthepast,organizationsusingsummariesspentasignificantamountoftimeandeffortcreatingsummariesmanually,identifyingwhichsummariestocreate,indexingthesummaries,updatingthem,andadvisingtheirusersonwhichonestouse.Theintroductionofsummarymanagementeasedtheworkloadofthedatabaseadministratorandmeanttheusernolongerneededtobeawareofthesummariesthathadbeendefined.Thedatabaseadministratorcreatesoneormorematerializedviews,whicharetheequivalentofasummary.Theenduserqueriesthetablesandviewsatthedetaildatalevel.ThequeryrewritemechanismintheOracleserverautomaticallyrewritestheSQLquerytousethesummarytables.Thismechanismreducesresponsetimeforreturningresultsfromthequery.Materializedviewswithinthedatawarehousearetransparenttotheenduserortothedatabaseapplication.
Althoughmaterializedviewsareusuallyaccessedthroughthequeryrewritemechanism,anenduserordatabaseapplicationcanconstructqueriesthatdirectlyaccessthematerializedviews.However,seriousconsiderationshouldbegiventowhetherusersshouldbeallowedtodothisbecauseanychangetothematerializedviewswillaffectthequeriesthatreferencethem.
()
MaterializedViewsforDataWarehousesIndatawarehouses,youcanusematerializedviewstoprecomputeandstoreaggregateddatasuchasthesumofsales.Materializedviewsintheseenvironmentsareoftenreferredtoassummaries,becausetheystoresummarizeddata.Theycanalsobeusedtoprecomputejoinswithorwithoutaggregations.Amaterializedvieweliminatestheoverheadassociatedwithexpensivejoinsandaggregationsforalargeorimportantclassofqueries.
()
MaterializedViewsforDistributedComputing
-
Indistributedenvironments,youcanusematerializedviewstoreplicatedataatdistributedsitesandtosynchronizeupdatesdoneatthosesiteswithconflictresolutionmethods.Thesereplicamaterializedviewsprovidelocalaccesstodatathatotherwisewouldhavetobeaccessedfromremotesites.Materializedviewsarealsousefulinremotedatamarts.SeeOracleDatabaseAdvancedReplication(../../server.111/b28326/toc.htm)andOracleDatabaseHeterogeneousConnectivityAdministrator'sGuide(../../server.111/b28277/toc.htm)fordetailsondistributedandmobilecomputing.
()
MaterializedViewsforMobileComputingYoucanalsousematerializedviewstodownloadasubsetofdatafromcentralserverstomobileclients,withperiodicrefreshesandupdatesbetweenclientsandthecentralservers.
Thischapterfocusesontheuseofmaterializedviewsindatawarehouses.SeeOracleDatabaseAdvancedReplication(../../server.111/b28326/toc.htm)andOracleDatabaseHeterogeneousConnectivityAdministrator'sGuide(../../server.111/b28277/toc.htm)fordetailsondistributedandmobilecomputing.
()
TheNeedforMaterializedViewsYoucanusematerializedviewstoincreasethespeedofqueriesonverylargedatabases.Queriestolargedatabasesofteninvolvejoinsbetweentables,aggregationssuchasSUM ,orboth.Theseoperationsareexpensiveintermsoftimeandprocessingpower.Thetypeofmaterializedviewyoucreatedetermineshowthematerializedviewisrefreshedandusedbyqueryrewrite.
Materializedviewsimprovequeryperformancebyprecalculatingexpensivejoinandaggregationoperationsonthedatabasepriortoexecutionandstoringtheresultsinthedatabase.Thequeryoptimizerautomaticallyrecognizeswhenanexistingmaterializedviewcanandshouldbeusedtosatisfyarequest.Itthentransparentlyrewritestherequesttousethematerializedview.Queriesgodirectlytothematerializedviewandnottotheunderlyingdetailtables.Ingeneral,rewritingqueriestousematerializedviewsratherthandetailtablesimprovesresponsetime.Figure81illustrateshowqueryrewriteworks.
()Figure81TransparentQueryRewrite
-
Descriptionof"Figure81TransparentQueryRewrite"(./img_text/dwhsg027.htm)
Whenusingqueryrewrite,creatematerializedviewsthatsatisfythelargestnumberofqueries.Forexample,ifyouidentify20queriesthatarecommonlyappliedtothedetailorfacttables,thenyoumightbeabletosatisfythemwithfiveorsixwellwrittenmaterializedviews.Amaterializedviewdefinitioncanincludeanynumberofaggregations(SUM ,COUNT(x) ,COUNT(*) ,COUNT(DISTINCTx) ,AVG ,VARIANCE ,STDDEV ,MIN ,andMAX ).Itcanalsoincludeanynumberofjoins.Ifyouareunsureofwhichmaterializedviewstocreate,OracleprovidestheSQLAccessAdvisor,whichisasetofadvisoryprocedure()sintheDBMS_ADVISOR packagetohelpindesigningandevaluatingmaterializedviewsforqueryrewrite.
Ifamaterializedviewistobeusedbyqueryrewrite,itmustbestoredinthesamedatabaseasthedetailtablesonwhichitrelies.Amaterializedviewcanbepartitioned,andyoucandefineamaterializedviewonapartitionedtable.Youcanalsodefineoneormoreindexesonthematerializedview.
Unlikeindexes,materializedviewscanbeaccesseddirectlyusingaSELECTstatement.However,itisrecommendedthatyoutrytoavoidwritingSQLstatementsthatdirectlyreferencethematerializedview,becausethenitisdifficulttochangethemwithoutaffectingtheapplication.Instead,letqueryrewritetransparentlyrewriteyourquerytousethematerializedview.
Notethatthetechniquesshowninthischapterillustratehowtousematerializedviewsindatawarehouses.MaterializedviewscanalsobeusedbyOracleReplication.SeeOracleDatabaseAdvancedReplication(../../server.111/b28326/toc.htm)forfurtherinformation.
()
ComponentsofSummaryManagementSummary()managementconsistsof:
-
TableofContents(toc.htm)OracleDatabase(toc.htm)
Preface(preface.htm)What'sNewinOracleDatabase?(whatsnew.htm)DataWarehousingConcepts(concept.htm)LogicalDesigninDataWarehouses(logical.htm)PhysicalDesigninDataWarehouses(physical.htm)HardwareandI/OConsiderationsinDataWarehouses(hardware.htm)
PartitioninginDataWarehouses(parpart.htm)Indexes(indexes.htm)IntegrityConstraints(constra.htm)BasicMaterializedViews(basicmv.htm)AdvancedMaterializedViews(advmv.htm)Dimensions(dimen.htm)OverviewofExtraction,Transformation,andLoading(ettover.htm)ExtractioninDataWarehouses(extract.htm)TransportationinDataWarehouses(transport.htm)LoadingandTransformation(transform.htm)MaintainingtheDataWarehouse(refresh.htm)ChangeDataCapture(cdc.htm)BasicQueryRewrite(qrbasic.htm)AdvancedQueryRewrite(qradv.htm)SchemaModelingTechniques(schemas.htm)SQLforAggregationinDataWarehouses(aggreg.htm)SQLforAnalysisandReporting(analysis.htm)SQLforModeling(sqlmodel.htm)OLAPandDataMining(bi.htm)AdvancedBusinessIntelligenceQueries(advbi.htm)UsingParallelExecution(usingpe.htm)Glossary(glossary.htm)
CategoriesHome(../../index.htm)BookList(../../nav/portal_booklist.htm)DataDictionary(../../nav/catalog_views.htm)SQLKeywords(../../nav/sql_keywords.htm)Acronyms(../../nav/acronym_list.htm)InitializationParameters(../../nav/initora.htm)ErrorMessages(../../nav/lookup.htm?id=ERRMG)
Download
Mechanismstodefinematerializedviewsanddimensions.
Arefreshmechanismtoensurethatallmaterializedviewscontainthelatestdata.
Aqueryrewritecapabilitytotransparentlyrewriteaquerytouseamaterializedview.
TheSQLAccessAdvisor,whichrecommendsmaterializedviews,partitions,andindexestocreate.
TUNE_MVIEW ,whichshowsyouhowtomakeyourmaterializedviewfastrefreshableandusegeneralqueryrewrite.
Theuseofsummarymanagementfeaturesimposesnoschemarestrictions,andcanenablesomeexistingDSSdatabaseapplicationstoimproveperformancewithouttheneedtoredesignthedatabaseortheapplication.
Figure82illustratestheuseofsummarymanagementinthewarehousingcycle.Afterthedatahasbeentransformed,staged,andloadedintothedetaildatainthewarehouse,youcaninvokethesummarymanagementprocess.First,usetheSQLAccessAdvisortoplanhowyouwillusematerializedviews.Then,creatematerializedviewsanddesignhowquerieswillberewritten.IfyouarehavingproblemstryingtogetyourmaterializedviewstoworkthenuseTUNE_MVIEW toobtainanoptimizedmaterializedview.
()Figure82OverviewofSummaryManagement
-
Descriptionof"Figure82OverviewofSummaryManagement"(./img_text/dwhsg071.htm)
Understandingthesummarymanagementprocessduringtheearlieststagesofdatawarehousedesigncanyieldlargedividendslaterintheformofhigherperformance,lowersummaryadministrationcosts,andreducedstoragerequirements.
()
DataWarehousingTerminologySomebasicdatawarehousingtermsaredefinedasfollows:
()()()()Dimensiontablesdescribethebusinessentitiesofanenterprise,representedashierarchical,categoricalinformationsuchastime,departments,locations,andproducts.Dimensiontablesaresometimescalled()lookupor()referencetables.
-
Dimensiontablesusuallychangeslowlyovertimeandarenotmodifiedonaperiodicschedule.Theyareusedinlongrunningdecisionsupportqueriestoaggregatethedatareturnedfromthequeryintoappropriatelevelsofthedimensionhierarchy.
Hierarchiesdescribethebusinessrelationshipsandcommonaccesspatternsinthedatabase.Ananalysisofthedimensions,combinedwithanunderstandingofthetypicalworkload,canbeusedtocreatematerializedviews.SeeChapter10,"Dimensions"(dimen.htm#g1011059)formoreinformation.
()()()Facttablesdescribethebusinesstransactionsofanenterprise.
ThevastmajorityofdatainadatawarehouseisstoredinafewverylargefacttablesthatareupdatedperiodicallywithdatafromoneormoreoperationalOLTPdatabases.
Facttablesinclud()efacts(alsocalledmeasures)suchassales,units,andinventory.
Asimplemeasureisanumericorcharactercolumnofonetablesuchasfact.sales .
Acomputedmeasureisanexpressioninvolvingmeasuresofonetable,forexample,fact.revenues fact.expenses .
Amultitablemeasureisacomputedmeasuredefinedonmultipletables,forexample,fact_a.revenues fact_b.expenses .
Facttablesalsocontainoneormoreforeign()keysthatorganizethebusinesstransactionsbytherelevantbusinessentitiessuchastime,product,andmarket.Inmostcases,theseforeignkeysarenonnull,formauniquecompoundkeyofthefacttable,andeachforeignkeyjoinswithexactlyonerowofa()dimensiontable(glossary.htm#i996883).
Amaterializedviewisaprecomputedtablecomprisingaggregatedandjoineddatafromfactandpossiblyfromdimensiontables.Amongbuildersofdatawarehouses,amaterializedviewisalsoknownasasummary(glossary.htm#i997158).
()
()()MaterializedViewSchemaDesign
-
Summarymanagement()canperformmanyusefulfunctions,includingqueryrewriteandmaterializedviewrefresh,evenifyourdatawarehousedesigndoesnotfollowtheseguidelines.However,youwillrealizesignificantlygreaterqueryexecutionperformanceandmaterializedviewrefreshperformancebenefitsandyouwillrequirefewermaterializedviewsifyourschemadesigncomplieswiththeseguidelines.
Amaterializedviewdefinitionincludesanynumberofaggregates,aswellasanynumberofjoins.Inseveralways,amaterializedviewbehaveslikeanindex:
Thepurposeofamaterializedviewistoincreasequeryexecutionperformance.
TheexistenceofamaterializedviewistransparenttoSQLapplications,sothatadatabaseadministratorcancreateordropmaterializedviewsatanytimewithoutaffectingthevalidityofSQLapplications.
Amaterializedviewconsumesstoragespace.
Thecontentsofthematerializedviewmustbeupdatedwhentheunderlyingdetailtablesaremodified.
()
SchemasandDimensionTablesInthecaseofnormalizedorpartiallynormalizeddimensiontables(adimensionthatisstoredinmorethanonetable),identifyhowthesetablesarejoined.Notewhetherthejoinsbetweenthedimensiontablescanguaranteethateachchildsiderowjoinswithoneandonlyoneparentsiderow.Inthecaseofdenormalizeddimensions,determinewhetherthechildsidecolumnsuniquelydeterminetheparentside(orattribute)columns.Theserelationshipscanbeenabledwithconstraints,usingtheNOVALIDATE andRELY optionsiftherelationshipsrepresentedbytheconstraintsareguaranteedbyothermeans.Notethatifthejoinsbetweenfactanddimensiontablesdonotsupporttheparentchildrelationshipdescribedpreviously,youstillgainsignificantperformanceadvantagesfromdefiningthedimensionwiththeCREATEDIMENSION statement.Anotheralternative,subjecttosomerestrictions,istouseouterjoinsinthematerializedviewdefinition(thatis,intheCREATEMATERIALIZED VIEW statement).
Youmustnotcreatedimensionsinanyschemathatdoesnotsatisfytheserelationships.Incorrectresultscanbereturnedfromqueriesotherwise.
()
-
MaterializedViewSchemaDesignGuidelinesBeforestartingtodefineandusethevariouscomponentsofsummarymanagement,youshouldreviewyourschemadesigntoabidebythefollowingguidelineswhereverpossible.
Guidelines1and2aremoreimportantthanguideline3.Ifyourschemadesigndoesnotfollowguidelines1and2,itdoesnotthenmatterwhetheritfollowsguideline3.Guidelines1,2,and3affectbothqueryrewriteperformanceandmaterializedviewrefreshperformance.
()()Table81SchemaDesignGuidelines
SchemaGuideline Description
Guideline1
Dimensions
Dimensionsshouldeitherbedenormalized(eachdimensioncontainedinonetable)orthejoinsbetweentablesinanormalizedorpartiallynormalizeddimensionshouldguaranteethateachchildsiderowjoinswithexactlyoneparentsiderow.Thebenefitsofmaintainingthisconditionaredescribedin"CreatingDimensions"(dimen.htm#i1006266).
YoucanenforcethisconditionbyaddingFOREIGN KEY andNOTNULL constraintsonthechildsidejoinkeysandPRIMARY KEY constraintsontheparentsidejoinkeys.
Guideline2
Dimensions
Ifdimensionsaredenormalizedorpartiallydenormalized,hierarchicalintegritymustbemaintainedbetweenthekeycolumnsofthedimensiontable.Eachchildkeyvaluemustuniquelyidentifyitsparentkeyvalue,evenifthedimensiontableisdenormalized.HierarchicalintegrityinadenormalizeddimensioncanbeverifiedbycallingtheVALIDATE_DIMENSION procedureoftheDBMS_DIMENSIONpackage.
Guideline3
Dimensions
Factanddimensiontablesshouldsimilarlyguaranteethateachfacttablerowjoinswithexactlyonedimensiontablerow.Thisconditionmustbedeclared,andoptionallyenforced,byaddingFOREIGN KEY andNOT NULLconstraintsonthefactkeycolumn(s)andPRIMARY KEYconstraintsonthedimensionkeycolumn(s),orbyusingouterjoins.Inadatawarehouse,constraintsaretypicallyenabledwiththeNOVALIDATE andRELY clausestoavoidconstraintenforcementperformanceoverhead.SeeOracleDatabaseSQLLanguageReference(../../server.111/b28286/toc.htm)forfurtherdetails.
-
Guideline4
IncrementalLoads
IncrementalloadsofyourdetaildatashouldbedoneusingtheSQL*Loaderdirectpathoption,oranybulkloaderutilitythatusesOracle'sdirectpathinterface.ThisincludesINSERT ...ASSELECT withtheAPPEND orPARALLELhints,wherethehintscausethedirectloaderlogtobeusedduringtheinsert.SeeOracleDatabaseSQLLanguageReference(../../server.111/b28286/toc.htm)and"TypesofMaterializedViews"formoreinformation.
Guideline5
Partitions
Range/compositepartitionyourtablesbyamonotonicallyincreasingtimecolumnifpossible(preferablyoftypeDATE ).
Guideline6
Dimensions
Aftereachloadandbeforerefreshingyourmaterializedview,usetheVALIDATE_DIMENSION procedureoftheDBMS_DIMENSION packagetoincrementallyverifydimensionalintegrity.
Guideline7
TimeDimensions
Ifatimedimensionappearsinthematerializedviewasatimecolumn,partitionandindexthematerializedviewinthesamemannerasyouhavethefacttables.
Ifyouareconcernedwiththetimerequiredtoenableconstraintsandwhetheranyconstraintsmightbeviolated,thenusetheENABLE NOVALIDATE withtheRELY clausetoturnonconstraintcheckingwithoutvalidatinganyoftheexistingconstraints.Theriskwiththisapproachisthatincorrectqueryresultscouldoccurifanyconstraintsarebroken.Therefore,asthedesigner,youmustdeterminehowcleanthedataisandwhethertheriskofincorrectresultsistoogreat.
()
LoadingDataintoDataWarehousesApopularandefficientwaytoloaddataintoadatawarehouseordatamartistouseSQL*LoaderwiththeDIRECT orPARALLEL option,DataPump,ortouseanotherloadertoolthatusestheOracledirectpathAPI.SeeOracleDatabaseUtilities(../../server.111/b28319/ldr_concepts.htm#SUTIL003)fortherestrictionsandconsiderationswhenusingSQL*LoaderwiththeDIRECT orPARALLELkeywords.
-
Loadingstrategiescanbeclassifiedasonephaseortwophase.Inonephaseloading,dataisloadeddirectlyintothetargettable,qualityassurancetestsareperformed,anderrorsareresolvedbyperformingDMLoperationspriortorefreshingmaterializedviews.Ifalargenumberofdeletionsarepossible,thenstorageutilizationcanbeadverselyaffected,buttemporaryspacerequirementsandloadtimeareminimized.
Inatwophaseloadingprocess:
Dataisfirstloadedintoatemporarytableinthewarehouse.
Qualityassuranceproceduresareappliedtothedata.
Referentialintegrityconstraintsonthetargettablearedisabled,andthelocalindexinthetargetpartitionismarkedunusable.
ThedataiscopiedfromthetemporaryareaintotheappropriatepartitionofthetargettableusingINSERT AS SELECT withthePARALLEL orAPPENDhint.Thetemporarytableisthendropped.Alternatively,ifthetargettableispartitioned,youcancreateanew(empty)partitioninthetargettableanduseALTERTABLE...EXCHANGEPARTITION toincorporatethetemporarytableintothetargettable.SeeOracleDatabaseSQLLanguageReference(../../server.111/b28286/toc.htm)formoreinformation.
Theconstraintsareenabled,usuallywiththeNOVALIDATE option.
Immediatelyafterloadingthedetaildataandupdatingtheindexesonthedetaildata,thedatabasecanbeopenedforoperation,ifdesired.YoucandisablequeryrewriteatthesystemlevelbyissuinganALTER SYSTEM SETQUERY_REWRITE_ENABLED =FALSE statementuntilallthematerializedviewsarerefreshed.
IfQUERY_REWRITE_INTEGRITY issettoSTALE_TOLERATED ,accesstothematerializedviewcanbeallowedatthesessionleveltoanyuserswhodonotrequirethematerializedviewstoreflectthedatafromthelatestloadbyissuinganALTER SESSION SET QUERY_REWRITE_ENABLED =TRUE statement.ThisscenariodoesnotapplywhenQUERY_REWRITE_INTEGRITY iseitherENFORCED orTRUSTED becausethesystemensuresinthesemodesthatonlymaterializedviewswithupdateddataparticipateinaqueryrewrite.
()
OverviewofMaterializedViewManagementTasks
-
Themotivationforusingmaterializedviewsistoimproveperformance,buttheoverheadassociatedwithmaterializedviewmanagementcanbecomeasignificantsystemmanagementproblem.Whenreviewingorevaluatingsomeofthenecessarymaterializedviewmanagementactivities,considersomeofthefollowing:
Identifyingwhatmaterializedviewstocreateinitially.
Indexingthematerializedviews.
Ensuringthatallmaterializedviewsandmaterializedviewindexesarerefreshedproperlyeachtimethedatabaseisupdated.
Checkingwhichmaterializedviewshavebeenused.
Determininghoweffectiveeachmaterializedviewhasbeenonworkloadperformance.
Measuringthespacebeingusedbymaterializedviews.
Determiningwhichnewmaterializedviewsshouldbecreated.
Determiningwhichexistingmaterializedviewsshouldbedropped.
Archivingolddetailandmaterializedviewdatathatisnolongeruseful.
Aftertheinitialeffortofcreatingandpopulatingthedatawarehouseordatamart,themajoradministrationoverheadistheupdateprocess,whichinvolves:
Periodicextractionofincrementalchangesfromtheoperationalsystems.
Transformingthedata.
Verifyingthattheincrementalchangesarecorrect,consistent,andcomplete.
Bulkloadingthedataintothewarehouse.
Refreshingindexesandmaterializedviewssothattheyareconsistentwiththedetaildata.
-
Theupdateprocessmustgenerallybeperformedwithinalimitedperiodoftimeknownasthe()updatewindow(glossary.htm#i997213).Theupdatewindowdependsonthe()updatefrequency(glossary.htm#i997216)(suchasdailyorweekly)andthenatureofthebusiness.Foradailyupdatefrequency,anupdatewindowoftwotosixhoursmightbetypical.
Youneedtoknowyourupdatewindowforthefollowingactivities:
Loadingthedetaildata
Updatingorrebuildingtheindexesonthedetaildata
Performingqualityassurancetestsonthedata
Refreshingthematerializedviews
Updatingtheindexesonthematerializedviews
()
TypesofMaterializedViews()TheSELECT clauseinthematerializedviewcreationstatementdefinesthedatathatthematerializedviewistocontain.Onlyafewrestrictionslimitwhatcanbespecified.Anynumberoftablescanbejoinedtogether.Besidestables,otherelementssuchasviews,inlineviews(subqueriesintheFROM clauseofaSELECT statement),subqueries,andmaterializedviewscanallbejoinedorreferencedintheSELECT clause.Youcannot,however,defineamaterializedviewwithasubqueryintheSELECT listofthedefiningquery.Youcan,however,includesubquerieselsewhereinthedefiningquery,suchasintheWHERE clause.
Thetypesofmaterializedviewsare:
MaterializedViewswithAggregates
MaterializedViewsContainingOnlyJoins
NestedMaterializedViews
()
MaterializedViewswith()AggregatesIn()datawarehouses,materializedviewsnormallycontainaggregatesasshowninExample81.Forfastrefreshtobepossible,theSELECT listmustcontainalloftheGROUP BY columns(ifpresent),andtheremustbea
-
COUNT(*) andaCOUNT(column) onanyaggregatedcolumns.Also,materializedviewlogsmustbepresentonalltablesreferencedinthequerythatdefinesthematerializedview.Thevalidaggregatefunctionsare:SUM ,COUNT(x) ,COUNT(*) ,AVG ,VARIANCE ,STDDEV ,MIN ,andMAX ,andtheexpressiontobeaggregatedcanbeanySQLvalueexpression.See"RestrictionsonFastRefreshonMaterializedViewswithAggregates".
FastrefreshforamaterializedviewcontainingjoinsandaggregatesispossibleafteranytypeofDMLtothebasetables(directloadorconventionalINSERT ,UPDATE ,orDELETE ).ItcanbedefinedtoberefreshedON COMMIT orONDEMAND .AREFRESHON COMMIT materializedviewwillberefreshedautomaticallywhenatransactionthatdoesDMLtooneofthematerializedview'sdetailtablescommits.Thetimetakentocompletethecommitmaybeslightlylongerthanusualwhenthismethodischosen.Thisisbecausetherefreshoperationisperformedaspartofthecommitprocess.Therefore,thismethodmaynotbesuitableifmanyusersareconcurrentlychangingthetablesuponwhichthematerializedviewisbased.
Herearesomeexamplesofmaterializedviewswithaggregates.Notethatmaterializedviewlogsareonlycreatedbecausethismaterializedviewwillbefastrefreshed.
()Example81Example1:CreatingaMaterializedView
CREATEMATERIALIZEDVIEWLOGONproductsWITHSEQUENCE,ROWID(prod_id,prod_name,prod_desc,prod_subcategory,prod_subcategory_desc,prod_category,prod_category_desc,prod_weight_class,prod_unit_of_measure,prod_pack_size,supplier_id,prod_status,prod_list_price,prod_min_price)INCLUDINGNEWVALUES;
CREATEMATERIALIZEDVIEWLOGONsalesWITHSEQUENCE,ROWID(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amount_sold)INCLUDINGNEWVALUES;
CREATEMATERIALIZEDVIEWproduct_sales_mvPCTFREE0TABLESPACEdemoSTORAGE(INITIAL8kNEXT8kPCTINCREASE0)BUILDIMMEDIATEREFRESHFASTENABLEQUERYREWRITEASSELECTp.prod_name,SUM(s.amount_sold)ASdollar_sales,COUNT(*)AScnt,COUNT(s.amount_sold)AScnt_amtFROMsaless,productspWHEREs.prod_id=p.prod_idGROUPBYp.prod_name;
-
Thisexamplecreatesamaterializedviewproduct_sales_mv thatcomputestotalnumberandvalueofsalesforaproduct.Itisderivedbyjoiningthetablessales andproducts onthecolumnprod_id .Thematerializedviewispopulatedwithdataimmediatelybecausethebuildmethodisimmediateanditisavailableforusebyqueryrewrite.Inthisexample,thedefaultrefreshmethodisFAST ,whichisallowedbecausetheappropriatematerializedviewlogshavebeencreatedontablesproducts andsales .
()Example82Example2:CreatingaMaterializedView
CREATEMATERIALIZEDVIEWproduct_sales_mvPCTFREE0TABLESPACEdemoSTORAGE(INITIAL16kNEXT16kPCTINCREASE0)BUILDDEFERREDREFRESHCOMPLETEONDEMANDENABLEQUERYREWRITEASSELECTp.prod_name,SUM(s.amount_sold)ASdollar_salesFROMsaless,productspWHEREs.prod_id=p.prod_idGROUPBYp.prod_name;
Thisexamplecreatesamaterializedviewproduct_sales_mv thatcomputesthesumofsalesbyprod_name .Itisderivedbyjoiningthetablessales andproducts onthecolumnprod_id .Thematerializedviewdoesnotinitiallycontainanydata,becausethebuildmethodisDEFERRED .Acompleterefreshisrequiredforthefirstrefreshofabuilddeferredmaterializedview.Whenitisrefreshedandoncepopulated,thismaterializedviewcanbeusedbyqueryrewrite.
()Example83Example3:CreatingaMaterializedView
CREATEMATERIALIZEDVIEWLOGONsalesWITHSEQUENCE,ROWID(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amount_sold)INCLUDINGNEWVALUES;
CREATEMATERIALIZEDVIEWsum_salesPARALLELBUILDIMMEDIATEREFRESHFASTONCOMMITASSELECTs.prod_id,s.time_id,COUNT(*)AScount_grp,SUM(s.amount_sold)ASsum_dollar_sales,COUNT(s.amount_sold)AScount_dollar_sales,SUM(s.quantity_sold)ASsum_quantity_sales,COUNT(s.quantity_sold)AScount_quantity_salesFROMsalessGROUPBYs.prod_id,s.time_id;
-
Thisexamplecreatesamaterializedviewthatcontainsaggregatesonasingletable.Becausethematerializedviewloghasbeencreatedwithallreferencedcolumnsinthematerializedview'sdefiningquery,thematerializedviewisfastrefreshable.IfDMLisappliedagainstthesales table,thenthechangeswillbereflectedinthematerializedviewwhenthecommitisissued.
()
RequirementsforUsingMaterializedViewswithAggregatesTable82illustratestheaggregaterequirementsformaterializedviews.IfaggregateX ispresent,aggregateY isrequiredandaggregateZ isoptional.
()()Table82RequirementsforMaterializedViewswithAggregates
X Y Z
COUNT(expr) - -
MIN(expr)
MAX(expr)
SUM(expr) COUNT(expr) -
SUM(col) ,colhasNOT NULLconstraint
AVG(expr) COUNT(expr) SUM(expr)
STDDEV(expr) COUNT(expr)SUM(expr) SUM(expr*expr)
VARIANCE(expr) COUNT(expr)SUM(expr) SUM(expr*expr)
NotethatCOUNT(*) mustalwaysbepresenttoguaranteealltypesoffastrefresh.Otherwise,youmaybelimitedtofastrefreshafterinsertsonly.OraclerecommendsthatyouincludetheoptionalaggregatesincolumnZ inthematerializedviewinordertoobtainthemostefficientandaccuratefastrefreshoftheaggregates.
-
()
MaterializedViews()ContainingOnlyJoinsSomematerializedviewscontainonlyjoinsandnoaggregates,suchasinExample84,whereamaterializedviewiscreatedthatjoinsthesales tabletothetimes andcustomers tables.Theadvantageofcreatingthistypeofmaterializedviewisthatexpensivejoinswillbeprecalculated.
FastrefreshforamaterializedviewcontainingonlyjoinsispossibleafteranytypeofDMLtothebasetables(directpathorconventionalINSERT ,UPDATE ,orDELETE ).
AmaterializedviewcontainingonlyjoinscanbedefinedtoberefreshedONCOMMIT orON DEMAND .IfitisON COMMIT ,therefreshisperformedatcommittimeofthetransactionthatdoesDMLonthematerializedview'sdetailtable.
IfyouspecifyREFRESH FAST ,Oracleperformsfurtherverificationofthequerydefinitiontoensurethatfastrefreshcanbeperformedifanyofthedetailtableschange.Theseadditionalchecksare:
AmaterializedviewlogmustbepresentforeachdetailtableunlessthetablesupportsPCT.Also,whenamaterializedviewlogisrequired,theROWIDcolumnmustbepresentineachmaterializedviewlog.
TherowidsofallthedetailtablesmustappearintheSELECT listofthematerializedviewquerydefinition.
Ifsomeoftheserestrictionsarenotmet,youcancreatethematerializedviewasREFRESH FORCE totakeadvantageoffastrefreshwhenitispossible.Ifoneofthetablesdidnotmeetallofthecriteria,buttheothertablesdid,thematerializedviewwouldstillbefastrefreshablewithrespecttotheothertablesforwhichallthecriteriaaremet.
()
MaterializedJoinViewsFROMClauseConsiderations
Ifthematerializedviewcontainsonlyjoins,theROWID columnsforeachtable(andeachinstanceofatablethatoccursmultipletimesintheFROM list)mustbepresentintheSELECT listofthematerializedview.
IfthematerializedviewhasremotetablesintheFROM clause,alltablesintheFROM clausemustbelocatedonthatsamesite.Further,ON COMMIT refreshisnotsupportedformaterializedviewwithremotetables.Materializedviewlogs
-
mustbepresentontheremotesiteforeachdetailtableofthematerializedviewandROWID columnsmustbepresentintheSELECT listofthematerializedview,asshowninthefollowingexample.
()Example84MaterializedViewContainingOnlyJoins
CREATEMATERIALIZEDVIEWLOGONsalesWITHROWID;CREATEMATERIALIZEDVIEWLOGONtimesWITHROWID;CREATEMATERIALIZEDVIEWLOGONcustomersWITHROWID;CREATEMATERIALIZEDVIEWdetail_sales_mvPARALLELBUILDIMMEDIATEREFRESHFASTASSELECTs.rowid"sales_rid",t.rowid"times_rid",c.rowid"customers_rid",c.cust_id,c.cust_last_name,s.amount_sold,s.quantity_sold,s.time_idFROMsaless,timest,customerscWHEREs.cust_id=c.cust_id(+)ANDs.time_id=t.time_id(+);
Alternatively,ifthepreviousexampledidnotincludethecolumnstimes_ridandcustomers_rid ,andiftherefreshmethodwasREFRESH FORCE ,thenthismaterializedviewwouldbefastrefreshableonlyifthesalestablewasupdatedbutnotifthetablestimes orcustomers wereupdated.
CREATEMATERIALIZEDVIEWdetail_sales_mvPARALLELBUILDIMMEDIATEREFRESHFORCEASSELECTs.rowid"sales_rid",c.cust_id,c.cust_last_name,s.amount_sold,s.quantity_sold,s.time_idFROMsaless,timest,customerscWHEREs.cust_id=c.cust_id(+)ANDs.time_id=t.time_id(+);
()
NestedMaterializedViews()()Anestedmaterializedviewisamaterializedviewwhosedefinitionisbasedonanothermaterializedview.Anestedmaterializedviewcanreferenceotherrelationsinthedatabaseinadditiontoreferencingmaterializedviews.
()
WhyUseNestedMaterializedViews?Inadatawarehouse,youtypicallycreatemanyaggregateviewsonasinglejoin(forexample,rollupsalongdifferentdimensions).Incrementallymaintainingthesedistinctmaterializedaggregateviewscantakealongtime,becausetheunderlyingjoinhastobeperformedmanytimes.
-
Usingnestedmaterializedviews,youcancreatemultiplesingletablematerializedviewsbasedonajoinsonlymaterializedviewandthejoinisperformedjustonce.Inaddition,optimizationscanbeperformedforthisclassofsingletableaggregatematerializedviewandthusrefreshisveryefficient.
()Example85NestedMaterializedView
Youcancreateanestedmaterializedviewonmaterializedviews,butallparentandbasematerializedviewsmustcontainjoinsoraggregates.Ifthedefiningqueriesforamaterializedviewdonotcontainjoinsoraggregates,itcannotbenested.Alltheunderlyingobjects(materializedviewsortables)onwhichthematerializedviewisdefinedmusthaveamaterializedviewlog.Alltheunderlyingobjectsaretreatedasiftheyweretables.Inaddition,youcanusealltheexistingoptionsformaterializedviews.
Usingthetablesandtheircolumnsfromthesh sampleschema,thefollowingmaterializedviewsillustratehownestedmaterializedviewscanbecreated.
CREATEMATERIALIZEDVIEWLOGONsalesWITHROWID;CREATEMATERIALIZEDVIEWLOGONcustomersWITHROWID;CREATEMATERIALIZEDVIEWLOGONtimesWITHROWID;
/*creatematerializedviewjoin_sales_cust_timeasfastrefreshableatCOMMITtime*/CREATEMATERIALIZEDVIEWjoin_sales_cust_timeREFRESHFASTONCOMMITASSELECTc.cust_id,c.cust_last_name,s.amount_sold,t.time_id,t.day_number_in_week,s.rowidsrid,t.rowidtrid,c.rowidcridFROMsaless,customersc,timestWHEREs.time_id=t.time_idANDs.cust_id=c.cust_id;
Tocreateanestedmaterializedviewonthetablejoin_sales_cust_time ,youwouldhavetocreateamaterializedviewlogonthetable.Becausethiswillbeasingletableaggregatematerializedviewonjoin_sales_cust_time ,youneedtologallthenecessarycolumnsandusetheINCLUDING NEWVALUES clause.
-
/*creatematerializedviewlogonjoin_sales_cust_time*/CREATEMATERIALIZEDVIEWLOGONjoin_sales_cust_timeWITHROWID(cust_last_name,day_number_in_week,amount_sold)INCLUDINGNEWVALUES;
/*createthesingle-tableaggregatematerializedviewsum_sales_cust_timeonjoin_sales_cust_timeasfastrefreshableatCOMMITtime*/CREATEMATERIALIZEDVIEWsum_sales_cust_timeREFRESHFASTONCOMMITASSELECTCOUNT(*)cnt_all,SUM(amount_sold)sum_sales,COUNT(amount_sold)cnt_sales,cust_last_name,day_number_in_weekFROMjoin_sales_cust_timeGROUPBYcust_last_name,day_number_in_week;
()
NestingMaterializedViewswithJoinsandAggregatesSometypesofnestedmaterializedviewscannotbefastrefreshed.UseEXPLAIN_MVIEW toidentifythosetypesofmaterializedviews.Youcanrefreshatreeofnestedmaterializedviewsintheappropriatedependencyorderbyspecifyingthenested=TRUE parameterwiththeDBMS_MVIEW.REFRESHparameter.Forexample,ifyoucallDBMS_MVIEW.REFRESH('SUM_SALES_CUST_TIME',nested=>TRUE) ,theREFRESH procedurewillfirstrefreshthejoin_sales_cust_timematerializedview,andthenrefreshthesum_sales_cust_time materializedview.
()
NestedMaterializedViewUsageGuidelinesYoushouldkeepthefollowinginmindwhendecidingwhethertousenestedmaterializedviews:
Ifyouwanttousefastrefresh,youshouldfastrefreshallthematerializedviewsalonganychain.
Ifyouwantthehighestlevelmaterializedviewtobefreshwithrespecttothedetailtables,youneedtoensurethatallmaterializedviewsinatreearerefreshedinthecorrectdependencyorderbeforerefreshingthehighestlevel.Youcanautomaticallyrefreshintermediatematerializedviewsinanestedhierarchyusingthenested=TRUE parameter,asdescribedin"NestingMaterializedViewswithJoinsandAggregates".Ifyoudonotspecifynested=TRUE andthematerializedviewsunderthehighestlevelmaterializedviewarestale,refreshingonlythehighestlevelwillsucceed,butmakesitfreshonlywithrespecttoitsunderlyingmaterializedview,notthedetailtablesatthebaseofthetree.
-
Whenrefreshingmaterializedviews,youneedtoensurethatallmaterializedviewsinatreearerefreshed.Ifyouonlyrefreshthehighestlevelmaterializedview,thematerializedviewsunderitwillbestaleandyoumustexplicitlyrefreshthem.IfyouusetheREFRESH procedurewiththenestedparametervaluesettoTRUE ,onlyspecifiedmaterializedviewsandtheirchildmaterializedviewsinthetreearerefreshed,andnottheirtoplevelmaterializedviews.UsetheREFRESH_DEPENDENT procedurewiththenestedparametervaluesettoTRUE ifyouwanttoensurethatallmaterializedviewsinatreearerefreshed.
Freshnessofamaterializedviewiscalculatedrelativetotheobjectsdirectlyreferencedbythematerializedview.Whenamaterializedviewreferencesanothermaterializedview,thefreshnessofthetopmostmaterializedviewiscalculatedrelativetochangesinthematerializedviewitdirectlyreferences,notrelativetochangesinthetablesreferencedbythematerializedviewitreferences.
()
RestrictionsWhenUsingNestedMaterializedViews()()Youcannotcreatebothamaterializedviewandaprebuiltmaterializedviewonthesametable.Forexample,Ifyouhaveatablecosts withamaterializedviewcost_mv basedonit,youcannotthencreateaprebuiltmaterializedviewontablecosts .Theresultwouldmakecost_mv anestedmaterializedviewandthismethodofconversionisnotsupported.
()
CreatingMaterializedViews()AmaterializedviewcanbecreatedwiththeCREATE MATERIALIZED VIEWstatementorusingEnterpriseManager.Example86illustratescreatinganmaterializedviewcalledcust_sales_mv .
()Example86CreatingaMaterializedView
-
CREATEMATERIALIZEDVIEWcust_sales_mvPCTFREE0TABLESPACEdemoSTORAGE(INITIAL16kNEXT16kPCTINCREASE0)PARALLELBUILDIMMEDIATEREFRESHCOMPLETEENABLEQUERYREWRITEASSELECTc.cust_last_name,SUM(amount_sold)ASsum_amount_soldFROMcustomersc,salessWHEREs.cust_id=c.cust_idGROUPBYc.cust_last_name;
Itisnotuncommoninadatawarehousetohavealreadycreatedsummaryoraggregationtables,andyoumightnotwishtorepeatthisworkbybuildinganewmaterializedview.Inthiscase,thetablethatalreadyexistsinthedatabasecanberegisteredasa()()prebuiltmaterializedview.Thistechniqueisdescribedin"RegisteringExistingMaterializedViews".
Onceyouhaveselectedthematerializedviewsyouwanttocreate,followthesestepsforeachmaterializedview.
1. Designthematerializedview.Existinguserdefinedmaterializedviewsdonotrequirethisstep.Ifthematerializedviewcontainsmanyrows,then,ifappropriate,thematerializedviewshouldbepartitioned(ifpossible)andshouldmatchthepartitioningofthelargestormostfrequentlyupdateddetailorfacttable(ifpossible).Refreshperformancebenefitsfrompartitioning,becauseitcantakeadvantageofparallelDMLcapabilitiesandpossiblePCTbasedrefresh.
2. UsetheCREATE MATERIALIZED VIEW statementtocreateand,optionally,populatethematerializedview.Ifauserdefinedmaterializedviewalreadyexists,thenusetheON PREBUILT TABLE clauseintheCREATEMATERIALIZED VIEW statement.Otherwise,usetheBUILD IMMEDIATEclausetopopulatethematerializedviewimmediately,ortheBUILDDEFERRED clausetopopulatethematerializedviewlater.ABUILDDEFERRED materializedviewisdisabledforusebyqueryrewriteuntilthefirstCOMPLETE REFRESH ,afterwhichitwillbeautomaticallyenabled,providedtheENABLE QUERY REWRITE clausehasbeenspecified.
SeeAlso:()()()OracleDatabaseSQLLanguageReference(../../server.111/b28286/toc.htm)fordescriptionsoftheSQLstatementsCREATE MATERIALIZED VIEW , ALTER MATERIALIZEDVIEW ,and DROP MATERIALIZED VIEW
-
()
CreatingMaterializedViewswithColumnAliasListsCurrently,whenamaterializedviewiscreated,ifitsdefiningquerycontainssamenamecolumnsintheSELECT list,thenameconflictsneedtoberesolvedbyspecifyinguniquealiasesforthosecolumns.Otherwise,theCREATEMATERIALIZED VIEW statementwillfailwiththeerrormessagesofcolumnsambiguouslydefined.However,thestandardmethodofattachingaliasesintheSELECT clausefornameresolutionrestrictstheuseofthefulltextmatchqueryrewriteanditwilloccuronlywhenthetextofthematerializedview'sdefiningqueryandthetextofuserinputqueryareidentical.Thus,iftheuserspecifiesselectaliasesinthematerializedview'sdefiningquerywhilethereisnoaliasinthequery,thefulltextmatchcomparisonwillfail.ThisisparticularlyaproblemforqueriesfromDiscoverer,whichmakesextensiveuseofcolumnaliases.
Thefollowingisanexampleoftheproblem.sales_mv iscreatedwithcolumnaliasesintheSELECT clausebuttheinputqueryQ1 doesnothavethealiases.Thefulltextmatchrewritewillfail.Thematerializedviewisasfollows:
CREATEMATERIALIZEDVIEWsales_mvENABLEQUERYREWRITEASSELECTs.time_idsales_tid,c.time_idcosts_tidFROMsaless,productsp,costscWHEREs.prod_id=p.prod_idANDc.prod_id=p.prod_idANDp.prod_nameIN(SELECTprod_nameFROMproducts);
InputquerystatementQ1 isasfollows:
SELECTs.time_id,c.time_idFROMsaless,productsp,costscWHEREs.prod_id=p.prod_idANDc.prod_id=p.prod_idANDp.prod_nameIN(SELECTprod_nameFROMproducts);
Eventhoughthematerializedview'sdefiningqueryisalmostidenticalandlogicallyequivalenttotheuser'sinputquery,queryrewritedoesnothappenbecauseofthefailureoffulltextmatchthatistheonlyrewritepossibilityforsomequeries(forexample,asubqueryintheWHERE clause).
YoucanaddacolumnaliaslisttoaCREATE MATERIALIZED VIEW statement.ThecolumnaliaslistexplicitlyresolvesanycolumnnameconflictwithoutattachingaliasesintheSELECT clauseofthematerializedview.Thesyntaxofthematerializedviewcolumnaliaslistisillustratedinthefollowingexample:
-
CREATEMATERIALIZEDVIEWsales_mv(sales_tid,costs_tid)ENABLEQUERYREWRITEASSELECTs.time_id,c.time_idFROMsaless,productsp,costscWHEREs.prod_id=p.prod_idANDc.prod_id=p.prod_idANDp.prod_nameIN(SELECTprod_nameFROMproducts);
Inthisexample,thedefiningqueryofsales_mv nowmatchesexactlywiththeuserqueryQ1 ,sofulltextmatchrewritewilltakeplace.
NotethatwhenaliasesarespecifiedinboththeSELECT clauseandthenewaliaslistclause,thealiaslistclausesupersedestheonesintheSELECTclause.
()
NamingMaterializedViews()ThenameofamaterializedviewmustconformtostandardOraclenamingconventions.However,ifthematerializedviewisbasedonauserdefinedprebuilttable,thenthenameofthematerializedviewmustexactlymatchthattablename.
Ifyoualreadyhaveanamingconventionfortablesandindexes,youmightconsiderextendingthisnamingschemetothematerializedviewssothattheyareeasilyidentifiable.Forexample,insteadofnamingthematerializedviewsum_of_sales ,itcouldbecalledsum_of_sales_mv todenotethatthisisamaterializedviewandnotatableorview.
()
StorageAndTableCompression()Unlessthematerializedviewisbasedon()()()()auserdefinedprebuilttable,itrequiresandoccupiesstoragespaceinsidethedatabase.Therefore,thestorageneedsforthematerializedviewshouldbespecifiedintermsofthetablespacewhereitistoresideandthesizeoftheextents.
Ifyoudonotknowhowmuchspacethematerializedviewwillrequire,thentheDBMS_MVIEW.ESTIMATE_SIZE packagecanestimatethenumberofbytesrequiredtostorethisuncompressedmaterializedview.Thisinformationcanthenassistthedesignteamindeterminingthetablespaceinwhichthematerializedviewshouldreside.
Youshouldusetablecompressionwithhighlyredundantdata,suchastableswithmanyforeignkeys.ThisisparticularlyusefulformaterializedviewscreatedwiththeROLLUP clause.Tablecompressionreducesdiskuseandmemoryuse
-
(specifically,thebuffercache),oftenleadingtoabetterscaleupforreadonlyoperations.Tablecompressioncanalsospeedupqueryexecutionattheexpenseofupdatecost.
SeeAlso:OracleDatabaseSQLLanguageReference(../../server.111/b28286/statements_10.htm#SQLRF017)foracompletedescriptionof STORAGE semantics,OracleDatabasePerformanceTuningGuide(../../server.111/b28274/toc.htm),andOracleDatabaseVLDBandPartitioningGuide(../../server.111/b32024/part_avail.htm#VLDBG004)fortablecompressionexamples
()
BuildMethods()()Twobuildmethodsareavailableforcreatingthematerializedview,asshowninTable83.IfyouselectBUILD IMMEDIATE ,thematerializedviewdefinitionisaddedtotheschemaobjectsinthedatadictionary,andthenthefactordetailtablesarescannedaccordingtotheSELECT expressionandtheresultsarestoredinthematerializedview.Dependingonthesizeofthetablestobescanned,thisbuildprocesscantakeaconsiderableamountoftime.
AnalternativeapproachistousetheBUILD DEFERRED clause,whichcreatesthematerializedviewwithoutdata,therebyenablingittobepopulatedatalaterdateusingtheDBMS_MVIEW.REFRESH packagedescribedinChapter15,"MaintainingtheDataWarehouse"(refresh.htm#g1018554).
()()Table83BuildMethods
BuildMethod Description
BUILD IMMEDIATE Createthematerializedviewandthenpopulateitwithdata.
BUILD DEFERRED Createthematerializedviewdefinitionbutdonotpopulateitwithdata.
-
()
EnablingQueryRewriteBefore()creatingamaterializedview,youcanverifywhattypesofqueryrewritearepossiblebycallingtheprocedureDBMS_MVIEW.EXPLAIN_MVIEW ,oruseDBMS_ADVISOR.TUNE_MVIEW tooptimizethematerializedviewsothatmanytypesofqueryrewritearepossible.Oncethematerializedviewhasbeencreated,youcanuseDBMS_MVIEW.EXPLAIN_REWRITE tofindoutif(orwhynot)itwillrewriteaspecificquery.
Eventhoughamaterializedviewisdefined,itwillnotautomaticallybeusedbythequeryrewritefacility.Eventhoughqueryrewriteisenabledbydefault,youalsomustspecifytheENABLE QUERY REWRITE clauseifthematerializedviewistobeconsideredavailableforrewritingqueries.
IfthisclauseisomittedorspecifiedasDISABLE QUERY REWRITE whenthematerializedviewiscreated,thematerializedviewcansubsequentlybeenabledforqueryrewritewiththeALTER MATERIALIZED VIEW statement.
IfyoudefineamaterializedviewasBUILD DEFERRED ,itisnoteligibleforqueryrewriteuntilitispopulatedwithdatathroughacompleterefresh.
()
QueryRewriteRestrictions()()()()Queryrewriteisnotpossiblewithallmaterializedviews.Ifqueryrewriteisnotoccurringwhenexpected,DBMS_MVIEW.EXPLAIN_REWRITE canhelpprovidereasonswhyaspecificqueryisnoteligibleforrewrite.Ifthisshowsthatnotalltypesofqueryrewritearepossible,usetheprocedureDBMS_ADVISOR.TUNE_MVIEW toseeifthematerializedviewcanbedefineddifferentlysothatqueryrewriteispossible.Also,checktoseeifyourmaterializedviewsatisfiesallofthefollowingconditions.
()
MaterializedViewRestrictions()Youshouldkeepinmindthefollowingrestrictions:
Thedefiningqueryofthematerializedviewcannotcontainanynonrepeatableexpressions(ROWNUM ,SYSDATE ,nonrepeatablePL/SQLfunctions,andsoon).
ThequerycannotcontainanyreferencestoRAW orLONG RAW datatypesorobjectREFs.
-
IfthematerializedviewwasregisteredasPREBUILT ,theprecisionofthecolumnsmustagreewiththeprecisionofthecorrespondingSELECTexpressionsunlessoverriddenbytheWITH REDUCED PRECISION clause.
()
GeneralQueryRewriteRestrictio()()nsYoushouldkeepinmindthefollowingrestrictions:
Aquerycanreferencebothlocalandremotetables.Suchaquerycanberewrittenaslongasaneligiblematerializedviewreferencingthesametablesisavailablelocally.
NeitherthedetailtablesnorthematerializedviewcanbeownedbySYS .
IfacolumnorexpressionispresentintheGROUP BY clauseofthematerializedview,itmustalsobepresentintheSELECT list.
Aggregatefunctionsmustoccuronlyastheoutermostpartoftheexpression.Thatis,aggregatessuchasAVG(AVG(x)) orAVG(x)+AVG(x) arenotallowed.
CONNECT BY clausesarenotallowed.
()
RefreshOptions()Whenyoudefineamaterializedview,youcanspecifythreerefreshoptions:howtorefresh,whattypeofrefresh,andcantrustedconstraintsbeused.Ifunspecified,thedefaultsareassumedasON DEMAND ,FORCE ,andENFORCEDconstraintsrespectively.
ThetworefreshexecutionmodesareON COMMIT andON DEMAND .Dependingonthematerializedviewyoucreate,someoftheoptionsmaynotbeavailable.Table84describestherefreshmodes.
()()Table84RefreshModes
RefreshMode Description
ONCOMMIT()
-
Refreshoccursautomaticallywhenatransactionthatmodifiedoneofthematerializedview'sdetailtablescommits.Thiscanbespecifiedaslongasthematerializedviewisfastrefreshable(inotherwords,notcomplex).TheON COMMIT privilegeisnecessarytousethismode.
ONDEMAND()
RefreshoccurswhenausermanuallyexecutesoneoftheavailablerefreshprocedurescontainedintheDBMS_MVIEWpackage(REFRESH ,REFRESH_ALL_MVIEWS ,REFRESH_DEPENDENT ).
WhenamaterializedviewismaintainedusingtheON COMMIT method,thetimerequiredtocompletethecommitmaybeslightlylongerthanusual.Thisisbecausetherefreshoperationisperformedaspartofthecommitprocess.Thereforethismethodmaynotbesuitableifmanyusersareconcurrentlychangingthetablesuponwhichthematerializedviewisbased.
Ifyouanticipateperforminginsert,updateordeleteoperationsontablesreferencedbyamaterializedviewconcurrentlywiththerefreshofthatmaterializedview,andthatmaterializedviewincludesjoinsandaggregation,OraclerecommendsyouuseON COMMIT fastrefreshratherthanON DEMANDfastrefresh.
Ifyouthinkthematerializedviewdidnotrefresh,checkthealertlogortracefile.
IfamaterializedviewfailsduringrefreshatCOMMIT time,youmustexplicitlyinvoketherefreshprocedureusingtheDBMS_MVIEW packageafteraddressingtheerrorsspecifiedinthetracefiles.Untilthisisdone,thematerializedviewwillnolongerberefreshedautomaticallyatcommittime.
Youcanspecifyhowyouwantyour()materializedviewstoberefreshedfromthedetailtablesbyselectingoneoffouroptions:COMPLETE ,FAST ,FORCE ,andNEVER .Table85describestherefreshoptions.
()()Table85RefreshOptions
RefreshOption Description
COMPLETE() Refreshesbyrecalculatingthematerializedview'sdefiningquery.
FAST()
-
Appliesincrementalchangestorefreshthematerializedviewusingtheinformationloggedinthematerializedviewlogs,orfromaSQL*Loaderdirectpathorapartitionmaintenanceoperation.
FORCE() AppliesFAST refreshifpossibleotherwise,itappliesCOMPLETE refresh.
NEVER() Indicatesthatthematerializedviewwillnotberefreshedwithrefreshmechanisms.
Whetherthefastrefreshoptionisavailabledependsuponthetypeofmaterializedview.YoucancalltheprocedureDBMS_MVIEW.EXPLAIN_MVIEWtodeterminewhetherfastrefreshispossible.
YoucanalsospecifyifitisacceptabletousetrustedconstraintsandQUERY_REWRITE_INTEGRITY=TRUSTED duringrefresh.AnynonvalidatedRELY constraintisatrustedconstraint.Forexample,nonvalidatedforeignkey/primarykeyrelationships,functionaldependenciesdefinedindimensionsoramaterializedviewintheUNKNOWN state.Ifqueryrewriteisenabledduringrefresh,thesecanimprovetheperformanceofrefreshbyenablingmoreperformantqueryrewrites.AnymaterializedviewthatcanuseTRUSTEDconstraintsforrefreshisleftinastateoftrustedfreshness(theUNKNOWN state)afterrefresh.
ThisisreflectedinthecolumnSTALENESS intheviewUSER_MVIEWS .ThecolumnUNKNOWN_TRUSTED_FD inthesameviewisalsosettoY ,whichmeansyes.
YoucandefinethispropertyofthematerializedvieweitherduringcreatetimebyspecifyingREFRESH USING TRUSTED [ENFORCED] CONSTRAINTS orbyusingALTER MATERIALIZED VIEW DDL.
()()Table86Constraints
ConstraintstoUse Description
TRUSTEDCONSTRAINTS RefreshcanusetrustedconstraintsandQUERY_REWRITE_INTEGRITY =TRUSTEDduringrefresh.Thisallowsuseofnon
-
validatedRELY constraintsandrewriteagainstmaterializedviewsinUNKNOWN orFRESH stateduringrefresh.
ENFORCEDCONSTRAINTS RefreshcanusevalidatedconstraintsandQUERY_REWRITE_INTEGRITY=ENFORCEDduringrefresh.Thisallowsuseofonlyvalidated,enforcedconstraintsandrewriteagainstmaterializedviewsinFRESH stateduringrefresh.
()
GeneralRestrictionson()()FastRefreshThedefiningqueryofthematerializedviewisrestrictedasfollows:
ThematerializedviewmustnotcontainreferencestononrepeatingexpressionslikeSYSDATE andROWNUM .
ThematerializedviewmustnotcontainreferencestoRAW orLONG RAWdatatypes.
ItcannotcontainaSELECT listsubquery.
Itcannotcontainanalyticalfunctions(forexample,RANK )intheSELECTclause.
ItcannotcontainaMODEL clause.
ItcannotcontainaHAVING clausewithasubquery.
ItcannotcontainnestedqueriesthathaveANY ,ALL ,orNOT EXISTS .
Itcannotcontaina[STARTWITH]CONNECTBY clause.
Itcannotcontainmultipledetailtablesatdifferentsites.
ON COMMIT materializedviewscannothaveremotedetailtables.
Nestedmaterializedviewsmusthaveajoinoraggregate.
-
()
RestrictionsonFastRefreshonMaterializedViewswithJoinsOnlyDefiningqueriesformaterializedviewswithjoinsonlyandnoaggregateshavethefollowingrestrictionsonfastrefresh:
Allrestrictionsfrom"GeneralRestrictionsonFastRefresh".
TheycannothaveGROUP BY clausesoraggregates.
RowidsofallthetablesintheFROM listmustappearintheSELECT listofthequery.
MaterializedviewlogsmustexistwithrowidsforallthebasetablesintheFROM listofthequery.
YoucannotcreateafastrefreshablematerializedviewfrommultipletableswithsimplejoinsthatincludeanobjecttypecolumnintheSELECTstatement.
()
RestrictionsonFastRefreshonMaterializedViewswithAggregatesDefiningqueriesformaterializedviewswithaggregatesorjoinshavethefollowingrestrictionsonfastrefresh:
Allrestrictionsfrom"GeneralRestrictionsonFastRefresh".
FastrefreshissupportedforbothON COMMIT andON DEMAND materializedviews,howeverthefollowingrestrictionsapply:
Alltablesinthematerializedviewmusthavematerializedviewlogs,andthematerializedviewlogsmust:
Containallcolumnsfromthetablereferencedinthematerializedview.However,noneofthesecolumnsinthebasetablecanbeencrypted.
SpecifywithROWID andINCLUDING NEW VALUES .
-
SpecifytheSEQUENCE clauseifthetableisexpectedtohaveamixofinserts/directloads,deletes,andupdates.
OnlySUM ,COUNT ,AVG ,STDDEV ,VARIANCE ,MIN andMAX aresupportedforfastrefresh.
COUNT(*) mustbespecified.
Aggregatefunctionsmustoccuronlyastheoutermostpartoftheexpression.Thatis,aggregatessuchasAVG(AVG(x)) orAVG(x)+AVG(x) arenotallowed.
ForeachaggregatesuchasAVG(expr) ,thecorrespondingCOUNT(expr)mustbepresent.OraclerecommendsthatSUM(expr) bespecified.SeeTable82forfurtherdetails.
IfVARIANCE(expr) orSTDDEV(expr )isspecified,COUNT(expr) andSUM(expr) mustbespecified.OraclerecommendsthatSUM(expr*expr) bespecified.SeeTable82forfurtherdetails.
TheSELECT columninthedefiningquerycannotbeacomplexexpressionwithcolumnsfrommultiplebasetables.Apossibleworkaroundtothisistouseanestedmaterializedview.
TheSELECT listmustcontainallGROUP BY columns.
Ifthematerializedviewhasoneofthefollowing,thenfastrefreshissupportedonlyonconventionalDMLinsertsanddirectloads.
MaterializedviewswithMIN orMAX aggregates
MaterializedviewswhichhaveSUM(expr) butnoCOUNT(expr)
MaterializedviewswithoutCOUNT(*)
Suchamaterializedviewiscalledaninsertonlymaterializedview.
AmaterializedviewwithMAX orMIN isfastrefreshableafterdeleteormixedDMLstatementsifitdoesnothaveaWHERE clause.
MaterializedviewswithnamedviewsorsubqueriesintheFROM clausecanbefastrefreshedprovidedtheviewscanbecompletelymerged.Forinformationonwhichviewswillmerge,refertotheOracleDatabasePerformanceTuningGuide(../../server.111/b28274/toc.htm).
-
Iftherearenoouterjoins,youmayhavearbitraryselectionsandjoinsintheWHERE clause.
MaterializedaggregateviewswithouterjoinsarefastrefreshableafterconventionalDMLanddirectloads,providedonlytheoutertablehasbeenmodified.Also,uniqueconstraintsmustexistonthejoincolumnsoftheinnerjointable.Ifthereareouterjoins,allthejoinsmustbeconnectedbyANDsandmustusetheequality(= )operator.
FormaterializedviewswithCUBE ,ROLLUP ,groupingsets,orconcatenationofthem,thefollowingrestrictionsapply:
TheSELECT listshouldcontaingroupingdistinguisherthatcaneitherbeaGROUPING_ID functiononallGROUP BY expressionsorGROUPINGfunctionsoneforeachGROUP BY expression.Forexample,iftheGROUPBY clauseofthematerializedviewis"GROUP BY CUBE(a,b) ",thentheSELECT listshouldcontaineither"GROUPING_ID(a,b) "or"GROUPING(a) AND GROUPING(b) "forthematerializedviewtobefastrefreshable.
GROUP BY shouldnotresultinanyduplicategroupings.Forexample,"GROUPBYa,ROLLUP(a,b) "isnotfastrefreshablebecauseitresultsinduplicategroupings"(a),(a,b),AND(a) ".
()
RestrictionsonFastRefreshonMaterializedViewswithUNIONALL
MaterializedviewswiththeUNION ALL setoperatorsupporttheREFRESHFAST optionifthefollowingconditionsaresatisfied:
ThedefiningquerymusthavetheUNION ALL operatoratthetoplevel.
TheUNION ALL operatorcannotbeembeddedinsideasubquery,withoneexception:TheUNION ALL canbeinasubqueryintheFROM clauseprovidedthedefiningqueryisoftheformSELECT*FROM (vieworsubquerywithUNION ALL )asinthefollowingexample:
-
CREATEVIEWview_with_unionallAS(SELECTc.rowidcrid,c.cust_id,2umarkerFROMcustomerscWHEREc.cust_last_name='Smith'UNIONALLSELECTc.rowidcrid,c.cust_id,3umarkerFROMcustomerscWHEREc.cust_last_name='Jones');
CREATEMATERIALIZEDVIEWunionall_inside_view_mvREFRESHFASTONDEMANDASSELECT*FROMview_with_unionall;
Notethattheviewview_with_unionall satisfiestherequirementsforfastrefresh.
EachqueryblockintheUNION ALL querymustsatisfytherequirementsofafastrefreshablematerializedviewwithaggregatesorafastrefreshablematerializedviewwithjoins.
Theappropriatematerializedviewlogsmustbecreatedonthetablesasrequiredforthecorrespondingtypeoffastrefreshablematerializedview.
NotethattheOracleDatabasealsoallowsthespecialcaseofasingletablematerializedviewwithjoinsonlyprovidedtheROWID columnhasbeenincludedintheSELECT listandinthematerializedviewlog.Thisisshowninthedefiningqueryoftheviewview_with_unionall .
TheSELECT listofeachquerymustincludeaUNION ALL marker,andtheUNION ALL columnmusthaveadistinctconstantnumericorstringvalueineachUNION ALL branch.Further,themarkercolumnmustappearinthesameordinalpositionintheSELECT listofeachqueryblock.See"UNIONALLMarker"(qradv.htm#BABEAHIA)formoreinformationregardingUNION ALLmarkers.
Somefeaturessuchasouterjoins,insertonlyaggregatematerializedviewqueriesandremotetablesarenotsupportedformaterializedviewswithUNION ALL .
Thecompatibilityinitializationparametermustbesetto9.2.0orhighertocreateafastrefreshablematerializedviewwithUNION ALL .
()
AchievingRefreshGoals
InadditiontotheEXPLAIN_MVIEW procedure,whichisdiscussedthroughoutthischapter,youcanusetheDBMS_ADVISOR.TUNE_MVIEW proceduretooptimizeaCREATE MATERIALIZED VIEW statementtoachieveREFRESH
-
FAST andENABLE QUERY REWRITE goals.
()
RefreshingNestedMaterializedViewsAnestedmaterializedviewisconsideredtobefreshaslongasitsdataissynchronizedwiththedatainitsdetailtables,evenifsomeofitsdetailtablescouldbestalematerializedviews.
Youcanrefreshnestedmaterializedviewsintwoways:DBMS_MVIEW.REFRESH withthenested flagsettoTRUE andREFRESH_DEPENDENT withthenested flagsettoTRUE onthebasetables.IfyouuseDBMS_MVIEW.REFRESH ,theentirematerializedviewchainisrefreshedandthecoveragestartingfromthespecifiedmaterializedviewintopdownfashion.Thatis,thespecifiedmaterializedviewandallitschildmaterializedviewsinthedependencyhierarchyarerefreshedinorder.WithDBMS_MVIEW.REFRESH_DEPENDENT ,theentirechainisrefreshedfromthebottomup.Thatis,alltheparentmaterializedviewsinthedependencyhierarchystartingfromthespecifiedtablearerefreshedinorder.
()Example87ExampleofRefreshingaNestedMaterializedView
Thefollowingstatementshowsanexampleofrefreshinganestedmaterializedview:
DBMS_MVIEW.REFRESH('SALES_MV,COST_MV',nested=>TRUE);
Thisstatementwillfirstrefreshallchildmaterializedviewsofsales_mv andcost_mv basedonthedependencyanalysisandthenrefreshthetwospecifiedmaterializedviews.
YoucanquerytheSTALE_SINCE columninthe*_MVIEWS viewstofindoutwhenamaterializedviewbecamestale.
()
ORDERBYClause()AnORDER BY clauseisallowedintheCREATE MATERIALIZED VIEWstatement.Itisusedonlyduringtheinitialcreationofthematerializedview.Itisnotusedduringafullrefreshorafastrefresh.
Toimprovetheperformanceofqueriesagainstlargematerializedviews,storetherowsinthematerializedviewintheorderspecifiedintheORDER BYclause.Thisinitialorderingprovidesphysicalclusteringofthedata.Ifindexesarebuiltonthecolumnsbywhichthematerializedviewisordered,accessingtherowsofthematerializedviewusingtheindexoftenreducesthetimefordiskI/Oduetothephysicalclustering.
-
TheORDER BY clauseisnotconsideredpartofthematerializedviewdefinition.Asaresult,thereisnodifferenceinthemannerinwhichOracleDatabasedetectsthevarioustypesofmaterializedviews(forexample,materializedjoinviewswithnoaggregates).Forthesamereason,queryrewriteisnotaffectedbytheORDER BY clause.ThisfeatureissimilartotheCREATE TABLE ...ORDER BY capability.
()
MaterializedViewLogsMaterializedview()()logsarerequiredifyouwanttousefastrefresh,withtheexceptionofPCTrefresh.Thatis,ifadetailtablesupportsPCTforamaterializedview,thematerializedviewlogonthatdetailtableisnotrequiredinordertodofastrefreshonthatmaterializedview.Asageneralrule,though,youshouldcreatematerializedviewlogsifyouwanttousefastrefresh.MaterializedviewlogsaredefinedusingaCREATE MATERIALIZED VIEW LOGstatementonthebasetablethatistobechanged.Theyarenotcreatedonthematerializedviewunlessthereisanothermaterializedviewontopofthatmaterializedview,whichisthecasewithnestedmaterializedviews.Forfastrefreshofmaterializedviews,thedefinitionofthematerializedviewlogsmustnormallyspecifytheROWID clause.Inaddition,foraggregatematerializedviews,itmustalsocontaineverycolumninthetablereferencedinthematerializedview,theINCLUDING NEW VALUES clauseandtheSEQUENCEclause.
Anexampleofamaterializedviewlogisshownasfollowswhereoneiscreatedonthetablesales :
CREATEMATERIALIZEDVIEWLOGONsalesWITHROWID(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amount_sold)INCLUDINGNEWVALUES;
Alternatively,amaterializedviewlogcanbeamendedtoincludetherowid,asinthefollowing:
ALTERMATERIALIZEDVIEWLOGONsalesADDROWID(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amount_sold)INCLUDINGNEWVALUES;
OraclerecommendsthatthekeywordSEQUENCE beincludedinyourmaterializedviewlogstatementunlessyouaresurethatyouwillneverperformamixedDMLoperation(acombinationofINSERT ,UPDATE ,orDELETEoperationsonmultipletables).TheSEQUENCE columnisrequiredinthe
-
materializedviewlogtosupportfastrefreshwithacombinationofINSERT ,UPDATE ,orDELETE statementsonmultipletables.Youcan,however,addtheSEQUENCE numbertothematerializedviewlogafterithasbeencreated.
TheboundaryofamixedDMLoperationisdeterminedbywhetherthematerializedviewisON COMMIT orON DEMAND .
ForON COMMIT ,themixedDMLstatementsoccurwithinthesametransactionbecausetherefreshofthematerializedviewwilloccuruponcommitofthistransaction.
ForON DEMAND ,themixedDMLstatementsoccurbetweenrefreshes.Thefollowingexampleofamaterializedviewlogillustrateswhereoneiscreatedonthetablesales thatincludestheSEQUENCE keyword:
CREATEMATERIALIZEDVIEWLOGONsalesWITHSEQUENCE,ROWID(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amount_sold)INCLUDINGNEWVALUES;
()
UsingtheFORCEOptionwithMaterializedViewLogs
IfyouspecifyFORCE andanyitemsspecifiedwiththeADD clausehavealreadybeenspecifiedforthematerializedviewlog,Oracledoesnotreturnanerror,butsilentlyignorestheexistingelementsandaddstothematerializedviewloganyitemsthatdonotalreadyexistinthelog.Forexample,ifyouusedafiltercolumnsuchascust_id andthiscolumnalreadyexisted,OracleDatabaseignorestheredundancyanddoesnotreturnanerror.
()
UsingOracleEnterpriseManagerAmaterializedviewcanalsobecreatedusingEnterpriseManagerbyselectingthematerializedviewobjecttype.Thereisnodifferenceintheinformationrequiredifthisapproachisused.
()
UsingMaterializedViewswithNLSParametersWhenusingcertainmaterializedviews,youmustensurethatyourNLSparametersarethesameaswhenyoucreatedthematerializedview.Materializedviewswiththisrestrictionareasfollows:
- Expressionsthatmayreturndifferentvalues,dependingonNLSparametersettings.Forexample,(date>"01/02/03" )or(rate
-
Inthecaseofaprebuilttable,ifithasanexistingcomment,thecommentwillbeinheritedbythematerializedviewafterithasbeencreated.Theexistingcommentwillbeprefixedwith'(fromtable)' .Forexample,tablesales_summary wascreatedtocontainsalessummaryinformation.Anexistingcomment'Salessummarydata' wasassociatedwiththetable.Amaterializedviewofthesamenameiscreatedtousetheprebuilttableasitscontainertable.Afterthematerializedviewcreation,thecommentbecomes'(fromtable)Salessummarydata' .
However,iftheprebuilttable,sales_summary ,doesnothaveanycomment,thefollowingcommentisadded:'Salessummarydata' .Then,ifwedropthematerializedview,thecommentwillbepassedtotheprebuilttablewiththecomment:'(frommaterializedview)Salessummarydata' .
()
RegisteringExistingMaterializedViews()Somedatawarehouseshaveimplementedmaterializedviewsinordinaryusertables.Althoughthissolutionprovidestheperformancebenefitsofmaterializedviews,itdoesnot:
ProvidequeryrewritetoallSQLapplications.
Enablematerializedviewsdefinedinoneapplicationtobetransparentlyaccessedinanotherapplication.
Generallysupportfastparallelorfastmaterializedviewrefresh.
Becauseoftheselimitations,andbecauseexistingmaterializedviewscanbeextremelylargeandexpensivetorebuild,youshouldregisteryourexistingmaterializedviewtableswheneverpossible.YoucanregisterauserdefinedmaterializedviewwiththeCREATE MATERIALIZED VIEW ...ON PREBUILTTABLE statement.Onceregistered,thematerializedviewcanbeusedforqueryrewritesormaintainedbyoneoftherefreshmethods,orboth.
Thecontentsofthetablemustreflectthematerializationofthedefiningqueryatthetimeyouregisteritasamaterializedview,andeachcolumninthedefiningquerymustcorrespondtoacolumninthetablethathasamatchingdatatype.However,youcanspecifyWITH REDUCED PRECISION toallowtheprecisionofcolumnsinthedefiningquerytobedifferentfromthatofthetablecolumns.
-
Thetableandthematerializedviewmusthavethesamename,butthetableretainsitsidentityasatableandcancontaincolumnsthatarenotreferencedinthedefiningqueryofthematerializedview.Theseextracolumnsareknownasunmanagedcolumns.Ifrowsareinsertedduringarefreshoperation,eachunmanagedcolumnoftherowissettoitsdefaultvalue.Therefore,theunmanagedcolumnscannothaveNOT NULL constraintsunlesstheyalsohavedefaultvalues.
MaterializedviewsbasedonprebuilttablesareeligibleforselectionbyqueryrewriteprovidedtheparameterQUERY_REWRITE_INTEGRITY issettoSTALE_TOLERATED orTRUSTED .SeeChapter17,"BasicQueryRewrite"(qrbasic.htm#g1045551)fordetailsaboutintegritylevels.
()()Whenyoudropamaterializedviewthatwascreatedonaprebuilttable,thetablestillexistsonlythematerializedviewisdropped.
Thefollowingexampleillustratesthetwostepsrequiredtoregisterauserdefinedtable.First,thetableiscreated,thenthematerializedviewisdefinedusingexactlythesamenameasthetable.Thismaterializedviewsum_sales_tab_mv iseligibleforuseinqueryrewrite.
CREATETABLEsum_sales_tabPCTFREE0TABLESPACEdemoSTORAGE(INITIAL16kNEXT16kPCTINCREASE0)ASSELECTs.prod_id,SUM(amount_sold)ASdollar_sales,SUM(quantity_sold)ASunit_salesFROMsalessGROUPBYs.prod_id;
CREATEMATERIALIZEDVIEWsum_sales_tab_mvONPREBUILTTABLEWITHOUTREDUCEDPRECISIONENABLEQUERYREWRITEASSELECTs.prod_id,SUM(amount_sold)ASdollar_sales,SUM(quantity_sold)ASunit_salesFROMsalessGROUPBYs.prod_id;
Youcouldhavecompressedthistabletosavespace.See"StorageAndTableCompression"fordetailsregardingtablecompression.
Insomecases,userdefinedmaterializedviewsarerefreshedonaschedulethatislongerthantheupdatecycle.Forexample,amonthlymaterializedviewmightbeupdatedonlyattheendofeachmonth,andthematerializedviewvaluesalwaysrefertocompletetimeperiods.Reportswrittendirectlyagainstthesematerializedviewsimplicitlyselectonlydatathatisnotinthecurrent(incomplete)timeperiod.Ifauserdefinedmaterializedviewalreadycontainsatimedimension:
Itshouldberegisteredandthenfastrefreshedeachupdatecycle.
-
Youcancreateaviewthatselectsthecompletetimeperiodofinterest.
Thereportsshouldbemodifiedtorefertotheviewinsteadofreferringdirectlytotheuserdefinedmaterializedview.
Iftheuserdefinedmaterializedviewdoesnotcontainatimedimension,then:
Createanewmaterializedviewthatdoesincludethetimedimension(ifpossible).
Theviewshouldaggregateoverthetimecolumninthenewmaterializedview.
()
ChoosingIndexesforMaterializedViewsThetwomostcommonoperationsonamaterializedviewarequeryexecutionandfastrefresh,andeachoperationhasdifferentperformancerequirements.Queryexecutionmightneedtoaccessanysubsetofthematerializedviewkeycolumns,andmightneedtojoinandaggregateoverasubsetofthosecolumns.Consequently,queryexecutionusuallyperformsbestifasinglecolumnbitmapindexisdefinedoneachmaterializedviewkeycolumn.
Inthecaseofmaterializedviewscontainingonlyjoinsusingfastrefresh,Oraclerecommendsthatindexesbecreatedonthecolumnsthatcontaintherowidstoimprovetheperformanceoftherefreshoperation.
Ifamaterializedviewusingaggregatesisfastrefreshable,thenanindexappropriateforthefastrefreshprocedureiscreatedunlessUSING NO INDEXisspecifiedintheCREATE MATERIALIZED VIEW statement.
Ifthematerializedviewispartitioned,then,afterdoingapartitionmaintenanceoperationonthematerializedview,theindexesbecomeunusable,andtheyneedtoberebuiltforfastrefreshtowork.
SeeOracleDatabasePerformanceTuningGuide(../../server.111/b28274/advisor.htm#PFGRF008)forinformationonusingtheSQLAccessAdvisortodeterminewhatindexesareappropriateforyourmaterializedview.
()
-
DroppingMaterializedViewsUsetheDROP MATERIALIZED VIEW statementtodropa()()materializedview.Forexample.thefollowingstatement:
DROPMATERIALIZEDVIEWsales_sum_mv;
Thisstatementdropsthematerializedviewsales_sum_mv .Ifthematerializedviewwasprebuiltonatable,thenthetableisnotdropped,butitcannolongerbemaintainedwiththerefreshmechanismorusedbyqueryrewrite.Alternatively,youcandropamaterializedviewusingOracleEnterpriseManager.
()
AnalyzingMaterializedViewCapabilitiesYoucanusetheDBMS_MVIEW .EXPLAIN_MVIEW proceduretolearnwhatispossiblewithamaterializedvieworpotentialmaterializedview.Inparticular,thisprocedureenablesyoutodetermine:
Ifamaterializedviewisfastrefreshable
Whattypesofqueryrewriteyoucanperformwiththismaterializedview
WhetherPCTrefreshispossible
Usingthisprocedureisstraightforward.YousimplycallDBMS_MVIEW.EXPLAIN_MVIEW ,passinginasasingleparametertheschemaandmaterializedviewnameforanexistingmaterializedview.Alternatively,youcanspecifytheSELECT stringforapotentialmaterializedvieworthecompleteCREATE MATERIALIZED VIEW statement.ThematerializedvieworpotentialmaterializedviewisthenanalyzedandtheresultsarewrittenintoeitheratablecalledMV_CAPABILITIES_TABLE ,whichisthedefault,ortoanarraycalledMSG_ARRAY .
Notethatyoumustruntheutlxmv.sql scriptpriortocallingEXPLAIN_MVIEW exceptwhenyouareplacingtheresultsinMSG_ARRAY .Thescriptisfoundintheadmin directory.ItistocreatetheMV_CAPABILITIES_TABLE inthecurrentschema.AnexplanationofthevariouscapabilitiesisinTable87,andallthepossiblemessagesarelistedinTable88.
()
-
UsingtheDBMS_MVIEW.EXPLAIN_MVIEWProcedureTheEXPLAIN_MVIEW proc()edurehasthefollowingparameters:
stmt_id
Anoptionalparameter.AclientsupplieduniqueidentifiertoassociateoutputrowswithspecificinvocationsofEXPLAIN_MVIEW .
mv
ThenameofanexistingmaterializedvieworthequerydefinitionortheentireCREATE MATERIALIZED VIEW statementofapotentialmaterializedviewyouwanttoanalyze.
msg-array
ThePL/SQLVARRAY thatreceivestheoutput.
EXPLAIN_MVIEW analyzesthespecifiedmaterializedviewintermsofitsrefreshandrewritecapabilitiesandinsertsitsresults(intheformofmultiplerows)intoMV_CAPABILITIES_TABLE orMSG_ARRAY .
SeeAlso:OracleDatabasePL/SQLPackagesandTypesReference(../../appdev.111/b28419/d_mview.htm#ARPLS027)forfurtherinformationaboutthe DBMS_MVIEW package
()
DBMS_MVIEW.EXPLAIN_MVIEWDeclarations
Thefollowing()PL/SQLdeclarationsthataremadeforyouintheDBMS_MVIEWpackageshowtheorderanddatatypesoftheseparametersforexplaininganexistingmaterializedviewandapotentialmaterializedviewwithoutputtoatableandtoaVARRAY .
ExplainanexistingorpotentialmaterializedviewwithoutputtoMV_CAPABILITIES_TABLE :
-
DBMS_MVIEW.EXPLAIN_MVIEW(mvINVARCHAR2,stmt_idINVARCHAR2:=NULL);
ExplainanexistingorpotentialmaterializedviewwithoutputtoaVARRAY :
DBMS_MVIEW.EXPLAIN_MVIEW(mvINVARCHAR2,msg_arrayOUTSYS.ExplainMVArrayType);
()
UsingMV_CAPABILITIES_TABLE
OneofthesimplestwaystouseDBMS_MVIEW.EXPLAIN_MVIEW is()withtheMV_CAPABILITIES_TABLE ,whichhasthefollowingstructure:
CREATETABLEMV_CAPABILITIES_TABLE(STATEMENT_IDVARCHAR(30),--Client-supplieduniquestatementidentifierMVOWNERVARCHAR(30),--NULLforSELECTbasedEXPLAIN_MVIEWMVNAMEVARCHAR(30),--NULLforSELECTbasedEXPLAIN_MVIEWCAPABILITY_NAMEVARCHAR(30),--Adescriptivenameoftheparticular--capability:--REWRITE--Candoatleastfulltextmatch--rewrite--REWRITE_PARTIAL_TEXT_MATCH--Candoatleatfullandpartial--textmatchrewrite--REWRITE_GENERAL--Candoallformsofrewrite--REFRESH--Candoatleastcompleterefresh--REFRESH_FROM_LOG_AFTER_INSERT--Candofastrefreshfromanmvlog--orchangecapturetableatleast--whenupdateoperationsare--restrictedtoINSERT--REFRESH_FROM_LOG_AFTER_ANY--candofastrefreshfromanmvlog--orchangecapturetableafterany--combinationofupdates--PCT--CandoEnhancedUpdateTrackingon--thetablenamedintheRELATED_NAME--column.EUTisneededforfast--refreshafterpartitioned--maintenanceoperationsonthetable
-
--namedintheRELATED_NAMEcolumn--andtodonon-staletolerated--rewritewhenthemvispartially--stalewithrespecttothetable--namedintheRELATED_NAMEcolumn.--EUTcanalsosometimesenablefast--refreshofupdatestothetable--namedintheRELATED_NAMEcolumn--whenfastrefreshfromanmvlog--orchangecapturetableisnot--possible.--SeeTable8-7POSSIBLECHARACTER(1),--T=capabilityispossible--F=capabilityisnotpossibleRELATED_TEXTVARCHAR(2000),--Owner.table.column,aliasname,andsoon--relatedtothismessage.Thespecific--meaningofthiscolumndependsonthe--NSGNOcolumn.Seethedocumentationfor--DBMS_MVIEW.EXPLAIN_MVIEW()fordetails.RELATED_NUMNUMBER,--Whenthereisanumericvalue--associatedwitharow,itgoeshere.MSGNOINTEGER,--Whenavailable,QSMmessage#explaining--whydisabledormoredetailswhen--enabled.MSGTXTVARCHAR(2000),--TextassociatedwithMSGNO.SEQNUMBER);--UsefulinORDERBYclausewhen--selectingfromthistable.
Youcanusetheutlxmv.sql scriptfoundintheadmin directorytocreateMV_CAPABILITIES_TABLE .
()Example88DBMS_MVIEW.EXPLAIN_MVIEW
First,createthematerializedview.Alternatively,youcanuseEXPLAIN_MVIEWonapotentialmaterializedviewusingitsSELECT statementorthecompleteCREATE MATERIALIZED VIEW statement.
CREATEMATERIALIZEDVIEWcal_month_sales_mvBUILDIMMEDIATEREFRESHFORCEENABLEQUERYREWRITEASSELECTt.calendar_month_desc,SUM(s.amount_sold)ASdollarsFROMsaless,timestWHEREs.time_id=t.time_idGROUPBYt.calendar_month_desc;
-
Then,youinvokeEXPLAIN_MVIEW withthematerializedviewtoexplain.YouneedtousetheSEQ columninanORDER BY clausesotherowswilldisplayinalogicalorder.Ifacapabilityisnotpossible,N willappearintheP columnandanexplanationintheMSGTXT column.Ifacapabilityisnotpossibleformorethanonereason,arowisdisplayedforeachreason.
EXECUTEDBMS_MVIEW.EXPLAIN_MVIEW('SH.CAL_MONTH_SALES_MV');
SELECTcapability_name,possible,SUBSTR(related_text,1,8)ASrel_text,SUBSTR(msgtxt,1,60)ASmsgtxtFROMMV_CAPABILITIES_TABLEORDERBYseq;
CAPABILITY_NAMEPREL_TEXTMSGTXT------------------------------PCTNREFRESH_COMPLETEYREFRESH_FASTNREWRITEYPCT_TABLENSALESnopartitionkeyorPMARKERinselectlistPCT_TABLENTIMESrelationisnotapartitionedtableREFRESH_FAST_AFTER_INSERTNSH.TIMESmvlogmusthavenewvaluesREFRESH_FAST_AFTER_INSERTNSH.TIMESmvlogmusthaveROWIDREFRESH_FAST_AFTER_INSERTNSH.TIMESmvlogdoesnothaveallnecessarycolumnsREFRESH_FAST_AFTER_INSERTNSH.SALESmvlogmusthavenewvaluesREFRESH_FAST_AFTER_INSERTNSH.SALESmvlogmusthaveROWIDREFRESH_FAST_AFTER_INSERTNSH.SALESmvlogdoesnothaveallnecessarycolumnsREFRESH_FAST_AFTER_ONETAB_DMLNDOLLARSSUM(expr)withoutCOUNT(expr)REFRESH_FAST_AFTER_ONETAB_DMLNseethereasonwhyREFRESH_FAST_AFTER_INSERTisdisabledREFRESH_FAST_AFTER_ONETAB_DMLNCOUNT(*)isnotpresentintheselectlistREFRESH_FAST_AFTER_ONETAB_DMLNSUM(expr)withoutCOUNT(expr)REFRESH_FAST_AFTER_ANY_DMLNseethereasonwhyREFRESH_FAST_AFTER_ONETAB_DMLisdisabledREFRESH_FAST_AFTER_ANY_DMLNSH.TIMESmvlogmusthavesequenceREFRESH_FAST_AFTER_ANY_DMLNSH.SALESmvlogmusthavesequenceREFRESH_PCTNPCTisnotpossibleonanyofthedetailtablesinthematerializedviewREWRITE_FULL_TEXT_MATCHYREWRITE_PARTIAL_TEXT_MATCHYREWRITE_GENERALYREWRITE_PCTNPCTisnotpossibleonanydetailtables
SeeAlso:
-
Chapter15,"MaintainingtheDataWarehouse"(refresh.htm#g1018554)andChapter18,"AdvancedQueryRewrite"(qradv.htm#g1045552)forfurtherdetailsaboutPCT
()
MV_CAPABILITIES_TABLE.CAPABILITY_NAMEDetails
Table87listsexplanationsforvaluesintheCAPABILITY_NAME column.
()()Table87CAPABILITY_NAMEColumnDetails
CAPABILITY_NAME Description
PCT Ifthiscapabilityispossible,PartitionChangeTracking(PCT)ispossibleonatleastonedetailrelation.Ifthiscapabilityisnotpossible,PCTisnotpossiblewithanydetailrelationreferencedbythematerializedview.
REFRESH_COMPLETE Ifthiscapabilityispossible,completerefreshofthematerializedviewispossible.
REFRESH_FAST Ifthiscapabilityispossible,fastrefreshispossibleatleastundercertaincircumstances.
REWRITE Ifthiscapabilityispossible,atleastfulltextmatchqueryrewriteispossible.Ifthiscapabilityisnotpossible,noformofqueryrewriteispossible.
PCT_TABLE Ifthiscapabilityispossible,itispossiblewithrespecttoaparticularpartitionedtableinthetoplevelFROM list.Whenpossible,PCTappliestothepartitionedtablenamedintheRELATED_TEXT column.
-
PCTisneededtosupportfastfreshafterpartitionmaintenanceoperationsonthetablenamedintheRELATED_TEXT column.
PCTmayalsosupportfastrefreshwithregardtoupdatestothetablenamedintheRELATED_TEXTcolumnwhenfastrefreshfromamaterializedviewlogisnotpossible.
PCTisalsoneededtosupportqueryrewriteinthepresenceofpartialstalenessofthematerializedviewwithregardtothetablenamedintheRELATED_TEXT column.
Whendisabled,PCTdoesnotapplytothetablenamedintheRELATED_TEXT column.Inthiscase,fastrefreshisnotpossibleafterpartitionmaintenanceoperationsonthetablenamedintheRELATED_TEXT column.Inaddition,PCTbasedrefreshofupdatestothetablenamedintheRELATED_TEXT columnisnotpossible.Finally,queryrewritecannotbesupportedinthepresenceofpartialstalenessofthematerializedviewwithregardtothetablenamedintheRELATED_TEXT column.
PCT_TABLE_REWRITE Ifthiscapabilityispossible,itispossiblewithrespecttoaparticularpartitionedtableinthetoplevelFROM list.Whenpossible,PCTappliestothepartitionedtablenamedintheRELATED_TEXT column.
Thiscapabilityisneededtosupportqueryrewriteagainstthismaterializedviewinpartialstale
-
statewithregardtothetablenamedintheRELATED_TEXTcolumn.
Whendisabled,queryrewritecannotbesupportedifthismaterializedviewisinpartialstalestatewithregardtothetablenamedintheRELATED_TEXTcolumn.
REFRESH_FAST_AFTER_INSERT Ifthiscapabilityispossible,fastrefreshfromamaterializedviewlogispossibleatleastinthecasewheretheupdatesarerestrictedtoINSERT operationscompleterefreshisalsopossible.Ifthiscapabilityisnotpossible,noformoffastrefreshfromamaterializedviewlogispossible.
REFRESH_FAST_AFTER_ONETAB_DML Ifthiscapabilityispossible,fastrefreshfromamaterializedviewlogispossibleregardlessofthetypeofupdateoperation,providedallupdateoperationsareperformedonasingletable.Ifthiscapabilityisnotpossible,fastrefreshfromamaterializedviewlogmaynotbepossiblewhentheupdateoperationsareperformedonmultipletables.
REFRESH_FAST_AFTER_ANY_DML Ifthiscapabilityispossible,fastrefreshfromamaterializedviewlogispossibleregardlessofthetypeofupdateoperationorthenumberoftablesupdated.Ifthiscapabilityisnotpossible,fastrefreshfromamaterializedviewlogmaynotbepossiblewhentheupdateoperations(otherthanINSERT )affectmultipletables.
-
REFRESH_FAST_PCT Ifthiscapabilityispossible,fastrefreshusingPCTispossible.Generally,thismeansthatrefreshispossibleafterpartitionmaintenanceoperationsonthosedetailtableswherePCTisindicatedaspossible.
REWRITE_FULL_TEXT_MATCH Ifthiscapabilityispossible,fulltextmatchqueryrewriteispossible.Ifthiscapabilityisnotpossible,fulltextmatchqueryrewriteisnotpossible.
REWRITE_PARTIAL_TEXT_MATCH Ifthiscapabilityispossible,atleastfullandpartialtextmatchqueryrewritearepossible.Ifthiscapabilityisnotpossible,atleastpartialtextmatchqueryrewriteandgeneralqueryrewritearenotpossible.
REWRITE_GENERAL Ifthiscapabilityispossible,allqueryrewritecapabilitiesarepossible,includinggeneralqueryrewriteandfullandpartialtextmatchqueryrewrite.Ifthiscapabilityisnotpossible,atleastgeneralqueryrewriteisnotpossible.
REWRITE_PCT Ifthiscapabilityispossible,queryrewritecanuseapartiallystalematerializedvieweveninQUERY_REWRITE_INTEGRITY =ENFORCED orTRUSTED modes.Whenthiscapabilityisnotpossible,queryrewritecanuseapartiallystalematerializedviewonlyinQUERY_REWRITE_INTEGRITY =STALE_TOLERATED mode.
-
()
MV_CAPABILITIES_TABLEColumnDetails
Table88liststhesemanticsforRELATED_TEXT andRELATED_NUM columns.
()()Table88MV_CAPABILITIES_TABLEColumnDetails
MSGNO MSGTXT RELATED_NUM RELATED_TEXT
NULL NULL ForPCTcapabilityonly:[ owner .] name ofthetableuponwhichPCTisenabled
2066 ThisstatementresultedinanOracleerror
Oracleerrornumberthatoccurred
2067 NopartitionkeyorPMARKER orjoindependentexpressioninSELECT list
[ owner .] name ofrelationforwhichPCTisnotsupported
2068 Relationisnotpartitioned
[ owner .] name ofrelationforwhichPCTisnotsupported
2069 PCTnotsupportedwithmulticolumnpartitionkey
[ owner .] name ofrelationforwhichPCTisnotsupported
2070 PCTnotsupportedwiththistypeofpartitioning
[ owner .] name ofrelationforwhichPCTisnotsupported
-
2071 Internalerror:undefinedPCTfailurecode
TheunrecognizednumericPCTfailurecode
[ owner .] name ofrelationforwhichPCTisnotsupported
2072 Requirementsnotsatisfiedforfastrefreshofnestedmaterializedview
2077 Materializedviewlogisnewerthanlastfullrefresh
[ owner .] table_nameoftableuponwhichthematerializedviewlogisneeded
2078 Materializedviewlogmusthavenewvalues
[ owner .] table_nameoftableuponwhichthematerializedviewlogisneeded
2079 MaterializedviewlogmusthaveROWID
[ owner .] table_nameoftableuponwhichthematerializedviewlogisneeded
2080 Materializedviewlogmusthaveprimarykey
[ owner .] table_nameoftableuponwhichthematerializedviewlogisneeded
2081 Materializedviewlogdoesnothaveallnecessarycolumns
[ owner .] table_nameoftableuponwhichthematerializedviewlogisneeded
-
2082 Problemwithmaterializedviewlog
[ owner .] table_nameoftableuponwhichthematerializedviewlogisneeded
2099 MaterializedviewreferencesaremotetableorviewintheFROM list
OffsetfromtheSELECTkeywordtothetableorviewinquestion
[ owner .] name ofthetableorviewinquestion
2126 Multiplemastersites
Nameofthefirstdifferentnode,orNULL ifthefirstdifferentnodeislocal
2129 Joinorfiltercondition(s)arecomplex
[ owner .] name ofthetableinvolvedwiththejoinorfiltercondition(orNULL whennotavailable)
2130 Expressionnotsupportedforfastrefresh
OffsetfromtheSELECTkeywordtotheexpressioninquestion
ThealiasnameintheSELECT listoftheexpressioninquestion
2150 SELECT listsmustbeidenticalacrosstheUNIONoperator
OffsetfromtheSELECTkeywordtothefirstdifferentselectitemintheSELECT list
ThealiasnameofthefirstdifferentselectitemintheSELECT list
2182 PCTisenabledthroughajoindependency
[ owner .] name ofrelationforwhichPCT_TABLE_REWRITE isnotenabled
2183 ExpressiontoenablePCTnotin
TheunrecognizednumericPCT
[ owner .] name ofrelationforwhichPCTisnotenabled
-
PARTITIONBY ofanalyticfunctionormodel
failurecode
2184 ExpressiontoenablePCTcannotberolledup
[ owner .] name ofrelationforwhichPCTisnotenabled
2185 NopartitionkeyorPMARKER intheSELECTlist
[ owner .] name ofrelationforwhichPCT_TABLE_REWRITE isnotenabled
2186 GROUPOUTER JOINispresent
2187 Materializedviewonexternaltable
AboutOracle(http://www.oracle.com/corporate/index.html) ContactUs(http://www.oracle.com/us/corporate/contact/index.html) LegalNotices
(http://www.oracle.com/us/legal/index.html) TermsofUse(http://www.oracle.com/us/legal/terms/index.html) YourPrivacyRights
(http://www.oracle.com/us/legal/privacy/index.html)
Copyright2015,Oracleand/oritsaffiliates.Allrightsreserved.