Schema on read is obsolete. Welcome metaprogramming..pdf
Oracle interview question & answers
1. Explainthe difference betweenahot backup and a cold backup and the benefitsassociated
with each.
A hotbackup isbasicallytakingabackup of the database while itisstill upandrunning
and itmust be inarchive logmode.A coldbackupis takinga backup of the database
while itisshutdownand doesnotrequire beinginarchive logmode.The benefitof
takinga hot backupis that the database isstill availableforuse while the backupis
occurringand you can recoverthe database to anypointintime.The benefitof takinga
coldbackup isthat it istypicallyeasiertoadministerthe backupandrecoveryprocess.
In addition,since youare takingcoldbackupsthe database doesnotrequire beingin
archive logmode and thusthere will be aslightperformance gainasthe database isnot
cuttingarchive logsto disk.
How do you add a data file to a tablespace?
ALTER TABLESPACEADD DATAFILESIZE
What is hash cluster?
A rowis storedina hash clusterbasedonthe resultof applyinga hashfunctiontothe
row’sclusterkeyvalue.All rowswiththe same hashkeyvalue are storestogetheron
disk
Explainthe difference betweenadata block, an extentand a segment.
A data blockis the smallestunitof logical storage foradatabase object.Asobjectsgrow
theytake chunksof additional storage thatare composedof contiguousdatablocks.
These groupingsof contiguousdatablocksare calledextents.All the extentsthatan
objecttakeswhengroupedtogetherare consideredthe segmentof the database
object.
Explainan ORA-01555.
You getthiserror whenyougeta snapshottoooldwithinrollback.Itcan usuallybe
solvedbyincreasingthe undoretentionorincreasingthe size of rollbacks.Youshould
alsolookat the logicinvolvedinthe applicationgettingthe errormessage.
Explainwhat partitioningis and what its benefitis.
Partitioningisamethodof takinglarge tablesandindexesandsplittingtheminto
smaller,more manageablepieces.
How can you enable a trace for a session?
Use the DBMS_SESSION.SET_SQL_TRACEor
Use ALTER SESSION SET SQL_TRACE = TRUE;
Whencan hash cluster used?
Hash clustersare betterchoice whenatable isoftenqueriedwithequalityqueries.For
such queriesthe specifiedclusterkeyvalue ishashed.The resultinghashkeyvalue
pointsdirectlytothe areaon diskthat storesthe specifiedrows.
Explainthe difference betweenaFUNCTION,PROCEDUREand PACKAGE.
A functionandprocedure are the same inthat theyare intendedtobe a collectionof
PL/SQL code that carriesa single task.While aprocedure doesnothave toreturn any
valuestothe callingapplication,afunctionwill returnasingle value.A package onthe
2. otherhand isa collectionof functionsandproceduresthatare groupedtogetherbased
on theircommonalitytoabusinessfunctionorapplication.
What is Oracle table?
A table isthe basic unitof data storage in an Oracle database.The tablesof a database
holdall of the useraccessible data.Table dataisstoredinrows and columns.
What viewwouldyou use to look at the size of a data file?
DBA_DATA_FILES
What is an Oracle view?
A viewisa virtual table.Everyview hasaqueryattachedto it.(The queryis a SELECT
statementthatidentifiesthe columnsandrowsof the table(s) the view uses.)
Compare and contrast TRUNCATE and DELETE for a table.
Both the truncate and delete commandhave the desiredoutcome of gettingridof all
the rows ina table.The differencebetweenthe twoisthatthe truncate commandis a
DDL operationandjustmovesthe highwatermarkand producesa now rollback.The
delete command,onthe otherhand,isa DML operation,whichwillproduce arollback
and thustake longerto complete.
What is SYSTEM tablespace and whenis it created?
EveryOracle database containsa tablespace namedSYSTEM,whichisautomatically
createdwhenthe database iscreated.The SYSTEM tablespace alwayscontainsthe data
dictionarytablesforthe entire database.
Describe what redo logs are.
Redologsare logical andphysical structuresthatare designedtoholdall the changes
made to a database and are intendedtoaidinthe recoveryof a database.
What doescoalescinga tablespace do?
Coalescingisonlyvalidfordictionary-managedtablespacesandde-fragmentsspace by
combiningneighboringfree extentsintolarge singleextents.
What is data block?
Oracle database’sdatais storedindata blocks.One datablockcorrespondstoa specific
numberof bytesof physical database space ondisk.
What is indexcluster?
A clusterwithanindex onthe clusterkey.
What is difference betweenTRUNCATE& DELETE?
TRUNCATE commitsafterdeletingentire tablei.e.,cannotbe rolledback.
Database triggersdo notfire on TRUNCATE
DELETE allowsthe filtereddeletion.Deletedrecordscanbe rolledbackor committed.
Database triggersfire onDELETE.
What is a tablespace?
A database isdividedintoLogical Storage Unitcalledtablespaces.A tablespace isused
to groupedrelatedlogical structurestogether.
Can objectsof the same schema reside indifferenttablespaces?
Yes
3. What is publicdatabase link?
Publicdatabase linkiscreatedforthe special usergroupPUBLIC.A publicdatabase link
can be usedwhenanyuserinthe associateddatabase specifiesaglobal objectname in
a SQL statementorobjectdefinition.
What is a transaction?
Transactionislogical unitbetweentwocommitsandcommitandrollback.
What is the difference betweenaTEMPORARY tablespace and a PERMANENT tablespace?
A temporarytablespace isusedfortemporaryobjectssuchassort structureswhile
permanenttablespacesare usedtostore those objectsmeanttobe usedas the true
objectsof the database.
Name a tablespace automatically created whenyou create a database.
The SYSTEM tablespace.
Give the stages of instance startup to a usable state where normal usersmay access it.
STARTUP NOMOUNT – Instance startup
STARTUP MOUNT – The database ismounted
STARTUP OPEN – The database isopened
What is the sub-query?
Sub-queryisaquerywhose returnvaluesare usedinfilteringconditionsof the main
query.
What is a deadlock?Explain.
Two processeswaitingtoupdate the rowsof a table,whichare lockedbyother
processesthendeadlockarises.
In a database environmentthiswilloftenhappenbecause of notissuingthe properrow
lockcommands.Poordesignof front-endapplicationmaycause thissituationandthe
performance of serverwill reducedrastically.
These lockswill be releasedautomaticallywhenacommit/rollbackoperationperformed
or any one of this processesbeingkilledexternally.
Where wouldyou look for errors from the database engine?
In the alertlog.
Give the reasoningbehindusing an index.
Fasteraccess to data blocksina table.
What command would you use to encrypt a PL/SQL application?
WRAP
Give two methodsyou could use to determine whatDDL changes have beenmade.
You coulduse Logmineror Streams
Name three advisory statisticsyou can collect
BufferCache Advice,SegmentLevel Statistics,&TimedStatistics.
What type of indexshouldyou use on a fact table?
A Bitmapindex.
How would you force a log switch?
ALTER SYSTEM SWITCH LOGFILE;
4. Can Oracle’s Data Guard be used on Standard Edition, and ifso how? How can you test that
the standby database is insync?
Oracle’sData Guard technologyisalayerof software andautomationbuiltontopof the
standbydatabase facility.InOracle StandardEditionitispossibletobe a standby
database,andupdate it*manually*.Roughly,putyourproductiondatabase inarchive
logmode. Create a hot backupof the database andmove it to the standbymachine.
Thencreate a standbycontrol file onthe productionmachine,andshipthatfile,along
withall the archivedredologfilestothe standbyserver.Once youhave all these files
assembled,place themintheirproperlocations,recoverthe standbydatabase,and
you’re readyto roll.Fromthispointon,youmust manuallyship,andmanuallyapply
those archivedredologstostay insync withproduction.
To testyour standbydatabase,make a change to a table onthe productionserver,and
committhe change.Thenmanuallyswitchalog file sothose changesare archived.
Manuallyshipthe newestarchivedredologfile,andmanuallyapplyitonthe standby
database.Thenopenyourstandbydatabase inread-onlymode,andselectfromyour
changedtable toverifythose changesare available.Once you’redone,shutdownyour
standbyand start upagain instandbymode.
What is private database link?
Private database linkiscreatedonbehalf of aspecificuser.A private database linkcan
be usedonlywhenthe ownerof the linkspecifiesaglobal objectname inaSQL
statementorinthe definitionof the owner’sviewsorprocedures.
What is a join?Explain the differenttypesof joins?
joinisa query,whichretrievesrelatedcolumnsorrowsfrommultiple tables.
SelfJoin– Joiningthe table withitself.
Equi Join– Joiningtwotablesbyequatingtwocommoncolumns.
Non-Equi Join– Joiningtwotablesbyequatingtwocommoncolumns.
Outer Join– Joiningtwotablesinsucha way thatquerycan also retrieve rowsthatdo
not have correspondingjoinvalue inthe othertable.
What is a database link? Whatis the difference betweenapublicand a private database link?
What is a fixeduserdatabase link?
A database linkallowsyoutomake a connectionwitharemote database,Oracle ornot,
and querytablesfromit,evenincorporatingthoseaccesseswithjoinstolocal tables.
A private database linkonlyworksfor,andisaccessible tothe user/schemathatownsit.
A global one can be accessedbyany userinthe database.
A fixeduserlinkspecifiesthatyouwill connecttothe remote dbas one and onlyone
userthat isdefinedinthe link.Alternatively,acurrentuserdatabase linkwill connectas
the current useryouare loggedinas.
Give the two types of tablesinvolvedinproducing a star schema and the type of data they
hold.
Fact tablesanddimensiontables.A facttable containsmeasurementswhiledimension
tableswill containdatathatwill help describethe facttables.
5. What are the typesof SQL statement?
Data DefinitionLanguage:CREATE, ALTER, DROP,TRUNCATE, REVOKE,NOAUDIT &
COMMIT.
Data ManipulationLanguage: INSERT,UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN &
SELECT.
Transactional Control: COMMIT & ROLLBACK
SessionControl:ALTERSESSION & SET ROLE
SystemControl: ALTER SYSTEM.
Give two examplesofreferential integrityconstraints.
A primarykeyand a foreignkey.
Explainthe difference between$ORACLE_HOMEand $ORACLE_BASE.
ORACLE_BASEis the root directoryfororacle.ORACLE_HOME locatedbeneath
ORACLE_BASEis where the oracle productsreside.
What are clusters?
Clustersare groupsof one or more tablesphysicallystorestogethertoshare common
columnsandare oftenusedtogether.
Give two examplesofhow you might determine the structure ofthe table DEPT.
Use the describe commandoruse the dbms_metadata.get_ddlpackage.
What are the componentsof logical database structure of Oracle database?
There are tablespacesanddatabase’sschema objects.
What is Database Buffers?
Database buffersare cache in the SGA usedto holdthe data blocksthatare read from
the data segmentsinthe database suchas tables,indexesandclusters
DB_BLOCK_BUFFERS parameterinINIT.ORA decidesthe size.
Explainthe relationshipamong database, tablespace and data file.
Each databaseslogicallydividedintoone ormore tablespacesone ormore data filesare
explicitlycreatedforeachtablespace.
Name two filesusedfor networkconnectionto a database.
TNSNAMES.ORA andSQLNET.ORA
Technical – UNIX
Whyis a UNIONALL faster than a UNION?
The unionoperation,youwill recall,bringstwosetsof datatogether.Itwill *NOT*
howeverproduce duplicate orredundantrows.Toperformthisfeatof magic,a SORT
operation isdone onbothtables.Thisisobviouslycomputationallyintensive,anduses
significantmemoryaswell.A UNION ALLconverselyjustdumpscollectionof bothsets
togetherinrandomorder,not worryingaboutduplicates.
Where inthe Oracle directorytree structure are audit traces placed?
In unix $ORACLE_HOME/rdbms/audit,inWindowsthe eventviewer
How would you determine whatsessionsare connectedand what resourcesthey are waiting
for?
Use of V$SESSION andV$SESSION_WAIT
6. Describe the Oracle WaitInterface,how it works, and what it provides.What are some
limitations?Whatdo the db_file_sequential_readanddb_file_scattered_readevents
indicate?
The Oracle WaitInterface referstoOracle’sdatadictionaryformanagingwaitevents.
Selectingfromtablessuchasv$system_eventandv$session_eventgiveyoueventtotals
throughthe life of the database (orsession).The formerare totalsforthe whole system,
and latterona persessionbasis.The eventdb_file_sequential_read referstosingle
blockreads,and table accessesbyrowid.db_file_scattered_readconverselyrefersto
full table scans.Itis sonamedbecause the blocksare read,and scatteredintothe buffer
cache.
Explainmaterializedviewsand how they are used.
Materializedviewsare objectsthatare reducedsetsof informationthathave been
summarized,grouped,oraggregatedfrombase tables.Theyare typicallyusedindata
warehouse ordecisionsupportsystems.
A table isclassifiedas a parent table and you want to drop and re-create it.How wouldyou do
this withoutaffectingthe childrentables?
Disable the foreignkeyconstrainttothe parent,dropthe table,re-create the table,
enable the foreignkeyconstraint.
What is the difference betweenthe SQL*Loader and IMPORT utilities?
These twoOracle utilitiesare usedforloadingdataintothe database.The difference is
that the importutilityreliesonthe databeingproducedbyanotherOracle utility
EXPORT while the SQL*Loaderutilityallowsdatatobe loaded thathas beenproduced
by otherutilitiesfromdifferentdatasourcesjustsolongas it conformsto ASCII
formattedordelimitedfiles.
What are Schema Objects?
Schemaobjectsare the logical structuresthatdirectlyrefertothe database’sdata.
Schemaobjectsinclude tables,views,sequences,synonyms,indexes,clusters,database
triggers,procedures,functionspackagesanddatabase links.
How would you determine the time zone under which a database was operating?
selectDBTIMEZONEfrom dual;
What background process refreshesmaterializedviews?
The Job Queue Processes.
How would you go about increasingthe buffercache hit ratio?
Use the buffercache advisoryovera givenworkloadandthenquerythe
v$db_cache_advice table.If achange was necessarythenIwoulduse the altersystem
setdb_cache_size command.
How are the indexupdates?
Indexesare automaticallymaintainedandusedbyOracle.Changestotable data are
automaticallyincorporatedintoall relevantindexes.
How do you resize a data file?
ALTER DATABASEDATAFILERESIZE ;
7. What are some advantages to usingOracle’s CREATE DATABASE statement to create a new
database manually?
You can script the processto include itina setof install scriptsyoudeliverwith a
product.
You can put yourcreate database scriptinCVSfor versioncontrol,soasyou make
changesor adjustmentstoit,youcan track themlike youdochangesto software code.
You can log the outputand review itforerrors.
You learnmore aboutthe processof database creation,suchas whatoptionsare
available andwhy.
What are the componentsof physical database structure of Oracle database?
Oracle database iscomprisedof three typesof files.One ormore datafiles,twoare
more redolog files, andone ormore control files.
What is schema?
A schemaiscollectionof database objectsof auser.
Whencreating a user, what permissionsmustyou grant to allow them to connect to the
database?
Grant the CONNECTtothe user.
How to define data blocksize?
A data blocksize isspecifiedforeachOracle database whenthe database iscreated.A
database usersandallocatedfree database space inOracle datablocks.Blocksize is
specifiedininit.orafile andcannotbe changedlatter.
How will you swap objectsinto a differenttable space for an existingdatabase?
– Exportthe user
– Performimportusingthe commandimpsystem/managerfile=export.dmp
indexfile=newrite.sql.Thiswillcreate all definitionsintonewfile.sql.
– Drop necessaryobjects.
– Runthe scriptnewfile.sql afteralteringthe tablespaces.
– Importfromthe backup forthe necessaryobjects.
Explainthe difference betweenARCHIVELOG mode andNOARCHIVELOG mode and the
benefitsanddisadvantages to each.
ARCHIVELOGmode isa mode thatyou can put the database infor creatinga backupof
all transactionsthathave occurred inthe database sothat youcan recovertoany point
intime.NOARCHIVELOGmode isbasicallythe absence of ARCHIVELOGmode andhas
the disadvantage of notbeingable torecoverto anypointintime.NOARCHIVELOG
mode doeshave the advantage of not havingtowrite transactionstoan archive logand
thusincreasesthe performance of the database slightly.
What is Oracle 10g?
Oracle 10g is a versionof the Oracle Database.The g standsfor “grid” to indicate that
10g is “grid-computingready”.
How can you rebuildan index?
ALTER INDEX REBUILD;
8. Difference betweenSUBSTRand INSTR?
INSTR(String1,String2(n, (m)),
INSTRreturnsthe positionof the m-thoccurrence of the string2 in string1.The search
beginsfromnthpositionof string1.
SUBSTR (String1n, m)
SUBSTR returnsa character stringof size m instring1,startingfrom n-thpositionof
string1.
What viewwouldyou use to determine free space in a tablespace?
DBA_FREE_SPACE
What are the advantages of VIEW?
– To protectsome of the columnsof a table fromotherusers.
– To hide complexityof aquery.
– To hide complexityof calculations.
How can you gather statistics on a table?
The ANALYZEcommand
What is difference between CHARand VARCHAR2? What isthe maximum SIZE allowedfor
each type?
CHAR padsblankspacesto the maximumlength.
VARCHAR2doesnotpad blankspaces.
For CHAR the maximumlengthis255 and 2000 for VARCHAR2.
What are three rules ofthumb to create good passwords? How would a DBA enforce those
rulesin Oracle? What businesschallengesmightyouencounter?
Typical passwordcrackingsoftware usesadictionaryinthe local language,aswell asa
listof propernames,andcombinationsthereof toattempttoguessunknown
passwords.Since computerscanchurnthrough10’s of thousandsof attemptsquickly,
thiscan be a veryaffective waytobreakintoa database.A good passwordtherefore
shouldnotbe a dictionaryword,itshouldnotbe a propername,birthday,orother
obviousguessable information.Itshouldalsobe of sufficientlength,suchaseighttoten
characters,includingupperandlowercase,special characters,andevenalternate
characters if possible.
Oracle has a facilitycalledpasswordsecurityprofiles.Wheninstalledtheycanenforce
complexity,andlengthrulesaswell asotherpasswordrelated securitymeasures.
In the securityarena,passwordscanbe made better,andit isa fairlysolvableproblem.
However,whataboutinthe real-world?Oftenthe biggestchallenge isinimplementing
a set of ruleslike thisinthe enterprise.There will likely be alotof resistance tothis,as it
createsadditional hasslesforusersof the systemwhomaynotbe usedto thinking
aboutsecurityseriously.Educatingbusinessfolksaboutthe real risks,bycomingupwith
real storiesof vulnerabilitiesandbreak-insyou’veencounteredonthe job,or those
discussedonthe internetgoesalongwaytowardsemphasizingwhatisatstake.
What is correlatedsub-query?
Correlatedsub-queryisasub-query,whichhasreference tothe mainquery.
9. What is database link?
A database linkisa namedobjectthatdescribesa“path” from one database to
another.
What is networkdatabase link?
Networkdatabase linkiscreatedandmanagedbya networkdomainservice.A network
database linkcanbe usedwhenanyuserof anydatabase inthe networkspecifiesa
global objectname ina SQL statementorobjectdefinition.
ExplainUNION,MINUS,UNIONALL and INTERSECT?
INTERSECT – returnsall distinctrowsselectedbybothqueries.
MINUS – returnsall distinctrowsselectedbythe firstquerybutnotby the
second.
UNION – returnsall distinctrowsselectedbyeitherquery
UNIONALL – returnsall rows selectedbyeitherquery,includingall duplicates.
How would you determine whohas added a row to a table?
Turn on fine grainauditingforthe table.
Whena user processfails, what background process cleansup after it?
PMON
What is clusterkey?
The relatedcolumnsof the tablesina clusterare calledthe clusterkey.
How do you switchfrom an init.ora file toa spfile?
Issue the create spfile frompfilecommand.
What command would you use to create a backup control file?
Alterdatabase backupcontrol file totrace.
How do you returnthe top-Nresults of a query inOracle? Why doesn’tthe obvious method
work?
Most people thinkof usingthe ROWNUMpseudocolumnwithORDERBY.Unfortunately
the ROWNUM isdetermined*before*the ORDERBY so youdon’tget the resultsyou
want.The answeristo use a subquerytodo the ORDER BY first. Forexample toreturn
the top-5 employeesbysalary:
SELECT * FROM(SELECT * FROMemployeesORDERBY salary) WHERE ROWNUM< 5;
How would you go about generatingan EXPLAIN plan?
Create a plantable withutlxplan.sql.
Use the explainplansetstatement_id =‘tst1′ intoplan_table foraSQL statement
Look at the explainplanwithutlxplp.sqlorutlxpls.sql
You have just had to restore from backup and do not have any control files.How would you
go about bringing up this database?
I wouldcreate a textbased backupcontrol file,stipulatingwhere ondiskall the data
fileswhere andthenissue the recovercommandwiththe usingbackupcontrol file
clause.
10. Explainthe use oftable functions.
Table functionsare designedtoreturnasetof rowsthroughPL/SQL logicbutare
intendedtobe usedasa normal table orview ina SQL statement.Theyare alsousedto
pipelineinformationinanETL process.
Explainthe use ofsetting GLOBAL_NAMESequal to TRUE.
SettingGLOBAL_NAMESdictateshow youmightconnectto a database.Thisvariable is
eitherTRUE or FALSE and if itis setto TRUE it enforcesdatabase linkstohave the same
name as the remote database to whichtheyare linking.