Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
com/en/)
SignIn(http://www.oracle.com/webapps/redirect/signon?nexturl=http://docs.oracle.com/cd/B28359_01/server.111/b28313/basicmv.htm)
Home(https://docs.oracle.com/)/Database(https://docs.oracle.com/en/database/)/OracleDatabaseOnlineDocumentation
11gRelease1(11.1)(../../index.htm)/DataWarehousingandBusinessIntelligence(../../nav/portal_6.htm)
DatabaseDataWarehousingGuide
()
()()
8()BasicMaterializedViews
Thischapterdescribestheuseofmaterializedviews.Itcontainsthefollowing
topics:
OverviewofDataWarehousingwithMaterializedViews
TypesofMaterializedViews
CreatingMaterializedViews
RegisteringExistingMaterializedViews
ChoosingIndexesforMaterializedViews
DroppingMaterializedViews
AnalyzingMaterializedViewCapabilities
()
OverviewofDataWarehousingwith
MaterializedViews
()()()Typically,dataflowsfromoneormoreonlinetransactionprocessing
(OLTP)databaseintoadatawarehouseonamonthly,weekly,ordailybasis.
Thedataisnormallyprocessedina()stagingfile(glossary.htm#i997125)before
beingaddedtothedatawarehouse.Datawarehousescommonlyrangeinsize
fromtensofgigabytestoafewterabytes.Usually,thevastmajorityofthedata
isstoredinafewverylargefacttables.
Onetechniqueemployedindatawarehousestoimproveperformanceisthe
creationofsummaries.Summariesarespecialtypesofaggregateviewsthat
improvequeryexecutiontimesbyprecalculatingexpensivejoinsand
aggregationoperationspriortoexecutionandstoringtheresultsinatablein
thedatabase.Forexample,youcancreateasummarytabletocontainthe
sumsofsalesbyregionandbyproduct.
Thesummariesoraggregatesthatarereferredtointhisbookandinliterature
ondatawarehousingarecreatedinOracleDatabaseusingaschemaobject
called()amaterializedview(glossary.htm#i997008).Materializedviewscan
performanumberofroles,suchasimprovingqueryperformanceorproviding
replicateddata.
Inthepast,organizationsusingsummariesspentasignificantamountoftime
andeffortcreatingsummariesmanually,identifyingwhichsummariestocreate,
indexingthesummaries,updatingthem,andadvisingtheirusersonwhichones
touse.Theintroductionofsummarymanagementeasedtheworkloadofthe
databaseadministratorandmeanttheusernolongerneededtobeawareof
thesummariesthathadbeendefined.Thedatabaseadministratorcreatesone
ormorematerializedviews,whicharetheequivalentofasummary.Theend
userqueriesthetablesandviewsatthedetaildatalevel.Thequeryrewrite
mechanismintheOracleserverautomaticallyrewritestheSQLquerytouse
thesummarytables.Thismechanismreducesresponsetimeforreturning
resultsfromthequery.Materializedviewswithinthedatawarehouseare
transparenttotheenduserortothedatabaseapplication.
Althoughmaterializedviewsareusuallyaccessedthroughthequeryrewrite
mechanism,anenduserordatabaseapplicationcanconstructqueriesthat
directlyaccessthematerializedviews.However,seriousconsiderationshould
begiventowhetherusersshouldbeallowedtodothisbecauseanychangeto
thematerializedviewswillaffectthequeriesthatreferencethem.
()
MaterializedViewsforDataWarehouses
Indatawarehouses,youcanusematerializedviewstoprecomputeandstore
aggregateddatasuchasthesumofsales.Materializedviewsinthese
environmentsareoftenreferredtoassummaries,becausetheystore
summarizeddata.Theycanalsobeusedtoprecomputejoinswithorwithout
aggregations.Amaterializedvieweliminatestheoverheadassociatedwith
expensivejoinsandaggregationsforalargeorimportantclassofqueries.
()
MaterializedViewsforDistributedComputing
Indistributedenvironments,youcanusematerializedviewstoreplicatedataat
distributedsitesandtosynchronizeupdatesdoneatthosesiteswithconflict
resolutionmethods.Thesereplicamaterializedviewsprovidelocalaccessto
datathatotherwisewouldhavetobeaccessedfromremotesites.Materialized
viewsarealsousefulinremotedatamarts.SeeOracleDatabaseAdvanced
Replication(../../server.111/b28326/toc.htm)andOracleDatabaseHeterogeneous
ConnectivityAdministrator'sGuide(../../server.111/b28277/toc.htm)fordetailson
distributedandmobilecomputing.
()
MaterializedViewsforMobileComputing
Youcanalsousematerializedviewstodownloadasubsetofdatafromcentral
serverstomobileclients,withperiodicrefreshesandupdatesbetweenclients
andthecentralservers.
Thischapterfocusesontheuseofmaterializedviewsindatawarehouses.See
OracleDatabaseAdvancedReplication(../../server.111/b28326/toc.htm)andOracle
DatabaseHeterogeneousConnectivityAdministrator'sGuide
(../../server.111/b28277/toc.htm)fordetailsondistributedandmobilecomputing.
()
TheNeedforMaterializedViews
Youcanusematerializedviewstoincreasethespeedofqueriesonverylarge
databases.Queriestolargedatabasesofteninvolvejoinsbetweentables,
aggregationssuchas SUM ,orboth.Theseoperationsareexpensiveintermsof
timeandprocessingpower.Thetypeofmaterializedviewyoucreate
determineshowthematerializedviewisrefreshedandusedbyqueryrewrite.
Materializedviewsimprovequeryperformancebyprecalculatingexpensivejoin
andaggregationoperationsonthedatabasepriortoexecutionandstoringthe
resultsinthedatabase.Thequeryoptimizerautomaticallyrecognizeswhenan
existingmaterializedviewcanandshouldbeusedtosatisfyarequest.Itthen
transparentlyrewritestherequesttousethematerializedview.Queriesgo
directlytothematerializedviewandnottotheunderlyingdetailtables.In
general,rewritingqueriestousematerializedviewsratherthandetailtables
improvesresponsetime.Figure81illustrateshowqueryrewriteworks.
()Figure81TransparentQueryRewrite
Descriptionof"Figure81TransparentQueryRewrite"(./img_text/dwhsg027.htm)
Whenusingqueryrewrite,creatematerializedviewsthatsatisfythelargest
numberofqueries.Forexample,ifyouidentify20queriesthatarecommonly
appliedtothedetailorfacttables,thenyoumightbeabletosatisfythemwith
fiveorsixwellwrittenmaterializedviews.Amaterializedviewdefinitioncan
includeanynumberofaggregations( SUM , COUNT(x) , COUNT(*) ,
COUNT(DISTINCTx) , AVG , VARIANCE , STDDEV , MIN ,and MAX ).Itcanalso
includeanynumberofjoins.Ifyouareunsureofwhichmaterializedviewsto
create,OracleprovidestheSQLAccessAdvisor,whichisasetofadvisory
procedure()sinthe DBMS_ADVISOR packagetohelpindesigningand
evaluatingmaterializedviewsforqueryrewrite.
Ifamaterializedviewistobeusedbyqueryrewrite,itmustbestoredinthe
samedatabaseasthedetailtablesonwhichitrelies.Amaterializedviewcan
bepartitioned,andyoucandefineamaterializedviewonapartitionedtable.
Youcanalsodefineoneormoreindexesonthematerializedview.
Unlikeindexes,materializedviewscanbeaccesseddirectlyusinga SELECT
statement.However,itisrecommendedthatyoutrytoavoidwritingSQL
statementsthatdirectlyreferencethematerializedview,becausethenitis
difficulttochangethemwithoutaffectingtheapplication.Instead,letquery
rewritetransparentlyrewriteyourquerytousethematerializedview.
Notethatthetechniquesshowninthischapterillustratehowtouse
materializedviewsindatawarehouses.Materializedviewscanalsobeusedby
OracleReplication.SeeOracleDatabaseAdvancedReplication
(../../server.111/b28326/toc.htm)forfurtherinformation.
()
ComponentsofSummaryManagement
Summary()managementconsistsof:
Mechanismstodefinematerializedviewsanddimensions.
TableofContents
(toc.htm) OracleDatabase (toc.htm)
Preface(preface.htm)
Arefreshmechanismtoensurethatallmaterializedviewscontainthelatest
data.
What'sNewinOracleDatabase?(whatsnew.htm)
Aqueryrewritecapabilitytotransparentlyrewriteaquerytousea
DataWarehousingConcepts(concept.htm)
materializedview.
LogicalDesigninDataWarehouses
(logical.htm)
PhysicalDesigninDataWarehouses(physical.htm)
HardwareandI/OConsiderationsinDataWarehouses
TheSQLAccessAdvisor,whichrecommendsmaterializedviews,partitions,
andindexestocreate.
(hardware.htm)
PartitioninginDataWarehouses(parpart.htm)
Indexes(indexes.htm)
TUNE_MVIEW ,whichshowsyouhowtomakeyourmaterializedviewfast
IntegrityConstraints(constra.htm) refreshableandusegeneralqueryrewrite.
BasicMaterializedViews(basicmv.htm)
AdvancedMaterializedViews(advmv.htm)
Dimensions(dimen.htm)
Theuseofsummarymanagementfeaturesimposesnoschemarestrictions,
OverviewofExtraction,Transformation,andLoading
(ettover.htm)
ExtractioninDataWarehousesandcanenablesomeexistingDSSdatabaseapplicationstoimprove
(extract.htm)
performancewithouttheneedtoredesignthedatabaseortheapplication.
TransportationinDataWarehouses
(transport.htm)
LoadingandTransformation(transform.htm)
Figure82illustratestheuseofsummarymanagementinthewarehousing
MaintainingtheDataWarehouse
(refresh.htm)
ChangeDataCapture(cdc.htm)cycle.Afterthedatahasbeentransformed,staged,andloadedintothedetail
datainthewarehouse,youcaninvokethesummarymanagementprocess.
BasicQueryRewrite(qrbasic.htm)
First,usetheSQLAccessAdvisortoplanhowyouwillusematerializedviews.
AdvancedQueryRewrite(qradv.htm)
SchemaModelingTechniquesThen,creatematerializedviewsanddesignhowquerieswillberewritten.Ifyou
(schemas.htm)
arehavingproblemstryingtogetyourmaterializedviewstoworkthenuse
SQLforAggregationinDataWarehouses
(aggreg.htm)
toobtainanoptimizedmaterializedview.
SQLforAnalysisandReportingTUNE_MVIEW
(analysis.htm)
SQLforModeling(sqlmodel.htm)
OLAPandDataMining(bi.htm) ()Figure82OverviewofSummaryManagement
AdvancedBusinessIntelligenceQueries(advbi.htm)
UsingParallelExecution(usingpe.htm)
Glossary(glossary.htm)
Download
Categories
Home(../../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)
Descriptionof"Figure82OverviewofSummaryManagement"
(./img_text/dwhsg071.htm)
Understandingthesummarymanagementprocessduringtheearlieststagesof
datawarehousedesigncanyieldlargedividendslaterintheformofhigher
performance,lowersummaryadministrationcosts,andreducedstorage
requirements.
()
DataWarehousingTerminology
Somebasicdatawarehousingtermsaredefinedasfollows:
()()()()Dimensiontablesdescribethebusinessentitiesofanenterprise,
representedashierarchical,categoricalinformationsuchastime,
departments,locations,andproducts.Dimensiontablesaresometimes
called()lookupor()referencetables.
Dimensiontablesusuallychangeslowlyovertimeandarenotmodifiedona
periodicschedule.Theyareusedinlongrunningdecisionsupportqueriesto
aggregatethedatareturnedfromthequeryintoappropriatelevelsofthe
dimensionhierarchy.
Hierarchiesdescribethebusinessrelationshipsandcommonaccess
patternsinthedatabase.Ananalysisofthedimensions,combinedwithan
understandingofthetypicalworkload,canbeusedtocreatematerialized
views.SeeChapter10,"Dimensions"(dimen.htm#g1011059)formore
information.
()()()Facttablesdescribethebusinesstransactionsofanenterprise.
Thevastmajorityofdatainadatawarehouseisstoredinafewverylarge
facttablesthatareupdatedperiodicallywithdatafromoneormore
operationalOLTPdatabases.
Facttablesinclud()efacts(alsocalledmeasures)suchassales,units,and
inventory.
Asimplemeasureisanumericorcharactercolumnofonetablesuchas
fact.sales .
Acomputedmeasureisanexpressioninvolvingmeasuresofonetable,for
example, fact.revenues fact.expenses .
Amultitablemeasureisacomputedmeasuredefinedonmultipletables,
forexample, fact_a.revenues fact_b.expenses .
Facttablesalsocontainoneormoreforeign()keysthatorganizethe
businesstransactionsbytherelevantbusinessentitiessuchastime,product,
andmarket.Inmostcases,theseforeignkeysarenonnull,formaunique
compoundkeyofthefacttable,andeachforeignkeyjoinswithexactlyone
rowofa()dimensiontable(glossary.htm#i996883).
Amaterializedviewisaprecomputedtablecomprisingaggregatedand
joineddatafromfactandpossiblyfromdimensiontables.Amongbuildersof
datawarehouses,amaterializedviewisalsoknownasasummary
(glossary.htm#i997158).
()
()()MaterializedViewSchemaDesign
Summarymanagement()canperformmanyusefulfunctions,includingquery
rewriteandmaterializedviewrefresh,evenifyourdatawarehousedesigndoes
notfollowtheseguidelines.However,youwillrealizesignificantlygreaterquery
executionperformanceandmaterializedviewrefreshperformancebenefitsand
youwillrequirefewermaterializedviewsifyourschemadesigncomplieswith
theseguidelines.
Amaterializedviewdefinitionincludesanynumberofaggregates,aswellas
anynumberofjoins.Inseveralways,amaterializedviewbehaveslikean
index:
Thepurposeofamaterializedviewistoincreasequeryexecution
performance.
TheexistenceofamaterializedviewistransparenttoSQLapplications,so
thatadatabaseadministratorcancreateordropmaterializedviewsatany
timewithoutaffectingthevalidityofSQLapplications.
Amaterializedviewconsumesstoragespace.
Thecontentsofthematerializedviewmustbeupdatedwhentheunderlying
detailtablesaremodified.
()
SchemasandDimensionTables
Inthecaseofnormalizedorpartiallynormalizeddimensiontables(adimension
thatisstoredinmorethanonetable),identifyhowthesetablesarejoined.Note
whetherthejoinsbetweenthedimensiontablescanguaranteethateachchild
siderowjoinswithoneandonlyoneparentsiderow.Inthecaseof
denormalizeddimensions,determinewhetherthechildsidecolumnsuniquely
determinetheparentside(orattribute)columns.Theserelationshipscanbe
enabledwithconstraints,usingthe NOVALIDATE and RELY optionsifthe
relationshipsrepresentedbytheconstraintsareguaranteedbyothermeans.
Notethatifthejoinsbetweenfactanddimensiontablesdonotsupportthe
parentchildrelationshipdescribedpreviously,youstillgainsignificant
performanceadvantagesfromdefiningthedimensionwiththe CREATE
DIMENSION statement.Anotheralternative,subjecttosomerestrictions,isto
useouterjoinsinthematerializedviewdefinition(thatis,inthe CREATE
MATERIALIZED VIEW statement).
Youmustnotcreatedimensionsinanyschemathatdoesnotsatisfythese
relationships.Incorrectresultscanbereturnedfromqueriesotherwise.
()
MaterializedViewSchemaDesignGuidelines
Beforestartingtodefineandusethevariouscomponentsofsummary
management,youshouldreviewyourschemadesigntoabidebythefollowing
guidelineswhereverpossible.
Guidelines1and2aremoreimportantthanguideline3.Ifyourschemadesign
doesnotfollowguidelines1and2,itdoesnotthenmatterwhetheritfollows
guideline3.Guidelines1,2,and3affectbothqueryrewriteperformanceand
materializedviewrefreshperformance.
()()Table81SchemaDesignGuidelines
Schema
Guideline
Guideline1
Dimensions
Description
Dimensionsshouldeitherbedenormalized(eachdimension
containedinonetable)orthejoinsbetweentablesina
normalizedorpartiallynormalizeddimensionshould
guaranteethateachchildsiderowjoinswithexactlyone
parentsiderow.Thebenefitsofmaintainingthiscondition
aredescribedin"CreatingDimensions"(dimen.htm#i1006266).
Youcanenforcethisconditionbyadding FOREIGN KEY and
NOTNULL constraintsonthechildsidejoinkeysand
PRIMARY KEY constraintsontheparentsidejoinkeys.
Guideline2
Dimensions
Guideline3
Dimensions
Ifdimensionsaredenormalizedorpartiallydenormalized,
hierarchicalintegritymustbemaintainedbetweenthekey
columnsofthedimensiontable.Eachchildkeyvaluemust
uniquelyidentifyitsparentkeyvalue,evenifthedimension
tableisdenormalized.Hierarchicalintegrityina
denormalizeddimensioncanbeverifiedbycallingthe
VALIDATE_DIMENSION procedureofthe DBMS_DIMENSION
package.
Factanddimensiontablesshouldsimilarlyguaranteethat
eachfacttablerowjoinswithexactlyonedimensiontable
row.Thisconditionmustbedeclared,andoptionally
enforced,byadding FOREIGN KEY and NOT NULL
constraintsonthefactkeycolumn(s)and PRIMARY KEY
constraintsonthedimensionkeycolumn(s),orbyusing
outerjoins.Inadatawarehouse,constraintsaretypically
enabledwiththe NOVALIDATE and RELY clausestoavoid
constraintenforcementperformanceoverhead.SeeOracle
DatabaseSQLLanguageReference
(../../server.111/b28286/toc.htm)forfurtherdetails.
Guideline4
Incremental
Loads
Guideline5
Incrementalloadsofyourdetaildatashouldbedoneusing
theSQL*Loaderdirectpathoption,oranybulkloaderutility
thatusesOracle'sdirectpathinterface.Thisincludes
INSERT ... ASSELECT withthe APPEND or PARALLEL
hints,wherethehintscausethedirectloaderlogtobeused
duringtheinsert.SeeOracleDatabaseSQLLanguage
Reference(../../server.111/b28286/toc.htm)and"Typesof
MaterializedViews"formoreinformation.
Range/compositepartitionyourtablesbyamonotonically
increasingtimecolumnifpossible(preferablyoftype DATE ).
Partitions
Guideline6
Dimensions
Guideline7
Time
Dimensions
Aftereachloadandbeforerefreshingyourmaterializedview,
usethe VALIDATE_DIMENSION procedureofthe
DBMS_DIMENSION packagetoincrementallyverify
dimensionalintegrity.
Ifatimedimensionappearsinthematerializedviewasa
timecolumn,partitionandindexthematerializedviewinthe
samemannerasyouhavethefacttables.
Ifyouareconcernedwiththetimerequiredtoenableconstraintsandwhether
anyconstraintsmightbeviolated,thenusethe ENABLE NOVALIDATE withthe
RELY clausetoturnonconstraintcheckingwithoutvalidatinganyofthe
existingconstraints.Theriskwiththisapproachisthatincorrectqueryresults
couldoccurifanyconstraintsarebroken.Therefore,asthedesigner,youmust
determinehowcleanthedataisandwhethertheriskofincorrectresultsistoo
great.
()
LoadingDataintoDataWarehouses
Apopularandefficientwaytoloaddataintoadatawarehouseordatamartis
touseSQL*Loaderwiththe DIRECT or PARALLEL option,DataPump,orto
useanotherloadertoolthatusestheOracledirectpathAPI.SeeOracle
DatabaseUtilities(../../server.111/b28319/ldr_concepts.htm#SUTIL003)fortherestrictions
andconsiderationswhenusingSQL*Loaderwiththe DIRECT or PARALLEL
keywords.
Loadingstrategiescanbeclassifiedasonephaseortwophase.Inonephase
loading,dataisloadeddirectlyintothetargettable,qualityassurancetestsare
performed,anderrorsareresolvedbyperformingDMLoperationspriorto
refreshingmaterializedviews.Ifalargenumberofdeletionsarepossible,then
storageutilizationcanbeadverselyaffected,buttemporaryspacerequirements
andloadtimeareminimized.
Inatwophaseloadingprocess:
Dataisfirstloadedintoatemporarytableinthewarehouse.
Qualityassuranceproceduresareappliedtothedata.
Referentialintegrityconstraintsonthetargettablearedisabled,andthelocal
indexinthetargetpartitionismarkedunusable.
Thedataiscopiedfromthetemporaryareaintotheappropriatepartitionof
thetargettableusing INSERT AS SELECT withthe PARALLEL or APPEND
hint.Thetemporarytableisthendropped.Alternatively,ifthetargettableis
partitioned,youcancreateanew(empty)partitioninthetargettableanduse
ALTERTABLE...EXCHANGEPARTITION toincorporatethetemporary
tableintothetargettable.SeeOracleDatabaseSQLLanguageReference
(../../server.111/b28286/toc.htm)formoreinformation.
Theconstraintsareenabled,usuallywiththe NOVALIDATE option.
Immediatelyafterloadingthedetaildataandupdatingtheindexesonthedetail
data,thedatabasecanbeopenedforoperation,ifdesired.Youcandisable
queryrewriteatthesystemlevelbyissuingan ALTER SYSTEM SET
QUERY_REWRITE_ENABLED = FALSE statementuntilallthematerializedviews
arerefreshed.
If QUERY_REWRITE_INTEGRITY issetto STALE_TOLERATED ,accesstothe
materializedviewcanbeallowedatthesessionleveltoanyuserswhodonot
requirethematerializedviewstoreflectthedatafromthelatestloadbyissuing
an ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE statement.This
scenariodoesnotapplywhen QUERY_REWRITE_INTEGRITY iseither
ENFORCED or TRUSTED becausethesystemensuresinthesemodesthatonly
materializedviewswithupdateddataparticipateinaqueryrewrite.
()
OverviewofMaterializedViewManagement
Tasks
Themotivationforusingmaterializedviewsistoimproveperformance,butthe
overheadassociatedwithmaterializedviewmanagementcanbecomea
significantsystemmanagementproblem.Whenreviewingorevaluatingsome
ofthenecessarymaterializedviewmanagementactivities,considersomeof
thefollowing:
Identifyingwhatmaterializedviewstocreateinitially.
Indexingthematerializedviews.
Ensuringthatallmaterializedviewsandmaterializedviewindexesare
refreshedproperlyeachtimethedatabaseisupdated.
Checkingwhichmaterializedviewshavebeenused.
Determininghoweffectiveeachmaterializedviewhasbeenonworkload
performance.
Measuringthespacebeingusedbymaterializedviews.
Determiningwhichnewmaterializedviewsshouldbecreated.
Determiningwhichexistingmaterializedviewsshouldbedropped.
Archivingolddetailandmaterializedviewdatathatisnolongeruseful.
Aftertheinitialeffortofcreatingandpopulatingthedatawarehouseordata
mart,themajoradministrationoverheadistheupdateprocess,whichinvolves:
Periodicextractionofincrementalchangesfromtheoperationalsystems.
Transformingthedata.
Verifyingthattheincrementalchangesarecorrect,consistent,andcomplete.
Bulkloadingthedataintothewarehouse.
Refreshingindexesandmaterializedviewssothattheyareconsistentwith
thedetaildata.
Theupdateprocessmustgenerallybeperformedwithinalimitedperiodoftime
knownasthe()updatewindow(glossary.htm#i997213).Theupdatewindow
dependsonthe()updatefrequency(glossary.htm#i997216)(suchasdailyor
weekly)andthenatureofthebusiness.Foradailyupdatefrequency,anupdate
windowoftwotosixhoursmightbetypical.
Youneedtoknowyourupdatewindowforthefollowingactivities:
Loadingthedetaildata
Updatingorrebuildingtheindexesonthedetaildata
Performingqualityassurancetestsonthedata
Refreshingthematerializedviews
Updatingtheindexesonthematerializedviews
()
TypesofMaterializedViews
()The SELECT clauseinthematerializedviewcreationstatementdefinesthe
datathatthematerializedviewistocontain.Onlyafewrestrictionslimitwhat
canbespecified.Anynumberoftablescanbejoinedtogether.Besidestables,
otherelementssuchasviews,inlineviews(subqueriesinthe FROM clauseofa
SELECT statement),subqueries,andmaterializedviewscanallbejoinedor
referencedinthe SELECT clause.Youcannot,however,defineamaterialized
viewwithasubqueryinthe SELECT listofthedefiningquery.Youcan,
however,includesubquerieselsewhereinthedefiningquery,suchasinthe
WHERE clause.
Thetypesofmaterializedviewsare:
MaterializedViewswithAggregates
MaterializedViewsContainingOnlyJoins
NestedMaterializedViews
()
MaterializedViewswith()Aggregates
In()datawarehouses,materializedviewsnormallycontainaggregatesas
showninExample81.Forfastrefreshtobepossible,the SELECT listmust
containallofthe GROUP BY columns(ifpresent),andtheremustbea
materializedviewlogsmustbepresentonalltablesreferencedinthequery
thatdefinesthematerializedview.Thevalidaggregatefunctionsare: SUM ,
COUNT(x) , COUNT(*) , AVG , VARIANCE , STDDEV , MIN ,and MAX ,andthe
expressiontobeaggregatedcanbeanySQLvalueexpression.See
"RestrictionsonFastRefreshonMaterializedViewswithAggregates".
Fastrefreshforamaterializedviewcontainingjoinsandaggregatesispossible
afteranytypeofDMLtothebasetables(directloadorconventional INSERT ,
UPDATE ,or DELETE ).Itcanbedefinedtoberefreshed ON COMMIT or ON
DEMAND .A REFRESHON COMMIT materializedviewwillberefreshed
automaticallywhenatransactionthatdoesDMLtooneofthematerialized
view'sdetailtablescommits.Thetimetakentocompletethecommitmaybe
slightlylongerthanusualwhenthismethodischosen.Thisisbecausethe
refreshoperationisperformedaspartofthecommitprocess.Therefore,this
methodmaynotbesuitableifmanyusersareconcurrentlychangingthetables
uponwhichthematerializedviewisbased.
Herearesomeexamplesofmaterializedviewswithaggregates.Notethat
materializedviewlogsareonlycreatedbecausethismaterializedviewwillbe
fastrefreshed.
()Example81Example1:CreatingaMaterializedView
CREATEMATERIALIZEDVIEWLOGONproductsWITHSEQUENCE,ROWID
(prod_id,prod_name,prod_desc,prod_subcategory,prod_subcategory_de
prod_category,prod_category_desc,prod_weight_class,prod_unit_of_me
prod_pack_size,supplier_id,prod_status,prod_list_price,prod_min_
INCLUDINGNEWVALUES;
CREATEMATERIALIZEDVIEWLOGONsales
WITHSEQUENCE,ROWID
(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amou
INCLUDINGNEWVALUES;
CREATEMATERIALIZEDVIEWproduct_sales_mv
PCTFREE0TABLESPACEdemo
STORAGE(INITIAL8kNEXT8kPCTINCREASE0)
BUILDIMMEDIATE
REFRESHFAST
ENABLEQUERYREWRITE
ASSELECTp.prod_name,SUM(s.amount_sold)ASdollar_sales,
COUNT(*)AScnt,COUNT(s.amount_sold)AScnt_amt
FROMsaless,productsp
WHEREs.prod_id=p.prod_idGROUPBYp.prod_name;
CREATEMATERIALIZEDVIEWproduct_sales_mv
PCTFREE0TABLESPACEdemo
STORAGE(INITIAL16kNEXT16kPCTINCREASE0)
BUILDDEFERRED
REFRESHCOMPLETEONDEMAND
ENABLEQUERYREWRITEAS
SELECTp.prod_name,SUM(s.amount_sold)ASdollar_sales
FROMsaless,productspWHEREs.prod_id=p.prod_id
GROUPBYp.prod_name;
CREATEMATERIALIZEDVIEWLOGONsalesWITHSEQUENCE,ROWID
(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amou
INCLUDINGNEWVALUES;
CREATEMATERIALIZEDVIEWsum_sales
PARALLEL
BUILDIMMEDIATE
REFRESHFASTONCOMMITAS
SELECTs.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_sales
FROMsaless
GROUPBYs.prod_id,s.time_id;
Thisexamplecreatesamaterializedviewthatcontainsaggregatesonasingle
table.Becausethematerializedviewloghasbeencreatedwithallreferenced
columnsinthematerializedview'sdefiningquery,thematerializedviewisfast
refreshable.IfDMLisappliedagainstthe sales table,thenthechangeswill
bereflectedinthematerializedviewwhenthecommitisissued.
()
RequirementsforUsingMaterializedViewswithAggregates
Table82illustratestheaggregaterequirementsformaterializedviews.If
aggregate X ispresent,aggregate Y isrequiredandaggregate Z isoptional.
()()Table82RequirementsforMaterializedViewswithAggregates
COUNT(expr)
MIN(expr)
MAX(expr)
SUM(expr)
COUNT(expr)
SUM(col) , col
AVG(expr)
COUNT(expr)
SUM(expr)
STDDEV(expr)
COUNT(expr)SUM(expr)
SUM(expr*expr)
VARIANCE(expr)
COUNT(expr)SUM(expr)
SUM(expr*expr)
()
MaterializedViews()ContainingOnlyJoins
Somematerializedviewscontainonlyjoinsandnoaggregates,suchasin
Example84,whereamaterializedviewiscreatedthatjoinsthe sales tableto
the times and customers tables.Theadvantageofcreatingthistypeof
materializedviewisthatexpensivejoinswillbeprecalculated.
Fastrefreshforamaterializedviewcontainingonlyjoinsispossibleafterany
typeofDMLtothebasetables(directpathorconventional INSERT , UPDATE ,
or DELETE ).
Amaterializedviewcontainingonlyjoinscanbedefinedtoberefreshed
ONCOMMIT or ON DEMAND .Ifitis ON COMMIT ,therefreshisperformedat
committimeofthetransactionthatdoesDMLonthematerializedview'sdetail
table.
Ifyouspecify REFRESH FAST ,Oracleperformsfurtherverificationofthequery
definitiontoensurethatfastrefreshcanbeperformedifanyofthedetailtables
change.Theseadditionalchecksare:
Amaterializedviewlogmustbepresentforeachdetailtableunlessthetable
supportsPCT.Also,whenamaterializedviewlogisrequired,the ROWID
columnmustbepresentineachmaterializedviewlog.
Therowidsofallthedetailtablesmustappearinthe SELECT listofthe
materializedviewquerydefinition.
Ifsomeoftheserestrictionsarenotmet,youcancreatethematerializedview
as REFRESH FORCE totakeadvantageoffastrefreshwhenitispossible.Ifone
ofthetablesdidnotmeetallofthecriteria,buttheothertablesdid,the
materializedviewwouldstillbefastrefreshablewithrespecttotheothertables
forwhichallthecriteriaaremet.
()
MaterializedJoinViewsFROMClauseConsiderations
Ifthematerializedviewcontainsonlyjoins,the ROWID columnsforeachtable
(andeachinstanceofatablethatoccursmultipletimesinthe FROM list)must
bepresentinthe SELECT listofthematerializedview.
Ifthematerializedviewhasremotetablesinthe FROM clause,alltablesinthe
FROM clausemustbelocatedonthatsamesite.Further, ON COMMIT refreshis
notsupportedformaterializedviewwithremotetables.Materializedviewlogs
mustbepresentontheremotesiteforeachdetailtableofthematerializedview
and ROWID columnsmustbepresentinthe SELECT listofthematerialized
view,asshowninthefollowingexample.
()Example84MaterializedViewContainingOnlyJoins
CREATEMATERIALIZEDVIEWLOGONsalesWITHROWID;
CREATEMATERIALIZEDVIEWLOGONtimesWITHROWID;
CREATEMATERIALIZEDVIEWLOGONcustomersWITHROWID;
CREATEMATERIALIZEDVIEWdetail_sales_mv
PARALLELBUILDIMMEDIATE
REFRESHFASTAS
SELECTs.rowid"sales_rid",t.rowid"times_rid",c.rowid"customers_r
c.cust_id,c.cust_last_name,s.amount_sold,s.quantity_sold,s
FROMsaless,timest,customersc
WHEREs.cust_id=c.cust_id(+)ANDs.time_id=t.time_id(+);
Alternatively,ifthepreviousexampledidnotincludethecolumns times_rid
and customers_rid ,andiftherefreshmethodwas REFRESH FORCE ,then
thismaterializedviewwouldbefastrefreshableonlyifthesalestablewas
updatedbutnotifthetables times or customers wereupdated.
CREATEMATERIALIZEDVIEWdetail_sales_mv
PARALLEL
BUILDIMMEDIATE
REFRESHFORCEAS
SELECTs.rowid"sales_rid",c.cust_id,c.cust_last_name,s.amount_sol
s.quantity_sold,s.time_id
FROMsaless,timest,customersc
WHEREs.cust_id=c.cust_id(+)ANDs.time_id=t.time_id(+);
()
NestedMaterializedViews
()()Anestedmaterializedviewisamaterializedviewwhosedefinitionisbased
onanothermaterializedview.Anestedmaterializedviewcanreferenceother
relationsinthedatabaseinadditiontoreferencingmaterializedviews.
()
WhyUseNestedMaterializedViews?
Inadatawarehouse,youtypicallycreatemanyaggregateviewsonasingle
join(forexample,rollupsalongdifferentdimensions).Incrementallymaintaining
thesedistinctmaterializedaggregateviewscantakealongtime,becausethe
underlyingjoinhastobeperformedmanytimes.
Usingnestedmaterializedviews,youcancreatemultiplesingletable
materializedviewsbasedonajoinsonlymaterializedviewandthejoinis
performedjustonce.Inaddition,optimizationscanbeperformedforthisclass
ofsingletableaggregatematerializedviewandthusrefreshisveryefficient.
()Example85NestedMaterializedView
Youcancreateanestedmaterializedviewonmaterializedviews,butallparent
andbasematerializedviewsmustcontainjoinsoraggregates.Ifthedefining
queriesforamaterializedviewdonotcontainjoinsoraggregates,itcannotbe
nested.Alltheunderlyingobjects(materializedviewsortables)onwhichthe
materializedviewisdefinedmusthaveamaterializedviewlog.Allthe
underlyingobjectsaretreatedasiftheyweretables.Inaddition,youcanuseall
theexistingoptionsformaterializedviews.
Usingthetablesandtheircolumnsfromthe sh sampleschema,thefollowing
materializedviewsillustratehownestedmaterializedviewscanbecreated.
CREATEMATERIALIZEDVIEWLOGONsalesWITHROWID;
CREATEMATERIALIZEDVIEWLOGONcustomersWITHROWID;
CREATEMATERIALIZEDVIEWLOGONtimesWITHROWID;
/*creatematerializedviewjoin_sales_cust_timeasfastrefreshablea
COMMITtime*/
CREATEMATERIALIZEDVIEWjoin_sales_cust_time
REFRESHFASTONCOMMITAS
SELECTc.cust_id,c.cust_last_name,s.amount_sold,t.time_id,
t.day_number_in_week,s.rowidsrid,t.rowidtrid,c.rowidcrid
FROMsaless,customersc,timest
WHEREs.time_id=t.time_idANDs.cust_id=c.cust_id;
Tocreateanestedmaterializedviewonthetable join_sales_cust_time ,
youwouldhavetocreateamaterializedviewlogonthetable.Becausethiswill
beasingletableaggregatematerializedviewon join_sales_cust_time ,
youneedtologallthenecessarycolumnsandusethe INCLUDING NEW
VALUES clause.
/*creatematerializedviewlogonjoin_sales_cust_time*/
CREATEMATERIALIZEDVIEWLOGONjoin_sales_cust_time
WITHROWID(cust_last_name,day_number_in_week,amount_sold)
INCLUDINGNEWVALUES;
/*createthesingle-tableaggregatematerializedviewsum_sales_cust
onjoin_sales_cust_timeasfastrefreshableatCOMMITtime*/
CREATEMATERIALIZEDVIEWsum_sales_cust_time
REFRESHFASTONCOMMITAS
SELECTCOUNT(*)cnt_all,SUM(amount_sold)sum_sales,COUNT(amount_sol
cnt_sales,cust_last_name,day_number_in_week
FROMjoin_sales_cust_time
GROUPBYcust_last_name,day_number_in_week;
()
NestingMaterializedViewswithJoinsandAggregates
Sometypesofnestedmaterializedviewscannotbefastrefreshed.Use
EXPLAIN_MVIEW toidentifythosetypesofmaterializedviews.Youcanrefresh
atreeofnestedmaterializedviewsintheappropriatedependencyorderby
specifyingthe nested=TRUE parameterwiththe DBMS_MVIEW.REFRESH
parameter.Forexample,ifyoucall
DBMS_MVIEW.REFRESH('SUM_SALES_CUST_TIME',nested=>TRUE) ,
the REFRESH procedurewillfirstrefreshthe join_sales_cust_time
materializedview,andthenrefreshthe sum_sales_cust_time materialized
view.
()
NestedMaterializedViewUsageGuidelines
Youshouldkeepthefollowinginmindwhendecidingwhethertousenested
materializedviews:
Ifyouwanttousefastrefresh,youshouldfastrefreshallthematerialized
viewsalonganychain.
Ifyouwantthehighestlevelmaterializedviewtobefreshwithrespecttothe
detailtables,youneedtoensurethatallmaterializedviewsinatreeare
refreshedinthecorrectdependencyorderbeforerefreshingthehighest
level.Youcanautomaticallyrefreshintermediatematerializedviewsina
nestedhierarchyusingthe nested=TRUE parameter,asdescribedin
"NestingMaterializedViewswithJoinsandAggregates".Ifyoudonotspecify
nested=TRUE andthematerializedviewsunderthehighestlevel
materializedviewarestale,refreshingonlythehighestlevelwillsucceed,but
makesitfreshonlywithrespecttoitsunderlyingmaterializedview,notthe
detailtablesatthebaseofthetree.
Whenrefreshingmaterializedviews,youneedtoensurethatallmaterialized
viewsinatreearerefreshed.Ifyouonlyrefreshthehighestlevel
materializedview,thematerializedviewsunderitwillbestaleandyoumust
explicitlyrefreshthem.Ifyouusethe REFRESH procedurewiththe nested
parametervaluesetto TRUE ,onlyspecifiedmaterializedviewsandtheir
childmaterializedviewsinthetreearerefreshed,andnottheirtoplevel
materializedviews.Usethe REFRESH_DEPENDENT procedurewiththe
nestedparametervaluesetto TRUE ifyouwanttoensurethatall
materializedviewsinatreearerefreshed.
Freshnessofamaterializedviewiscalculatedrelativetotheobjectsdirectly
referencedbythematerializedview.Whenamaterializedviewreferences
anothermaterializedview,thefreshnessofthetopmostmaterializedviewis
calculatedrelativetochangesinthematerializedviewitdirectlyreferences,
notrelativetochangesinthetablesreferencedbythematerializedviewit
references.
()
RestrictionsWhenUsingNestedMaterializedViews
()()Youcannotcreatebothamaterializedviewandaprebuiltmaterializedview
CreatingMaterializedViews
()Amaterializedviewcanbecreatedwiththe CREATE MATERIALIZED VIEW
statementorusingEnterpriseManager.Example86illustratescreatingan
materializedviewcalled cust_sales_mv .
()Example86CreatingaMaterializedView
CREATEMATERIALIZEDVIEWcust_sales_mv
PCTFREE0TABLESPACEdemo
STORAGE(INITIAL16kNEXT16kPCTINCREASE0)
PARALLEL
BUILDIMMEDIATE
REFRESHCOMPLETE
ENABLEQUERYREWRITEAS
SELECTc.cust_last_name,SUM(amount_sold)ASsum_amount_sold
FROMcustomersc,salessWHEREs.cust_id=c.cust_id
GROUPBYc.cust_last_name;
Itisnotuncommoninadatawarehousetohavealreadycreatedsummaryor
aggregationtables,andyoumightnotwishtorepeatthisworkbybuildinga
newmaterializedview.Inthiscase,thetablethatalreadyexistsinthedatabase
canberegisteredasa()()prebuiltmaterializedview.Thistechniqueis
describedin"RegisteringExistingMaterializedViews".
Onceyouhaveselectedthematerializedviewsyouwanttocreate,followthese
stepsforeachmaterializedview.
1. Designthematerializedview.Existinguserdefinedmaterializedviewsdonot
requirethisstep.Ifthematerializedviewcontainsmanyrows,then,if
appropriate,thematerializedviewshouldbepartitioned(ifpossible)and
shouldmatchthepartitioningofthelargestormostfrequentlyupdateddetail
orfacttable(ifpossible).Refreshperformancebenefitsfrompartitioning,
becauseitcantakeadvantageofparallelDMLcapabilitiesandpossiblePCT
basedrefresh.
2. Usethe CREATE MATERIALIZED VIEW statementtocreateand,optionally,
populatethematerializedview.Ifauserdefinedmaterializedviewalready
exists,thenusethe ON PREBUILT TABLE clauseinthe CREATE
MATERIALIZED VIEW statement.Otherwise,usethe BUILD IMMEDIATE
clausetopopulatethematerializedviewimmediately,orthe BUILD
DEFERRED clausetopopulatethematerializedviewlater.A BUILD
DEFERRED materializedviewisdisabledforusebyqueryrewriteuntilthe
first COMPLETE REFRESH ,afterwhichitwillbeautomaticallyenabled,
providedthe ENABLE QUERY REWRITE clausehasbeenspecified.
SeeAlso:
()()()OracleDatabaseSQLLanguageReference
(../../server.111/b28286/toc.htm)fordescriptionsoftheSQLstatements
()
CreatingMaterializedViewswithColumnAlias
Lists
Currently,whenamaterializedviewiscreated,ifitsdefiningquerycontains
samenamecolumnsinthe SELECT list,thenameconflictsneedtoberesolved
byspecifyinguniquealiasesforthosecolumns.Otherwise,the CREATE
MATERIALIZED VIEW statementwillfailwiththeerrormessagesofcolumns
ambiguouslydefined.However,thestandardmethodofattachingaliasesinthe
SELECT clausefornameresolutionrestrictstheuseofthefulltextmatchquery
rewriteanditwilloccuronlywhenthetextofthematerializedview'sdefining
queryandthetextofuserinputqueryareidentical.Thus,iftheuserspecifies
selectaliasesinthematerializedview'sdefiningquerywhilethereisnoaliasin
thequery,thefulltextmatchcomparisonwillfail.Thisisparticularlyaproblem
forqueriesfromDiscoverer,whichmakesextensiveuseofcolumnaliases.
Thefollowingisanexampleoftheproblem. sales_mv iscreatedwithcolumn
aliasesinthe SELECT clausebuttheinputquery Q1 doesnothavethealiases.
Thefulltextmatchrewritewillfail.Thematerializedviewisasfollows:
CREATEMATERIALIZEDVIEWsales_mv
ENABLEQUERYREWRITEAS
SELECTs.time_idsales_tid,c.time_idcosts_tid
FROMsaless,productsp,costsc
WHEREs.prod_id=p.prod_idANDc.prod_id=p.prod_idAND
p.prod_nameIN(SELECTprod_nameFROMproducts);
Inputquerystatement Q1 isasfollows:
SELECTs.time_id,c.time_id
FROMsaless,productsp,costsc
WHEREs.prod_id=p.prod_idANDc.prod_id=p.prod_idAND
p.prod_nameIN(SELECTprod_nameFROMproducts);
Eventhoughthematerializedview'sdefiningqueryisalmostidenticaland
logicallyequivalenttotheuser'sinputquery,queryrewritedoesnothappen
becauseofthefailureoffulltextmatchthatistheonlyrewritepossibilityfor
somequeries(forexample,asubqueryinthe WHERE clause).
Youcanaddacolumnaliaslisttoa CREATE MATERIALIZED VIEW statement.
Thecolumnaliaslistexplicitlyresolvesanycolumnnameconflictwithout
attachingaliasesinthe SELECT clauseofthematerializedview.Thesyntaxof
thematerializedviewcolumnaliaslistisillustratedinthefollowingexample:
CREATEMATERIALIZEDVIEWsales_mv(sales_tid,costs_tid)
ENABLEQUERYREWRITEAS
SELECTs.time_id,c.time_id
FROMsaless,productsp,costsc
WHEREs.prod_id=p.prod_idANDc.prod_id=p.prod_idAND
p.prod_nameIN(SELECTprod_nameFROMproducts);
NamingMaterializedViews
()ThenameofamaterializedviewmustconformtostandardOraclenaming
conventions.However,ifthematerializedviewisbasedonauserdefined
prebuilttable,thenthenameofthematerializedviewmustexactlymatchthat
tablename.
Ifyoualreadyhaveanamingconventionfortablesandindexes,youmight
considerextendingthisnamingschemetothematerializedviewssothatthey
areeasilyidentifiable.Forexample,insteadofnamingthematerializedview
sum_of_sales ,itcouldbecalled sum_of_sales_mv todenotethatthisisa
materializedviewandnotatableorview.
()
StorageAndTableCompression
()Unlessthematerializedviewisbasedon()()()()auserdefinedprebuilttable,
itrequiresandoccupiesstoragespaceinsidethedatabase.Therefore,the
storageneedsforthematerializedviewshouldbespecifiedintermsofthe
tablespacewhereitistoresideandthesizeoftheextents.
Ifyoudonotknowhowmuchspacethematerializedviewwillrequire,thenthe
DBMS_MVIEW.ESTIMATE_SIZE packagecanestimatethenumberofbytes
requiredtostorethisuncompressedmaterializedview.Thisinformationcan
thenassistthedesignteamindeterminingthetablespaceinwhichthe
materializedviewshouldreside.
Youshouldusetablecompressionwithhighlyredundantdata,suchastables
withmanyforeignkeys.Thisisparticularlyusefulformaterializedviewscreated
withthe ROLLUP clause.Tablecompressionreducesdiskuseandmemoryuse
(specifically,thebuffercache),oftenleadingtoabetterscaleupforreadonly
operations.Tablecompressioncanalsospeedupqueryexecutionatthe
expenseofupdatecost.
SeeAlso:
OracleDatabaseSQLLanguageReference
(../../server.111/b28286/statements_10.htm#SQLRF017)foracomplete
descriptionof STORAGE semantics,OracleDatabasePerformance
TuningGuide(../../server.111/b28274/toc.htm),andOracleDatabaseVLDB
andPartitioningGuide(../../server.111/b32024/part_avail.htm#VLDBG004)for
tablecompressionexamples
()
BuildMethods
()()Twobuildmethodsareavailableforcreatingthematerializedview,as
BuildMethod
Description
BUILD IMMEDIATE
Createthe
materializedviewand
thenpopulateitwith
data.
BUILD DEFERRED
Createthe
materializedview
definitionbutdonot
populateitwithdata.
()
EnablingQueryRewrite
Before()creatingamaterializedview,youcanverifywhattypesofqueryrewrite
arepossiblebycallingtheprocedure DBMS_MVIEW.EXPLAIN_MVIEW ,oruse
DBMS_ADVISOR.TUNE_MVIEW tooptimizethematerializedviewsothatmany
typesofqueryrewritearepossible.Oncethematerializedviewhasbeen
created,youcanuse DBMS_MVIEW.EXPLAIN_REWRITE tofindoutif(orwhy
not)itwillrewriteaspecificquery.
Eventhoughamaterializedviewisdefined,itwillnotautomaticallybeusedby
thequeryrewritefacility.Eventhoughqueryrewriteisenabledbydefault,you
alsomustspecifythe ENABLE QUERY REWRITE clauseifthematerializedview
istobeconsideredavailableforrewritingqueries.
Ifthisclauseisomittedorspecifiedas DISABLE QUERY REWRITE whenthe
materializedviewiscreated,thematerializedviewcansubsequentlybe
enabledforqueryrewritewiththe ALTER MATERIALIZED VIEW statement.
Ifyoudefineamaterializedviewas BUILD DEFERRED ,itisnoteligiblefor
queryrewriteuntilitispopulatedwithdatathroughacompleterefresh.
()
QueryRewriteRestrictions
()()()()Queryrewriteisnotpossiblewithallmaterializedviews.Ifqueryrewrite
MaterializedViewRestrictions()
Youshouldkeepinmindthefollowingrestrictions:
Thedefiningqueryofthematerializedviewcannotcontainanynon
repeatableexpressions( ROWNUM , SYSDATE ,nonrepeatablePL/SQL
functions,andsoon).
Thequerycannotcontainanyreferencesto RAW or LONG RAW datatypesor
object REF s.
()
GeneralQueryRewriteRestrictio()()ns
Youshouldkeepinmindthefollowingrestrictions:
Aquerycanreferencebothlocalandremotetables.Suchaquerycanbe
rewrittenaslongasaneligiblematerializedviewreferencingthesametables
isavailablelocally.
Neitherthedetailtablesnorthematerializedviewcanbeownedby SYS .
Ifacolumnorexpressionispresentinthe GROUP BY clauseofthe
materializedview,itmustalsobepresentinthe SELECT list.
Aggregatefunctionsmustoccuronlyastheoutermostpartoftheexpression.
Thatis,aggregatessuchas AVG(AVG(x)) or AVG(x) + AVG(x) arenot
allowed.
CONNECT BY clausesarenotallowed.
()
RefreshOptions
()Whenyoudefineamaterializedview,youcanspecifythreerefreshoptions:
howtorefresh,whattypeofrefresh,andcantrustedconstraintsbeused.If
unspecified,thedefaultsareassumedas ON DEMAND , FORCE ,and ENFORCED
constraintsrespectively.
Thetworefreshexecutionmodesare ON COMMIT and ON DEMAND .
Dependingonthematerializedviewyoucreate,someoftheoptionsmaynot
beavailable.Table84describestherefreshmodes.
()()Table84RefreshModes
Refresh
Mode
ONCOMMIT
()
Description
Refreshoccursautomaticallywhenatransactionthat
modifiedoneofthematerializedview'sdetailtables
commits.Thiscanbespecifiedaslongasthematerialized
viewisfastrefreshable(inotherwords,notcomplex).The
ON COMMIT privilegeisnecessarytousethismode.
ONDEMAND
()
Refreshoccurswhenausermanuallyexecutesoneofthe
availablerefreshprocedurescontainedinthe DBMS_MVIEW
package( REFRESH , REFRESH_ALL_MVIEWS ,
REFRESH_DEPENDENT ).
Refresh
Option
COMPLETE()
FAST()
Description
Refreshesbyrecalculatingthematerializedview's
definingquery.
Appliesincrementalchangestorefreshthematerialized
viewusingtheinformationloggedinthematerializedview
logs,orfromaSQL*Loaderdirectpathorapartition
maintenanceoperation.
FORCE()
NEVER()
Indicatesthatthematerializedviewwillnotberefreshed
withrefreshmechanisms.
Whetherthefastrefreshoptionisavailabledependsuponthetypeof
materializedview.Youcancalltheprocedure DBMS_MVIEW.EXPLAIN_MVIEW
todeterminewhetherfastrefreshispossible.
Youcanalsospecifyifitisacceptabletousetrustedconstraintsand
QUERY_REWRITE_INTEGRITY=TRUSTED duringrefresh.Anynonvalidated
RELY constraintisatrustedconstraint.Forexample,nonvalidatedforeign
key/primarykeyrelationships,functionaldependenciesdefinedindimensions
oramaterializedviewinthe UNKNOWN state.Ifqueryrewriteisenabledduring
refresh,thesecanimprovetheperformanceofrefreshbyenablingmore
performantqueryrewrites.Anymaterializedviewthatcanuse TRUSTED
constraintsforrefreshisleftinastateoftrustedfreshness(the UNKNOWN state)
afterrefresh.
Thisisreflectedinthecolumn STALENESS intheview USER_MVIEWS .The
column UNKNOWN_TRUSTED_FD inthesameviewisalsosetto Y ,whichmeans
yes.
Youcandefinethispropertyofthematerializedvieweitherduringcreatetime
byspecifying REFRESH USING TRUSTED [ENFORCED] CONSTRAINTS orby
using ALTER MATERIALIZED VIEW DDL.
()()Table86Constraints
ConstraintstoUse
TRUSTEDCONSTRAINTS
Description
Refreshcanusetrustedconstraintsand
QUERY_REWRITE_INTEGRITY =TRUSTED
duringrefresh.Thisallowsuseofnon
ENFORCEDCONSTRAINTS
Refreshcanusevalidatedconstraintsand
QUERY_REWRITE_INTEGRITY=ENFORCED
duringrefresh.Thisallowsuseofonly
validated,enforcedconstraintsandrewrite
againstmaterializedviewsin FRESH state
duringrefresh.
()
GeneralRestrictionson()()FastRefresh
Thedefiningqueryofthematerializedviewisrestrictedasfollows:
Thematerializedviewmustnotcontainreferencestononrepeating
expressionslike SYSDATE and ROWNUM .
Thematerializedviewmustnotcontainreferencesto RAW or LONG RAW
datatypes.
Itcannotcontaina SELECT listsubquery.
Itcannotcontainanalyticalfunctions(forexample, RANK )inthe SELECT
clause.
Itcannotcontaina MODEL clause.
Itcannotcontaina HAVING clausewithasubquery.
Itcannotcontainnestedqueriesthathave ANY , ALL ,or NOT EXISTS .
Itcannotcontaina [STARTWITH]CONNECTBY clause.
Itcannotcontainmultipledetailtablesatdifferentsites.
ON COMMIT materializedviewscannothaveremotedetailtables.
Nestedmaterializedviewsmusthaveajoinoraggregate.
()
RestrictionsonFastRefreshonMaterializedViewswithJoins
Only
Definingqueriesformaterializedviewswithjoinsonlyandnoaggregateshave
thefollowingrestrictionsonfastrefresh:
Allrestrictionsfrom"GeneralRestrictionsonFastRefresh".
Theycannothave GROUP BY clausesoraggregates.
Rowidsofallthetablesinthe FROM listmustappearinthe SELECT listof
thequery.
Materializedviewlogsmustexistwithrowidsforallthebasetablesinthe
FROM listofthequery.
Youcannotcreateafastrefreshablematerializedviewfrommultipletables
withsimplejoinsthatincludeanobjecttypecolumninthe SELECT
statement.
()
RestrictionsonFastRefreshonMaterializedViewswith
Aggregates
Definingqueriesformaterializedviewswithaggregatesorjoinshavethe
followingrestrictionsonfastrefresh:
Allrestrictionsfrom"GeneralRestrictionsonFastRefresh".
Alltablesinthematerializedviewmusthavematerializedviewlogs,andthe
materializedviewlogsmust:
Containallcolumnsfromthetablereferencedinthematerializedview.
However,noneofthesecolumnsinthebasetablecanbeencrypted.
Specifywith ROWID and INCLUDING NEW VALUES .
Only SUM , COUNT , AVG , STDDEV , VARIANCE , MIN and MAX aresupported
forfastrefresh.
COUNT(*) mustbespecified.
Aggregatefunctionsmustoccuronlyastheoutermostpartoftheexpression.
Thatis,aggregatessuchas AVG(AVG(x)) or AVG(x) + AVG(x) arenot
allowed.
Foreachaggregatesuchas AVG(expr) ,thecorresponding COUNT(expr)
mustbepresent.Oraclerecommendsthat SUM(expr) bespecified.See
Table82forfurtherdetails.
If VARIANCE(expr) or STDDEV(expr )isspecified, COUNT(expr) and
SUM(expr) mustbespecified.Oraclerecommendsthat
SUM(expr*expr) bespecified.SeeTable82forfurtherdetails.
Iftherearenoouterjoins,youmayhavearbitraryselectionsandjoinsinthe
WHERE clause.
Materializedaggregateviewswithouterjoinsarefastrefreshableafter
conventionalDMLanddirectloads,providedonlytheoutertablehasbeen
modified.Also,uniqueconstraintsmustexistonthejoincolumnsoftheinner
jointable.Ifthereareouterjoins,allthejoinsmustbeconnectedby AND s
andmustusetheequality( = )operator.
Formaterializedviewswith CUBE , ROLLUP ,groupingsets,orconcatenation
ofthem,thefollowingrestrictionsapply:
()
RestrictionsonFastRefreshonMaterializedViewswith
UNIONALL
Materializedviewswiththe UNION ALL setoperatorsupportthe REFRESH
FAST optionifthefollowingconditionsaresatisfied:
CREATEVIEWview_with_unionallAS
(SELECTc.rowidcrid,c.cust_id,2umarker
FROMcustomerscWHEREc.cust_last_name='Smith'
UNIONALL
SELECTc.rowidcrid,c.cust_id,3umarker
FROMcustomerscWHEREc.cust_last_name='Jones');
CREATEMATERIALIZEDVIEWunionall_inside_view_mv
REFRESHFASTONDEMANDAS
SELECT*FROMview_with_unionall;
()
AchievingRefreshGoals
Inadditiontothe EXPLAIN_MVIEW procedure,whichisdiscussedthroughout
thischapter,youcanusethe DBMS_ADVISOR.TUNE_MVIEW procedureto
optimizea CREATE MATERIALIZED VIEW statementtoachieve REFRESH
RefreshingNestedMaterializedViews
Anestedmaterializedviewisconsideredtobefreshaslongasitsdatais
synchronizedwiththedatainitsdetailtables,evenifsomeofitsdetailtables
couldbestalematerializedviews.
Youcanrefreshnestedmaterializedviewsintwoways:
DBMS_MVIEW.REFRESH withthe nested flagsetto TRUE and
REFRESH_DEPENDENT withthe nested flagsetto TRUE onthebasetables.If
youuse DBMS_MVIEW.REFRESH ,theentirematerializedviewchainisrefreshed
andthecoveragestartingfromthespecifiedmaterializedviewintopdown
fashion.Thatis,thespecifiedmaterializedviewandallitschildmaterialized
viewsinthedependencyhierarchyarerefreshedinorder.With
DBMS_MVIEW.REFRESH_DEPENDENT ,theentirechainisrefreshedfromthe
bottomup.Thatis,alltheparentmaterializedviewsinthedependency
hierarchystartingfromthespecifiedtablearerefreshedinorder.
()Example87ExampleofRefreshingaNestedMaterializedView
Thefollowingstatementshowsanexampleofrefreshinganestedmaterialized
view:
DBMS_MVIEW.REFRESH('SALES_MV,COST_MV',nested=>TRUE);
ORDERBYClause
()An ORDER BY clauseisallowedinthe CREATE MATERIALIZED VIEW
statement.Itisusedonlyduringtheinitialcreationofthematerializedview.Itis
notusedduringafullrefreshorafastrefresh.
Toimprovetheperformanceofqueriesagainstlargematerializedviews,store
therowsinthematerializedviewintheorderspecifiedinthe ORDER BY
clause.Thisinitialorderingprovidesphysicalclusteringofthedata.Ifindexes
arebuiltonthecolumnsbywhichthematerializedviewisordered,accessing
therowsofthematerializedviewusingtheindexoftenreducesthetimefordisk
I/Oduetothephysicalclustering.
MaterializedViewLogs
Materializedview()()logsarerequiredifyouwanttousefastrefresh,withthe
exceptionofPCTrefresh.Thatis,ifadetailtablesupportsPCTfora
materializedview,thematerializedviewlogonthatdetailtableisnotrequiredin
ordertodofastrefreshonthatmaterializedview.Asageneralrule,though,you
shouldcreatematerializedviewlogsifyouwanttousefastrefresh.
Materializedviewlogsaredefinedusinga CREATE MATERIALIZED VIEW LOG
statementonthebasetablethatistobechanged.Theyarenotcreatedonthe
materializedviewunlessthereisanothermaterializedviewontopofthat
materializedview,whichisthecasewithnestedmaterializedviews.Forfast
refreshofmaterializedviews,thedefinitionofthematerializedviewlogsmust
normallyspecifythe ROWID clause.Inaddition,foraggregatematerialized
views,itmustalsocontaineverycolumninthetablereferencedinthe
materializedview,the INCLUDING NEW VALUES clauseandthe SEQUENCE
clause.
Anexampleofamaterializedviewlogisshownasfollowswhereoneiscreated
onthetable sales :
CREATEMATERIALIZEDVIEWLOGONsalesWITHROWID
(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amou
INCLUDINGNEWVALUES;
Alternatively,amaterializedviewlogcanbeamendedtoincludetherowid,as
inthefollowing:
ALTERMATERIALIZEDVIEWLOGONsalesADDROWID
(prod_id,cust_id,time_id,channel_id,promo_id,quantity_sold,amou
INCLUDINGNEWVALUES;
materializedviewlogtosupportfastrefreshwithacombinationof INSERT ,
UPDATE ,or DELETE statementsonmultipletables.Youcan,however,addthe
SEQUENCE numbertothematerializedviewlogafterithasbeencreated.
TheboundaryofamixedDMLoperationisdeterminedbywhetherthe
materializedviewis ON COMMIT or ON DEMAND .
()
UsingtheFORCEOptionwithMaterializedViewLogs
Ifyouspecify FORCE andanyitemsspecifiedwiththe ADD clausehavealready
beenspecifiedforthematerializedviewlog,Oracledoesnotreturnanerror,
butsilentlyignorestheexistingelementsandaddstothematerializedviewlog
anyitemsthatdonotalreadyexistinthelog.Forexample,ifyouusedafilter
columnsuchas cust_id andthiscolumnalreadyexisted,OracleDatabase
ignorestheredundancyanddoesnotreturnanerror.
()
UsingOracleEnterpriseManager
AmaterializedviewcanalsobecreatedusingEnterpriseManagerbyselecting
thematerializedviewobjecttype.Thereisnodifferenceintheinformation
requiredifthisapproachisused.
()
UsingMaterializedViewswithNLS
Parameters
Whenusingcertainmaterializedviews,youmustensurethatyourNLS
parametersarethesameaswhenyoucreatedthematerializedview.
Materializedviewswiththisrestrictionareasfollows:
Expressionsthatmayreturndifferentvalues,dependingonNLSparameter
settings.Forexample,( date>"01/02/03" )or( rate<="2.150" )are
NLSparameterdependentexpressions.
Equijoinswhereonesideofthejoinischaracterdata.Theresultofthis
equijoindependsoncollationandthiscanchangeonasessionbasis,giving
anincorrectresultinthecaseofqueryrewriteoraninconsistentmaterialized
viewafterarefreshoperation.
Expressionsthatgenerateinternalconversiontocharacterdatainthe
SELECT listofamaterializedview,orinsideanaggregateofamaterialized
aggregateview.Thisrestrictiondoesnotapplytoexpressionsthatinvolve
onlynumericdata,forexample, a+b where a and b arenumericfields.
()
AddingCommentstoMaterializedViews
Youcanaddacommenttoamaterializedview.Forexample,thefollowing
statementaddsacommenttodatadictionaryviewsfortheexistingmaterialized
view:
COMMENTONMATERIALIZEDVIEWsales_mvIS'salesmaterializedview';
Toviewthecommentaftertheprecedingstatementexecution,theusercan
querythecatalogviews, {USER , DBA} ALL_MVIEW_COMMENTS .Forexample:
SELECTMVIEW_NAME,COMMENTS
FROMUSER_MVIEW_COMMENTSWHEREMVIEW_NAME='SALES_MV';
Theoutputwillresemblethefollowing:
MVIEW_NAMECOMMENTS
---------------------------------SALES_MVsalesmaterializedview
Inthecaseofaprebuilttable,ifithasanexistingcomment,thecommentwill
beinheritedbythematerializedviewafterithasbeencreated.Theexisting
commentwillbeprefixedwith '(fromtable)' .Forexample,table
sales_summary wascreatedtocontainsalessummaryinformation.An
existingcomment 'Salessummarydata' wasassociatedwiththetable.A
materializedviewofthesamenameiscreatedtousetheprebuilttableasits
containertable.Afterthematerializedviewcreation,thecommentbecomes
'(fromtable)Salessummarydata' .
However,iftheprebuilttable, sales_summary ,doesnothaveanycomment,
thefollowingcommentisadded: 'Salessummarydata' .Then,ifwedrop
thematerializedview,thecommentwillbepassedtotheprebuilttablewiththe
comment: '(frommaterializedview)Salessummarydata' .
()
RegisteringExistingMaterialized
Views
()Somedatawarehouseshaveimplementedmaterializedviewsinordinary
usertables.Althoughthissolutionprovidestheperformancebenefitsof
materializedviews,itdoesnot:
ProvidequeryrewritetoallSQLapplications.
Enablematerializedviewsdefinedinoneapplicationtobetransparently
accessedinanotherapplication.
Generallysupportfastparallelorfastmaterializedviewrefresh.
Becauseoftheselimitations,andbecauseexistingmaterializedviewscanbe
extremelylargeandexpensivetorebuild,youshouldregisteryourexisting
materializedviewtableswheneverpossible.Youcanregisterauserdefined
materializedviewwiththe CREATE MATERIALIZED VIEW ... ON PREBUILT
TABLE statement.Onceregistered,thematerializedviewcanbeusedfor
queryrewritesormaintainedbyoneoftherefreshmethods,orboth.
Thecontentsofthetablemustreflectthematerializationofthedefiningquery
atthetimeyouregisteritasamaterializedview,andeachcolumninthe
definingquerymustcorrespondtoacolumninthetablethathasamatching
datatype.However,youcanspecify WITH REDUCED PRECISION toallowthe
precisionofcolumnsinthedefiningquerytobedifferentfromthatofthetable
columns.
Thetableandthematerializedviewmusthavethesamename,butthetable
retainsitsidentityasatableandcancontaincolumnsthatarenotreferencedin
thedefiningqueryofthematerializedview.Theseextracolumnsareknownas
unmanagedcolumns.Ifrowsareinsertedduringarefreshoperation,each
unmanagedcolumnoftherowissettoitsdefaultvalue.Therefore,the
unmanagedcolumnscannothave NOT NULL constraintsunlesstheyalsohave
defaultvalues.
Materializedviewsbasedonprebuilttablesareeligibleforselectionbyquery
rewriteprovidedtheparameter QUERY_REWRITE_INTEGRITY issetto
STALE_TOLERATED or TRUSTED .SeeChapter17,"BasicQueryRewrite"
(qrbasic.htm#g1045551)fordetailsaboutintegritylevels.
()()Whenyoudropamaterializedviewthatwascreatedonaprebuilttable,the
tablestillexistsonlythematerializedviewisdropped.
Thefollowingexampleillustratesthetwostepsrequiredtoregisterauser
definedtable.First,thetableiscreated,thenthematerializedviewisdefined
usingexactlythesamenameasthetable.Thismaterializedview
sum_sales_tab_mv iseligibleforuseinqueryrewrite.
CREATETABLEsum_sales_tab
PCTFREE0TABLESPACEdemo
STORAGE(INITIAL16kNEXT16kPCTINCREASE0)AS
SELECTs.prod_id,SUM(amount_sold)ASdollar_sales,
SUM(quantity_sold)ASunit_sales
FROMsalessGROUPBYs.prod_id;
CREATEMATERIALIZEDVIEWsum_sales_tab_mv
ONPREBUILTTABLEWITHOUTREDUCEDPRECISION
ENABLEQUERYREWRITEAS
SELECTs.prod_id,SUM(amount_sold)ASdollar_sales,
SUM(quantity_sold)ASunit_sales
FROMsalessGROUPBYs.prod_id;
Youcouldhavecompressedthistabletosavespace.See"StorageAndTable
Compression"fordetailsregardingtablecompression.
Insomecases,userdefinedmaterializedviewsarerefreshedonaschedule
thatislongerthantheupdatecycle.Forexample,amonthlymaterializedview
mightbeupdatedonlyattheendofeachmonth,andthematerializedview
valuesalwaysrefertocompletetimeperiods.Reportswrittendirectlyagainst
thesematerializedviewsimplicitlyselectonlydatathatisnotinthecurrent
(incomplete)timeperiod.Ifauserdefinedmaterializedviewalreadycontainsa
timedimension:
Itshouldberegisteredandthenfastrefreshedeachupdatecycle.
Youcancreateaviewthatselectsthecompletetimeperiodofinterest.
Thereportsshouldbemodifiedtorefertotheviewinsteadofreferring
directlytotheuserdefinedmaterializedview.
Iftheuserdefinedmaterializedviewdoesnotcontainatimedimension,then:
Createanewmaterializedviewthatdoesincludethetimedimension(if
possible).
Theviewshouldaggregateoverthetimecolumninthenewmaterialized
view.
()
ChoosingIndexesforMaterialized
Views
Thetwomostcommonoperationsonamaterializedviewarequeryexecution
andfastrefresh,andeachoperationhasdifferentperformancerequirements.
Queryexecutionmightneedtoaccessanysubsetofthematerializedviewkey
columns,andmightneedtojoinandaggregateoverasubsetofthosecolumns.
Consequently,queryexecutionusuallyperformsbestifasinglecolumnbitmap
indexisdefinedoneachmaterializedviewkeycolumn.
Inthecaseofmaterializedviewscontainingonlyjoinsusingfastrefresh,Oracle
recommendsthatindexesbecreatedonthecolumnsthatcontaintherowidsto
improvetheperformanceoftherefreshoperation.
Ifamaterializedviewusingaggregatesisfastrefreshable,thenanindex
appropriateforthefastrefreshprocedureiscreatedunless USING NO INDEX
isspecifiedinthe CREATE MATERIALIZED VIEW statement.
Ifthematerializedviewispartitioned,then,afterdoingapartitionmaintenance
operationonthematerializedview,theindexesbecomeunusable,andthey
needtoberebuiltforfastrefreshtowork.
SeeOracleDatabasePerformanceTuningGuide
(../../server.111/b28274/advisor.htm#PFGRF008)forinformationonusingtheSQLAccess
Advisortodeterminewhatindexesareappropriateforyourmaterializedview.
()
DroppingMaterializedViews
Usethe DROP MATERIALIZED VIEW statementtodropa()()materializedview.
Forexample.thefollowingstatement:
DROPMATERIALIZEDVIEWsales_sum_mv;
AnalyzingMaterializedView
Capabilities
Youcanusethe DBMS_MVIEW . EXPLAIN_MVIEW proceduretolearnwhatis
possiblewithamaterializedvieworpotentialmaterializedview.Inparticular,
thisprocedureenablesyoutodetermine:
Ifamaterializedviewisfastrefreshable
Whattypesofqueryrewriteyoucanperformwiththismaterializedview
WhetherPCTrefreshispossible
Usingthisprocedureisstraightforward.Yousimplycall
DBMS_MVIEW.EXPLAIN_MVIEW ,passinginasasingleparametertheschema
andmaterializedviewnameforanexistingmaterializedview.Alternatively,you
canspecifythe SELECT stringforapotentialmaterializedvieworthecomplete
CREATE MATERIALIZED VIEW statement.Thematerializedvieworpotential
materializedviewisthenanalyzedandtheresultsarewrittenintoeitheratable
called MV_CAPABILITIES_TABLE ,whichisthedefault,ortoanarraycalled
MSG_ARRAY .
Notethatyoumustrunthe utlxmv.sql scriptpriortocalling
EXPLAIN_MVIEW exceptwhenyouareplacingtheresultsin MSG_ARRAY .The
scriptisfoundinthe admin directory.Itistocreatethe
MV_CAPABILITIES_TABLE inthecurrentschema.Anexplanationofthe
variouscapabilitiesisinTable87,andallthepossiblemessagesarelistedin
Table88.
()
UsingtheDBMS_MVIEW.EXPLAIN_MVIEW
Procedure
The EXPLAIN_MVIEW proc()edurehasthefollowingparameters:
stmt_id
Anoptionalparameter.Aclientsupplieduniqueidentifiertoassociateoutput
rowswithspecificinvocationsof EXPLAIN_MVIEW .
mv
Thenameofanexistingmaterializedvieworthequerydefinitionortheentire
CREATE MATERIALIZED VIEW statementofapotentialmaterializedview
youwanttoanalyze.
msg-array
EXPLAIN_MVIEW analyzesthespecifiedmaterializedviewintermsofits
refreshandrewritecapabilitiesandinsertsitsresults(intheformofmultiple
rows)into MV_CAPABILITIES_TABLE or MSG_ARRAY .
SeeAlso:
OracleDatabasePL/SQLPackagesandTypesReference
(../../appdev.111/b28419/d_mview.htm#ARPLS027)forfurtherinformationabout
()
DBMS_MVIEW.EXPLAIN_MVIEWDeclarations
Thefollowing()PL/SQLdeclarationsthataremadeforyouinthe DBMS_MVIEW
packageshowtheorderanddatatypesoftheseparametersforexplainingan
existingmaterializedviewandapotentialmaterializedviewwithoutputtoa
tableandtoa VARRAY .
Explainanexistingorpotentialmaterializedviewwithoutputto
MV_CAPABILITIES_TABLE :
DBMS_MVIEW.EXPLAIN_MVIEW(mvINVARCHAR2,
stmt_idINVARCHAR2:=NULL);
Explainanexistingorpotentialmaterializedviewwithoutputtoa VARRAY :
DBMS_MVIEW.EXPLAIN_MVIEW(mvINVARCHAR2,
msg_arrayOUTSYS.ExplainMVArrayType);
()
UsingMV_CAPABILITIES_TABLE
Oneofthesimplestwaystouse DBMS_MVIEW.EXPLAIN_MVIEW is()withthe
MV_CAPABILITIES_TABLE ,whichhasthefollowingstructure:
CREATETABLEMV_CAPABILITIES_TABLE
(STATEMENT_IDVARCHAR(30),--Client-supplieduniquestatement
MVOWNERVARCHAR(30),--NULLforSELECTbasedEXPLAIN_MV
MVNAMEVARCHAR(30),--NULLforSELECTbasedEXPLAIN_MV
CAPABILITY_NAMEVARCHAR(30),--Adescriptivenameofthepartic
--capability:
--REWRITE
--Candoatleastfulltextmatc
--rewrite
--REWRITE_PARTIAL_TEXT_MATCH
--Candoatleatfullandpartia
--textmatchrewrite
--REWRITE_GENERAL
--Candoallformsofrewrite
--REFRESH
--Candoatleastcompleterefre
--REFRESH_FROM_LOG_AFTER_INSERT
--Candofastrefreshfromanmv
--orchangecapturetableatlea
--whenupdateoperationsare
--restrictedtoINSERT
--REFRESH_FROM_LOG_AFTER_ANY
--candofastrefreshfromanmv
--orchangecapturetableafter
--combinationofupdates
--PCT
--CandoEnhancedUpdateTrackin
--thetablenamedintheRELATED
--column.EUTisneededforfas
--refreshafterpartitioned
--maintenanceoperationsonthe
--namedintheRELATED_NAMEcolu
--andtodonon-staletolerated
--rewritewhenthemvispartial
--stalewithrespecttothetabl
--namedintheRELATED_NAMEcolu
--EUTcanalsosometimesenable
--refreshofupdatestothetabl
--namedintheRELATED_NAMEcolu
--whenfastrefreshfromanmvl
--orchangecapturetableisnot
--possible.
--SeeTable8-7
POSSIBLECHARACTER(1),--T=capabilityispossible
--F=capabilityisnotpossible
RELATED_TEXTVARCHAR(2000),--Owner.table.column,aliasname,
--relatedtothismessage.Thespe
--meaningofthiscolumndependso
--NSGNOcolumn.Seethedocumentat
--DBMS_MVIEW.EXPLAIN_MVIEW()ford
RELATED_NUMNUMBER,--Whenthereisanumericvalue
--associatedwitharow,itgoesh
MSGNOINTEGER,--Whenavailable,QSMmessage#ex
--whydisabledormoredetailswhe
--enabled.
MSGTXTVARCHAR(2000),--TextassociatedwithMSGNO.
SEQNUMBER);--UsefulinORDERBYclausewhen
--selectingfromthistable.
First,createthematerializedview.Alternatively,youcanuse EXPLAIN_MVIEW
onapotentialmaterializedviewusingits SELECT statementorthecomplete
CREATE MATERIALIZED VIEW statement.
CREATEMATERIALIZEDVIEWcal_month_sales_mv
BUILDIMMEDIATE
REFRESHFORCE
ENABLEQUERYREWRITEAS
SELECTt.calendar_month_desc,SUM(s.amount_sold)ASdollars
FROMsaless,timestWHEREs.time_id=t.time_id
GROUPBYt.calendar_month_desc;
CAPABILITY_NAMEPREL_TEXTMSGTXT
-----------------------------PCTN
REFRESH_COMPLETEY
REFRESH_FASTN
REWRITEY
PCT_TABLENSALESnopartitionkeyor
PCT_TABLENTIMESrelationisnotap
REFRESH_FAST_AFTER_INSERTNSH.TIMESmvlogmusthavene
REFRESH_FAST_AFTER_INSERTNSH.TIMESmvlogmusthaveRO
REFRESH_FAST_AFTER_INSERTNSH.TIMESmvlogdoesnothav
REFRESH_FAST_AFTER_INSERTNSH.SALESmvlogmusthavene
REFRESH_FAST_AFTER_INSERTNSH.SALESmvlogmusthaveRO
REFRESH_FAST_AFTER_INSERTNSH.SALESmvlogdoesnothav
REFRESH_FAST_AFTER_ONETAB_DMLNDOLLARSSUM(expr)withoutC
REFRESH_FAST_AFTER_ONETAB_DMLNseethereasonwhy
REFRESH_FAST_AFTER_
REFRESH_FAST_AFTER_ONETAB_DMLNCOUNT(*)isnotpre
REFRESH_FAST_AFTER_ONETAB_DMLNSUM(expr)withoutC
REFRESH_FAST_AFTER_ANY_DMLNseethereasonwhy
REFRESH_FAST_AFTER_
REFRESH_FAST_AFTER_ANY_DMLNSH.TIMESmvlogmusthavese
REFRESH_FAST_AFTER_ANY_DMLNSH.SALESmvlogmusthavese
REFRESH_PCTNPCTisnotpossible
tablesinthemater
REWRITE_FULL_TEXT_MATCHY
REWRITE_PARTIAL_TEXT_MATCHY
REWRITE_GENERALY
REWRITE_PCTNPCTisnotpossible
SeeAlso:
Chapter15,"MaintainingtheDataWarehouse"(refresh.htm#g1018554)
andChapter18,"AdvancedQueryRewrite"(qradv.htm#g1045552)for
furtherdetailsaboutPCT
()
MV_CAPABILITIES_TABLE.CAPABILITY_NAMEDetails
Table87listsexplanationsforvaluesinthe CAPABILITY_NAME column.
()()Table87CAPABILITY_NAMEColumnDetails
CAPABILITY_NAME
Description
PCT
Ifthiscapabilityispossible,
PartitionChangeTracking(PCT)
ispossibleonatleastonedetail
relation.Ifthiscapabilityisnot
possible,PCTisnotpossiblewith
anydetailrelationreferencedby
thematerializedview.
REFRESH_COMPLETE
Ifthiscapabilityispossible,
completerefreshofthe
materializedviewispossible.
REFRESH_FAST
Ifthiscapabilityispossible,fast
refreshispossibleatleastunder
certaincircumstances.
REWRITE
Ifthiscapabilityispossible,at
leastfulltextmatchqueryrewrite
ispossible.Ifthiscapabilityisnot
possible,noformofqueryrewrite
ispossible.
PCT_TABLE
Ifthiscapabilityispossible,itis
possiblewithrespecttoa
particularpartitionedtableinthe
toplevel FROM list.When
possible,PCTappliestothe
partitionedtablenamedinthe
RELATED_TEXT column.
PCTisneededtosupportfast
freshafterpartitionmaintenance
operationsonthetablenamedin
the RELATED_TEXT column.
PCTmayalsosupportfastrefresh
withregardtoupdatestothetable
namedinthe RELATED_TEXT
columnwhenfastrefreshfroma
materializedviewlogisnot
possible.
PCTisalsoneededtosupport
queryrewriteinthepresenceof
partialstalenessofthe
materializedviewwithregardto
thetablenamedinthe
RELATED_TEXT column.
Whendisabled,PCTdoesnot
applytothetablenamedinthe
RELATED_TEXT column.Inthis
case,fastrefreshisnotpossible
afterpartitionmaintenance
operationsonthetablenamedin
the RELATED_TEXT column.In
addition,PCTbasedrefreshof
updatestothetablenamedinthe
RELATED_TEXT columnisnot
possible.Finally,queryrewrite
cannotbesupportedinthe
presenceofpartialstalenessof
thematerializedviewwithregard
tothetablenamedinthe
RELATED_TEXT column.
PCT_TABLE_REWRITE
Ifthiscapabilityispossible,itis
possiblewithrespecttoa
particularpartitionedtableinthe
toplevel FROM list.When
possible,PCTappliestothe
partitionedtablenamedinthe
RELATED_TEXT column.
Thiscapabilityisneededto
supportqueryrewriteagainstthis
materializedviewinpartialstale
statewithregardtothetable
namedinthe RELATED_TEXT
column.
Whendisabled,queryrewrite
cannotbesupportedifthis
materializedviewisinpartialstale
statewithregardtothetable
namedinthe RELATED_TEXT
column.
REFRESH_FAST_AFTER_INSERT
Ifthiscapabilityispossible,fast
refreshfromamaterializedview
logispossibleatleastinthecase
wheretheupdatesarerestricted
to INSERT operationscomplete
refreshisalsopossible.Ifthis
capabilityisnotpossible,noform
offastrefreshfromamaterialized
viewlogispossible.
REFRESH_FAST_AFTER_ONETAB_DML
Ifthiscapabilityispossible,fast
refreshfromamaterializedview
logispossibleregardlessofthe
typeofupdateoperation,provided
allupdateoperationsare
performedonasingletable.Ifthis
capabilityisnotpossible,fast
refreshfromamaterializedview
logmaynotbepossiblewhenthe
updateoperationsareperformed
onmultipletables.
REFRESH_FAST_AFTER_ANY_DML
Ifthiscapabilityispossible,fast
refreshfromamaterializedview
logispossibleregardlessofthe
typeofupdateoperationorthe
numberoftablesupdated.Ifthis
capabilityisnotpossible,fast
refreshfromamaterializedview
logmaynotbepossiblewhenthe
updateoperations(otherthan
INSERT )affectmultipletables.
REFRESH_FAST_PCT
Ifthiscapabilityispossible,fast
refreshusingPCTispossible.
Generally,thismeansthatrefresh
ispossibleafterpartition
maintenanceoperationsonthose
detailtableswherePCTis
indicatedaspossible.
REWRITE_FULL_TEXT_MATCH
Ifthiscapabilityispossible,full
textmatchqueryrewriteis
possible.Ifthiscapabilityisnot
possible,fulltextmatchquery
rewriteisnotpossible.
REWRITE_PARTIAL_TEXT_MATCH
Ifthiscapabilityispossible,at
leastfullandpartialtextmatch
queryrewritearepossible.Ifthis
capabilityisnotpossible,atleast
partialtextmatchqueryrewrite
andgeneralqueryrewritearenot
possible.
REWRITE_GENERAL
Ifthiscapabilityispossible,all
queryrewritecapabilitiesare
possible,includinggeneralquery
rewriteandfullandpartialtext
matchqueryrewrite.Ifthis
capabilityisnotpossible,atleast
generalqueryrewriteisnot
possible.
REWRITE_PCT
Ifthiscapabilityispossible,query
rewritecanuseapartiallystale
materializedviewevenin
QUERY_REWRITE_INTEGRITY =
ENFORCED or TRUSTED modes.
Whenthiscapabilityisnot
possible,queryrewritecanusea
partiallystalematerializedview
onlyin
QUERY_REWRITE_INTEGRITY =
STALE_TOLERATED mode.
()
MV_CAPABILITIES_TABLEColumnDetails
Table88liststhesemanticsfor RELATED_TEXT and RELATED_NUM columns.
()()Table88MV_CAPABILITIES_TABLEColumnDetails
MSGNO
MSGTXT
RELATED_NUM
RELATED_TEXT
NULL
NULL
ForPCTcapabilityonly:
[ owner .] name ofthe
tableuponwhichPCTis
enabled
2066
This
statement
resultedinan
Oracleerror
Oracleerror
numberthat
occurred
2067
Nopartition
keyor
PMARKER or
join
dependent
expressionin
SELECT list
[ owner .] name of
relationforwhichPCTis
notsupported
2068
Relationisnot
partitioned
[ owner .] name of
PCTnot
supported
with
multicolumn
partitionkey
PCTnot
supported
withthistype
ofpartitioning
2069
2070
relationforwhichPCTis
notsupported
[ owner .] name of
relationforwhichPCTis
notsupported
[ owner .] name of
relationforwhichPCTis
notsupported
2071
Internalerror:
undefined
PCTfailure
code
The
unrecognized
numericPCT
failurecode
[ owner .] name of
relationforwhichPCTis
notsupported
2072
Requirements
notsatisfied
forfast
refreshof
nested
materialized
view
2077
Materialized
viewlogis
newerthan
lastfull
refresh
[ owner .] table_name
Materialized
viewlogmust
havenew
values
Materialized
viewlogmust
have ROWID
Materialized
viewlogmust
haveprimary
key
Materialized
viewlogdoes
nothaveall
necessary
columns
2078
2079
2080
2081
oftableuponwhichthe
materializedviewlogis
needed
[ owner .] table_name
oftableuponwhichthe
materializedviewlogis
needed
[ owner .] table_name
oftableuponwhichthe
materializedviewlogis
needed
[ owner .] table_name
oftableuponwhichthe
materializedviewlogis
needed
[ owner .] table_name
oftableuponwhichthe
materializedviewlogis
needed
2082
Problemwith
materialized
viewlog
Materialized
view
referencesa
remotetable
orviewinthe
FROM list
Offsetfromthe
SELECT
tableorviewinquestion
2126
Multiple
mastersites
Nameofthefirstdifferent
node,or NULL ifthefirst
differentnodeislocal
2129
Joinorfilter
condition(s)
arecomplex
Expression
notsupported
forfast
refresh
Offsetfromthe
SELECT lists
Offsetfromthe
2099
2130
2150
mustbe
identical
acrossthe
UNION
operator
2182
2183
[ owner .] table_name
oftableuponwhichthe
materializedviewlogis
needed
keywordtothe
tableorviewin
question
tableinvolvedwiththe
joinorfiltercondition(or
NULL whennotavailable)
SELECT
keywordtothe
expressionin
question
SELECT
keywordtothe
firstdifferent
selectiteminthe
SELECT list
PCTis
enabled
throughajoin
dependency
Expressionto
enablePCT
notin
The
unrecognized
numericPCT
Thealiasnameinthe
SELECT listofthe
expressioninquestion
Thealiasnameofthefirst
differentselectiteminthe
SELECT list
[ owner .] name of
relationforwhich
PCT_TABLE_REWRITE is
notenabled
[ owner .] name of
relationforwhichPCTis
notenabled
PARTITION
failurecode
BY ofanalytic
functionor
model
2184
2185
2186
Expressionto
enablePCT
cannotbe
rolledup
Nopartition
keyor
PMARKER in
the SELECT
list
GROUP
[ owner .] name of
relationforwhichPCTis
notenabled
[ owner .] name of
relationforwhich
PCT_TABLE_REWRITE is
notenabled
OUTER JOIN
ispresent
2187
(http://www.oracle.com/us/legal/index.html)
ContactUs (http://www.oracle.com/us/corporate/contact/index.html)
TermsofUse(http://www.oracle.com/us/legal/terms/index.html)
(http://www.oracle.com/us/legal/privacy/index.html)
Copyright2015,Oracleand/oritsaffiliates.Allrightsreserved.
LegalNotices
YourPrivacyRights
AboutOracle(http://www.oracle.com/corporate/index.html)
Materialized
viewon
externaltable