OCA Oracle Database SQL Exam Guide (Exam 1Z0 071) (Oracle Press)
User Manual:
Open the PDF directly: View PDF .
Page Count: 790 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Title Page
- Copyright Page
- Dedication
- Contents
- Acknowledgments
- Preface
- Introduction
- Exam Readiness Checklist
- 1 Oracle and Structured Query Language (SQL)
- The Exam: An Overview
- What to Do and What to Expect
- Oracle SQL vs. ANSI SQL
- Oracle SQL vs. Oracle SQL*Plus
- SQL Fundamentals I vs. SQL Certified Associate
- Confirm Appropriate Materials for Study
- Identify the Connection Between an ERD and a Relational Database
- Entity-Relationship Diagrams and Data Modeling
- Relational Databases
- Many-to-Many Relationships
- Database Normalization
- Explain the Relationship Between a Database and SQL
- Describe the Purpose of DDL
- Describe the Purpose of DML
- Transaction Control Language
- Build a SELECT Statement to Retrieve Data from an Oracle Database Table
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 2 Using DDL Statements to Create and Manage Tables
- Categorize the Main Database Objects
- What Are Database Objects?
- Schemas
- Create a Simple Table
- Naming a Table or Other Object
- The SQL Statement CREATE TABLE
- Review the Table Structure
- List the Data Types That Are Available for Columns
- Character
- Numeric
- Date
- Large Objects
- Explain How Constraints Are Created at the Time of Table Creation
- Creating CONSTRAINTS in the CREATE TABLE Statement
- The Types of CONSTRAINTS
- Drop Columns and Set Column UNUSED
- Dropping Columns
- UNUSED
- Create and Use External Tables
- Benefits
- Creating External Tables
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 3 Manipulating Data
- Truncate Data
- Recursively Truncate Child Tables
- Insert Rows into a Table
- Default Column List
- Enumerated Column List
- Update Rows in a Table
- Expressions
- Constraints
- The WHERE Clause
- Delete Rows from a Table
- Control Transactions
- COMMIT
- ROLLBACK
- SAVEPOINT
- ROLLBACK Revisited
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 4 Restricting and Sorting Data
- Sort the Rows That Are Retrieved by a Query
- Reference by Name
- Expressions
- Reference by Position
- Combinations
- ORDER BY and NULL
- Limit the Rows That Are Retrieved by a Query
- The WHERE Clause
- Boolean Logic
- Additional WHERE Clause Features
- Additional Concepts
- Use Ampersand Substitution to Restrict and Sort Output at Run Time
- &
- DEFINE and UNDEFINE Commands
- The SET and SHOW Commands
- ACCEPT and PROMPT
- Use the SQL Row Limiting Clause
- FETCH
- WITH TIES
- OFFSET
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 5 Using Single-Row Functions to Customize Output
- Use Various Types of Functions That Are Available in SQL
- Character Functions
- Number Functions
- Date Functions
- Other Functions
- Use Character, Number, Date, and Analytical (PERCENTILE_CONT, STDDEV, LAG, LEAD) Functions in SELECT Statements
- The DUAL Table
- Character Functions
- Numerical Functions
- Date Functions
- Analytical Functions
- Nesting Functions
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 6 Using Conversion Functions and Conditional Expressions
- Describe Various Types of Conversion Functions
- Explicit and Implicit Conversion
- Use the TO_CHAR, TO_NUMBER, and TO_DATE Conversion Functions
- Conversion Functions
- Additional Conversion Functions
- Apply General Functions and Conditional Expressions in a SELECT Statement
- CASE
- DECODE
- NVL
- NULLIF
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 7 Reporting Aggregated Data Using the Group Functions
- Describe the Use of Group Functions
- COUNT
- SUM
- MIN, MAX
- AVG
- MEDIAN
- RANK
- DENSE_RANK
- FIRST, LAST
- Others
- Group Data by Using the GROUP BY Clause
- Multiple Columns
- ORDER BY Revisited
- Nesting Functions
- Include or Exclude Grouped Rows by Using the HAVING Clause
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 8 Displaying Data from Multiple Tables
- Describe the Different Types of Joins and Their Features
- Types of Joins
- Use SELECT Statements to Access Data from More Than One Table Using Equijoins and Non-Equijoins
- Inner Joins
- Using Table Aliases
- Natural Joins
- USING
- Multitable Joins
- Non-Equijoins
- Join a Table to Itself by Using a Self-Join
- Self-Referencing Foreign Keys
- Self-Join Syntax
- View Data That Generally Does Not Meet a Join Condition by Using Outer Joins
- LEFT OUTER JOIN
- RIGHT OUTER JOIN
- FULL OUTER JOIN
- For the Record: Oracle Outer Join Syntax: (+)
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 9 Using Subqueries to Solve Queries
- Define Subqueries
- Describe the Types of Problems Subqueries Can Solve
- Describe the Types of Subqueries
- Query Data Using Correlated Subqueries
- Update and Delete Rows Using Correlated Subqueries
- UPDATE with a Correlated Subquery
- DELETE with a Correlated Subquery
- Use the EXISTS and NOT EXISTS Operators
- Use the WITH Clause
- Write Single-Row and Multiple-Row Subqueries
- Single-Row Subqueries
- Multiple-Row Subqueries
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 10 Managing Schema Objects
- Describe How Schema Objects Work
- Tables
- Constraints
- Views
- Indexes
- Sequences
- Create Simple and Complex Views with Visible/Invisible Columns
- Creating Views
- Updatable Views
- Inline Views
- ALTER VIEW
- Visible/Invisible Columns
- Create, Maintain, and Use Sequences
- Creating and Dropping Sequences
- Using Sequences
- Create and Maintain Indexes Including Invisible Indexes and Multiple Indexes on the Same Columns
- The Oracle Database Optimizer
- Implicit Index Creation
- Single Column
- Composite
- Unique
- Dropping
- Visible and Invisible Indexes
- Index Alternatives on the Same Column Set
- Perform Flashback Operations
- Overview
- Recover Dropped Tables
- Recovering Data Within Existing Tables over Time
- Marking Time
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 11 Using the Set Operators
- 12 Managing Objects with Data Dictionary Views
- Query Various Data Dictionary Views
- Structure
- Dynamic Performance Views
- Reading Comments
- Adding Comments
- DICTIONARY
- Identifying a User’s Owned Objects
- Inspecting Tables and Columns
- Compiling Views
- Checking Privileges
- Inspecting Constraints
- Finding Columns
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 13 Manipulating Large Data Sets
- 14 Controlling User Access
- Differentiate System Privileges from Object Privileges
- System Privileges
- Prerequisites
- GRANT and REVOKE
- ANY
- ADMIN OPTION
- ALL PRIVILEGES
- PUBLIC
- Grant Privileges on Tables and on a User
- Schema Prefixes
- WITH GRANT OPTION
- REVOKE
- ALL PRIVILEGES
- Dependent Privileges
- View Privileges in the Data Dictionary
- Grant Roles
- Distinguish Between Privileges and Roles
- Certification Summary
- ✓ Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- A About the Download
- Glossary
- Index
Copyright©2017byMcGraw-HillEducation.Allrightsreserved.Exceptas
permittedundertheUnitedStatesCopyrightActof1976,nopartofthis
publicationmaybereproducedordistributedinanyformorbyanymeans,or
storedinadatabaseorretrievalsystem,withoutthepriorwrittenpermissionof
thepublisher,withtheexceptionthattheprogramlistingsmaybeentered,
stored,andexecutedinacomputersystem,buttheymaynotbereproducedfor
publication.
ISBN:978-1-25-958461-9
MHID:1-25-958461-5.
ThematerialinthiseBookalsoappearsintheprintversionofthistitle:ISBN:
978-1-25-958549-4,MHID:1-25-958549-2.
eBookconversionbycodeMantra
Version1.0
Alltrademarksaretrademarksoftheirrespectiveowners.Ratherthanputa
trademarksymbolaftereveryoccurrenceofatrademarkedname,weusenames
inaneditorialfashiononly,andtothebenefitofthetrademarkowner,withno
intentionofinfringementofthetrademark.Wheresuchdesignationsappearin
thisbook,theyhavebeenprintedwithinitialcaps.
McGraw-HillEducationeBooksareavailableatspecialquantitydiscountstouse
aspremiumsandsalespromotionsorforuseincorporatetrainingprograms.To
contactarepresentative,pleasevisittheContactUspageat
www.mhprofessional.com.
OracleisaregisteredtrademarkofOracleCorporationand/oritsaffiliates.All
othertrademarksarethepropertyoftheirrespectiveowners,andMcGraw-Hill
Educationmakesnoclaimofownershipbythementionofproductsthatcontain
thesemarks.
ScreendisplaysofcopyrightedOraclesoftwareprogramshavebeenreproduced
hereinwiththepermissionofOracleCorporationand/oritsaffiliates.
OracleCorporationdoesnotmakeanyrepresentationsorwarrantiesastothe
accuracy,adequacy,orcompletenessofanyinformationcontainedinthisWork,
andisnotresponsibleforanyerrorsoromissions.
TERMSOFUSE
ThisisacopyrightedworkandMcGraw-HillEducationanditslicensorsreserve
allrightsinandtothework.Useofthisworkissubjecttotheseterms.Exceptas
permittedundertheCopyrightActof1976andtherighttostoreandretrieveone
copyofthework,youmaynotdecompile,disassemble,reverseengineer,
reproduce,modify,createderivativeworksbasedupon,transmit,distribute,
disseminate,sell,publishorsublicensetheworkoranypartofitwithout
McGraw-HillEducation’spriorconsent.Youmayusetheworkforyourown
noncommercialandpersonaluse;anyotheruseoftheworkisstrictlyprohibited.
Yourrighttousetheworkmaybeterminatedifyoufailtocomplywiththese
terms.
THEWORKISPROVIDED“ASIS.”McGRAW-HILLEDUCATIONAND
ITSLICENSORSMAKENOGUARANTEESORWARRANTIESASTO
THEACCURACY,ADEQUACYORCOMPLETENESSOFORRESULTS
TOBEOBTAINEDFROMUSINGTHEWORK,INCLUDINGANY
INFORMATIONTHATCANBEACCESSEDTHROUGHTHEWORKVIA
HYPERLINKOROTHERWISE,ANDEXPRESSLYDISCLAIMANY
WARRANTY,EXPRESSORIMPLIED,INCLUDINGBUTNOTLIMITED
TOIMPLIEDWARRANTIESOFMERCHANTABILITYORFITNESSFOR
APARTICULARPURPOSE.McGraw-HillEducationanditslicensorsdonot
warrantorguaranteethatthefunctionscontainedintheworkwillmeetyour
requirementsorthatitsoperationwillbeuninterruptedorerrorfree.Neither
McGraw-HillEducationnoritslicensorsshallbeliabletoyouoranyoneelsefor
anyinaccuracy,errororomission,regardlessofcause,intheworkorforany
damagesresultingtherefrom.McGraw-HillEducationhasnoresponsibilityfor
thecontentofanyinformationaccessedthroughthework.Underno
circumstancesshallMcGraw-HillEducationand/oritslicensorsbeliableforany
indirect,incidental,special,punitive,consequentialorsimilardamagesthat
resultfromtheuseoforinabilitytousethework,evenifanyofthemhasbeen
advisedofthepossibilityofsuchdamages.Thislimitationofliabilityshallapply
toanyclaimorcausewhatsoeverwhethersuchclaimorcausearisesincontract,
tortorotherwise.
ToJimBauchspies,whogavememyfirstOraclejobandwhohasalwaysbeen
likeasecondfathertome.
ABOUTTHEAUTHOR
SteveO’Hearnisatechnologyconsultantwithexpertiseinthedesign,
development,andadministrationofvariousdataanddata-drivensystemsfor
suchclientsastheU.S.DefenseDepartment,NASAHQ,theFAA,theWorld
Bank,andmanyothers.HefirstbecameanOracleCertifiedProfessional(OCP)
in2001andisacertifiedOracleDatabaseSQLExpert.Hehasadegreein
businessadministrationwithaspecializationininformationprocessingfrom
GeorgeWashingtonUniversity,andhispostgraduateworkincludesadvanced
statisticsandthecompletionoftheFutureofe-GovernmentExecutiveEducation
trainingatHarvardUniversity’sKennedySchoolofGovernmentin2003.Heis
amemberofMensa.
Mr.O’HearnauthoredOCEOracleDatabaseSQLCertifiedExpertExam
Guide(Exam1Z0-047),theofficialcertificationexamguideforOracle’sfirst
expert-levelcertificationexam,andthecriticallyacclaimedOCPDeveloper:
PL/SQLProgramUnitsExamGuide,bothfromOraclePress.Hecontributedto
OracleWebApplications101fromOraclePressandOracle8ServerUnleashed.
HehasbeenfeaturedonOracleTVandOracleOpenWorld/JavaOne.Hehas
beenpublishedinavarietyofpublications,includingtheHarvardBusiness
ReviewandtheRecordoftheNationalPressClub,whereheisanofficially
recognizedsubject-matterexpertonthetopicsofdatabaseandinformation
technology.HehasbeenvicepresidentandconferencecoordinatorfortheMid-
AtlanticAssociationofOracleProfessionals.HeleadstheofficialJavaUser
Group(JUG)fortheBaltimoreWashingtonMetropolitanArea,possesses
certificationsinJavaandothertechnologies,andlovesworkingwithhisown
RaspberryPiand3Dprintingdevices.
Mr.O’HearnprovidesOracleandJavatechnologytrainingandtutoring
online.HeblogsatSkere9.com.Heinvitesanyandallinquiriesat
soh@corbinian.com.
AbouttheContributor
BobBrylaisanOracle9i,10g,11g,and12cCertifiedProfessionalwithmore
than20yearsofexperienceindatabasedesign,databaseapplication
development,training,andOracledatabaseadministration.Heistheprimary
OracleDBAanddatabasescientistatEpicinVerona,Wisconsin.Heisa
technicaleditorforanumberofOraclePressbooks,includingseveral
certificationstudyguidesforOracleDatabase10g,11g,and12c.Youcanalso
findhimonLynda.comteachingOracleDatabasefundamentalsinbite-sized
videos.Hehasalsobeenknowntowatchscience-fictionmovies,tinkerwith
Androiddevices,andrefinishantiquefurnitureinhissparetime.
AbouttheTechnicalEditor
ToddMeisterhasbeenworkingintheITindustryformorethan20years.He’s
beenatechnicaleditoronmorethan75booksrangingintopicfromSQLServer
tothe.NETFramework.Besidestechnicalediting,heistheassistantvice
president/chiefenterprisearchitectatBallStateUniversityinMuncie,Indiana.
HelivesincentralIndianawithhiswife,Kimberly,andtheirfivebright
children.
CONTENTSATAGLANCE
1OracleandStructuredQueryLanguage(SQL)
2UsingDDLStatementstoCreateandManageTables
3ManipulatingData
4RestrictingandSortingData
5UsingSingle-RowFunctionstoCustomizeOutput
6UsingConversionFunctionsandConditionalExpressions
7ReportingAggregatedDataUsingtheGroupFunctions
8DisplayingDatafromMultipleTables
9UsingSubqueriestoSolveQueries
10ManagingSchemaObjects
11UsingtheSetOperators
12ManagingObjectswithDataDictionaryViews
13ManipulatingLargeDataSets
14ControllingUserAccess
AAbouttheDownload
Glossary
Index
CONTENTS
Acknowledgments
Preface
Introduction
ExamReadinessChecklist
1OracleandStructuredQueryLanguage(SQL)
TheExam:AnOverview
WhattoDoandWhattoExpect
OracleSQLvs.ANSISQL
OracleSQLvs.OracleSQL*Plus
SQLFundamentalsIvs.SQLCertifiedAssociate
ConfirmAppropriateMaterialsforStudy
IdentifytheConnectionBetweenanERDandaRelationalDatabase
Entity-RelationshipDiagramsandDataModeling
RelationalDatabases
Many-to-ManyRelationships
DatabaseNormalization
ExplaintheRelationshipBetweenaDatabaseandSQL
DescribethePurposeofDDL
DescribethePurposeofDML
TransactionControlLanguage
BuildaSELECTStatementtoRetrieveDatafromanOracle
DatabaseTable
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
2UsingDDLStatementstoCreateandManageTables
CategorizetheMainDatabaseObjects
WhatAreDatabaseObjects?
Schemas
CreateaSimpleTable
NamingaTableorOtherObject
TheSQLStatementCREATETABLE
ReviewtheTableStructure
ListtheDataTypesThatAreAvailableforColumns
Character
Numeric
Date
LargeObjects
ExplainHowConstraintsAreCreatedattheTimeofTableCreation
CreatingCONSTRAINTSintheCREATETABLEStatement
TheTypesofCONSTRAINTS
DropColumnsandSetColumnUNUSED
DroppingColumns
UNUSED
CreateandUseExternalTables
Benefits
CreatingExternalTables
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
3ManipulatingData
TruncateData
RecursivelyTruncateChildTables
InsertRowsintoaTable
DefaultColumnList
EnumeratedColumnList
UpdateRowsinaTable
Expressions
Constraints
TheWHEREClause
DeleteRowsfromaTable
ControlTransactions
COMMIT
ROLLBACK
SAVEPOINT
ROLLBACKRevisited
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
4RestrictingandSortingData
SorttheRowsThatAreRetrievedbyaQuery
ReferencebyName
Expressions
ReferencebyPosition
Combinations
ORDERBYandNULL
LimittheRowsThatAreRetrievedbyaQuery
TheWHEREClause
BooleanLogic
AdditionalWHEREClauseFeatures
AdditionalConcepts
UseAmpersandSubstitutiontoRestrictandSortOutputatRunTime
&
DEFINEandUNDEFINECommands
TheSETandSHOWCommands
ACCEPTandPROMPT
UsetheSQLRowLimitingClause
FETCH
WITHTIES
OFFSET
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
5UsingSingle-RowFunctionstoCustomizeOutput
UseVariousTypesofFunctionsThatAreAvailableinSQL
CharacterFunctions
NumberFunctions
DateFunctions
OtherFunctions
UseCharacter,Number,Date,andAnalytical
(PERCENTILE_CONT,STDDEV,LAG,LEAD)FunctionsinSELECT
Statements
TheDUALTable
CharacterFunctions
NumericalFunctions
DateFunctions
AnalyticalFunctions
NestingFunctions
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
6UsingConversionFunctionsandConditional
Expressions
DescribeVariousTypesofConversionFunctions
ExplicitandImplicitConversion
UsetheTO_CHAR,TO_NUMBER,andTO_DATEConversion
Functions
ConversionFunctions
AdditionalConversionFunctions
ApplyGeneralFunctionsandConditionalExpressionsinaSELECT
Statement
CASE
DECODE
NVL
NULLIF
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
7ReportingAggregatedDataUsingtheGroupFunctions
DescribetheUseofGroupFunctions
COUNT
SUM
MIN,MAX
AVG
MEDIAN
RANK
DENSE_RANK
FIRST,LAST
Others
GroupDatabyUsingtheGROUPBYClause
MultipleColumns
ORDERBYRevisited
NestingFunctions
IncludeorExcludeGroupedRowsbyUsingtheHAVINGClause
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
8DisplayingDatafromMultipleTables
DescribetheDifferentTypesofJoinsandTheirFeatures
TypesofJoins
UseSELECTStatementstoAccessDatafromMoreThanOneTable
UsingEquijoinsandNon-Equijoins
InnerJoins
UsingTableAliases
NaturalJoins
USING
MultitableJoins
Non-Equijoins
JoinaTabletoItselfbyUsingaSelf-Join
Self-ReferencingForeignKeys
Self-JoinSyntax
ViewDataThatGenerallyDoesNotMeetaJoinConditionbyUsing
OuterJoins
LEFTOUTERJOIN
RIGHTOUTERJOIN
FULLOUTERJOIN
FortheRecord:OracleOuterJoinSyntax:(+)
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
9UsingSubqueriestoSolveQueries
DefineSubqueries
DescribetheTypesofProblemsSubqueriesCanSolve
DescribetheTypesofSubqueries
QueryDataUsingCorrelatedSubqueries
UpdateandDeleteRowsUsingCorrelatedSubqueries
UPDATEwithaCorrelatedSubquery
DELETEwithaCorrelatedSubquery
UsetheEXISTSandNOTEXISTSOperators
UsetheWITHClause
WriteSingle-RowandMultiple-RowSubqueries
Single-RowSubqueries
Multiple-RowSubqueries
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
10ManagingSchemaObjects
DescribeHowSchemaObjectsWork
Tables
Constraints
Views
Indexes
Sequences
CreateSimpleandComplexViewswithVisible/InvisibleColumns
CreatingViews
UpdatableViews
InlineViews
ALTERVIEW
Visible/InvisibleColumns
Create,Maintain,andUseSequences
CreatingandDroppingSequences
UsingSequences
CreateandMaintainIndexesIncludingInvisibleIndexesand
MultipleIndexesontheSameColumns
TheOracleDatabaseOptimizer
ImplicitIndexCreation
SingleColumn
Composite
Unique
Dropping
VisibleandInvisibleIndexes
IndexAlternativesontheSameColumnSet
PerformFlashbackOperations
Overview
RecoverDroppedTables
RecoveringDataWithinExistingTablesoverTime
MarkingTime
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
11UsingtheSetOperators
DescribeSetOperators
UseaSetOperatortoCombineMultipleQueriesintoaSingleQuery
UNION
UNIONALL
INTERSECT
MINUS
Combinations
ControltheOrderofRowsReturned
ORDERBY—ByPosition
ORDERBY—ByReference
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
12ManagingObjectswithDataDictionaryViews
QueryVariousDataDictionaryViews
Structure
DynamicPerformanceViews
ReadingComments
AddingComments
DICTIONARY
IdentifyingaUser’sOwnedObjects
InspectingTablesandColumns
CompilingViews
CheckingPrivileges
InspectingConstraints
FindingColumns
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
13ManipulatingLargeDataSets
DescribetheFeaturesofMultitableINSERTs
UsetheFollowingTypesofMultitableINSERTS:
UnconditionalandConditional
MergeRowsintoaTable
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
14ControllingUserAccess
DifferentiateSystemPrivilegesfromObjectPrivileges
SystemPrivileges
Prerequisites
GRANTandREVOKE
ANY
ADMINOPTION
ALLPRIVILEGES
PUBLIC
GrantPrivilegesonTablesandonaUser
SchemaPrefixes
WITHGRANTOPTION
REVOKE
ALLPRIVILEGES
DependentPrivileges
ViewPrivilegesintheDataDictionary
GrantRoles
DistinguishBetweenPrivilegesandRoles
CertificationSummary
✓Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
F
ACKNOWLEDGMENTS
irst,Iwanttoacknowledgeyou,thereader.Wereitnotforyou,thisbook
wouldneverhavebeencreated.Becauseofyou,becauseofyourinterest,
becauseofyourprofessionalism,andbecauseofyourdemonstrablecommitment
toimprovingyourselfandthereforetheindustry,thisbookwascreated.Wereit
notforyou,therewouldnotbeaneliteteamofexpertshereatOraclePress
respondingtoyourinterestandyourdemandforqualitymaterial.So,thankyou.
Withoutyou,wewouldnotbedoingwhatwedo,norwouldthisbookexist.
Speakingofthisbookthatyouareholdinginyourhands(orperhapsreading
onyourscreen),itisatremendousworkandavaluablecontributiontothe
industry.Itrepresentsagreatdealofeffortbyanumberoftalented,persistent,
anddedicatedprofessionals.
Thisbookoriginallystartedasasecondeditiontomy2009SQLExpertbook
onthe1Z0-047examandwasnearingcompletionwhenitevolvedintothis
book,thefirstcertificationexamguideforthe1Z0-071exam.
First,aspecialandhugethank-youtoHilaryFlood.Thisbookwouldnot
havehappenedwithouther.Itwasherbold,openmindandcreativeforcethat
helpedoriginallysteerthisshipthroughmurkywaterstoitseventualgoal.For
herpersistence,patience,expertise,andinsight,Ithankher.
ClaireYeewastheeditorialcoordinator.Shewasconsistentlycheerfuland
encouragingandworkedtirelesslytoensureeachchapterorothersection
workeditswaythroughthemanyeditorialcycles,fromoriginalmaterialthrough
technicaledit,copyediting,andbeyondtofinalproduction.
DipikaRungtawastheprojectmanager.Asthevariouschaptersandother
sectionsexitedtheprocessheadedbyClaire,eachmovedtoDipikafor
additionalreview,work,andthemanydemandingdetailsnecessarytoprepare
thebookforproduction.Dipikahasbeenajoytoworkwithandisatremendous
assettoanybookproductioneffort.
JodyMcKenziewastheeditorialsupervisorandsteppedintoresolvesome
challengingissuesatkeytimes.LisaMcCoywastheproofreaderandcaught
someofthemostobscuretyposimaginable.ThecopyeditorwasKimWimpsett
andhelpedmakesuresomeofmycuriousexpressionsorwordchoiceswere
translatedintounderstandablenarratives.TheproductionsupervisorwasJim
Kussow,whohasmanagedtheproductionandprintingprocessesofthis
ponderoustome.
ThankyoutoVasundharaSawhneywhocontributedalotofworkinthe
earlieststagesofthisjourney.
TheacquisitionseditorwasLisaMcClain.Acquisitionseditorsleadthe
chargetoputbookprojectstogetherinthefirstplaceandstayinvolvedtoensure
thoseprojectsmarchforwardtotheirdestination.Theymaketoughcallsinthe
faceofuncertaintyandhavetodiscernapathforwardwithsometimeslimited
information.OraclePresshastalentedacquisitionseditors,andLisaMcClainis
oneofthebestinthebusiness.Sheheraldedthiseffortinthelatterstages,andit
hasbeenaprivilegetohaveservedwithheronthisproject.
Nowlet’stalkaboutindexing.Indexingabookisacrucialjob.Thisistrue
whetherthebookisinprintedordigitalform.Ijudgetechnicalbooksbyafew
keyindicators,includingthequalityandrelevanceoftheindex.Igenerally
alreadyhaveanideaofwhatI’mlookingforinatechnicalbook,sowhenIpick
upapapertechnicalbookforthefirsttime,Ifliptotheindexandcheckfor
particularsubjectareasofinteresttodeterminewhethertheindexcorrectly
referencestheminthenarrative.Ifyes,Ibuythebook.Ifnot,Idon’t.That’s
oftenmyonlycriteriawhenevaluatingnewbooks.That’showimportantthe
indexofatechnicalbookistome.
Ifyou’rereadingthisdigitally,youmightbethinking,“Sowhat?Icanalways
doawordsearch.WhydoIneedanindex?”Therearemanytopicsinbookslike
thiswherethekeywordisn’teasilysearchable.Forexample,considertheword
set.Itisusedquiteabitinnormalconversationandislikelyinthenarrativefor
variousreasons.ButsetisalsoakeyconceptinthisbookwithregardtoSET
operationssuchasUNIONandINTERSECT.Andthattopiciscompletely
differentfromthekeywordSETinanUPDATEstatement.Allareinthisbook.
Soifyouaresearchingforjustoneparticularuseofsetinthisbook,thenan
electronicsearchonakeywordmayslogyouthroughallsortsofunrelated
material.Butawell-craftedindexwillgetyouwhereyouneedtogoquickly,
eveninadigitalversionofthebook.
Forthatreason,IamverygratefulfortheworkofJackLewis,theindexerfor
thisbook.It’sagreatdealofworkandoftenoverlookedbutneverbyme—
neitherasaconsumernorasanauthor.Thankyou,Jack.Iappreciateyourwork
muchmorethanyoumayrealize.
Ahugeandspecialthank-youtomytechnicaleditor,ToddMeister.Toddhas
workedtirelesslytoreviewandanalyzehundredsofpagesofcode,andhehas
reverse-engineeredamyriadofexamples,illustrations,questions,andanswers.
Hetraveleddownthislongroadwiththerestoftheteamwithstyle,grace,and
amazingpersistence.Oneparticularchallengewiththiskindoftechnicalbookis
thatitdoesn’tlenditselftoaconsistentlybuiltapplication(forexamplesand
illustrations)likesomeotherbooksdo.Thenatureofacertificationexamguide
isthatitmustcoveravarietyofsyntaxcombinations,soratherthanbuildingan
applicationasaproject,thisbookrequiresyoutounderstandallformsofcertain
syntaxcombinations.Thatisachallengetothecertificationcandidate;imagine
thechallengetoatechnicaleditor.Itisenormous.YetToddhasdoneit
brilliantlyandwithaplombandprofessionalism.Iwillalwayshavevisionsof
hisfamiliar“ToddMeisterverified”annotationsthroughoutthedraftcopiesof
thebookasthevarioussectionspassedbackandforthalongthecycleof
production.Butnotethatthebookhasgonethroughafewiterations,soifyou
stillbizarrelymanagetofindsomethinginitthatislessthanideal—andthat’s
thecasewithvirtuallyeverypublication—thenthat’llbeonme.Butknowthat
thankstoTodd,thebookislight-yearsaheadofwhereitotherwisewouldhave
been.
Alsoabigthank-youtoBobBryla,anoutstandingOraclePressauthorinhis
ownrightmanytimesover,whojumpedinatthelastminutetocontributea
goodnumberofquestionsandanswerstothesamplecertificationexamincluded
withthebook.Thankyou,Bob!
TomyverymanyfriendsandcolleagueswithwhomI’vehadthepleasureof
workingand/orservingovertheyearsatvariouslocationsandinvarious
capacities,atsuchenterprisesasAtrexa,LHRDigitalConsulting,Corbinian,
Sysorex,ISC,db-Training,MAOP,EOUG,Boeing,ORI,ARC,NPC,and
elsewhere,includingsomewhoarestillatthoseplacesandsomewhohavegone
ontootheradventures—thereisnowayIcouldnameeveryoneherewhohas
beeninstrumentalorcontributedsomethingimportanttomylifeandwork.A
partiallistincludesthefollowing:MarkO’Donnell,MattHutchinson,Daveand
JackieDougherty,JohnCook,TimGreen,JeremyJudson,SalamQureishi,Nadir
Ali,WendyLoundermon,AtharJavaid,DanDoherty,TonyCovert,Bianca
Canales,MarleneTheriault,KevinLoney,MichelleVeghte,ArdellFleeson,
MarkusDale,KarlDavis,AllenShoulders,EdWolfe,AshleyRubeck,Cindy
Shiflett,PhilHasse,DaveGagner,JonFeld,JayNielsen,SteveSmith,Edgar
Kline,DaveSalmen,OscarWood,JamesPerry,TerriBuckler,SarahHenrikson,
MarkTash,SteveVandivier,AdhilShaikh,MoniqueTribolet,EdSpinella,Dino
Merkezas,KathyGardos,BertSpencer,KarenOwens,MikeAult,Graham
Seibert,VinceAdams,BobSchnetter,JoshParreco,CraigKasold,JenniferBlair,
BrettSimpson,MikeGerrity,DaveCooper,TedCohen,SteveCummings,
JimmySmith,PeterDube,RuthieWashburn,KimCurl,ToniBoyd,RobinRuth,
ReneeBattle,DannyDuong,HungNguyen,DrewDaffron,KenO’Neal,Kim
Miller,JohnLauder,BobSmout,ToddStottlemeyer,PaulLeslie,DavidWise,
DanRutherford,LauraTaylor,LauraSetliff,TrinTranh,WilsonDizard,Paul
Elliott,JohnMetelsky,DonKnight,ArtGarrison,MarshallCohen,MarkWojno,
BillMcCarren,JonathanSalant,CaroleFeldman,TammyLytle,SheilaCherry,
RickDunham,DougHarbrecht,AudreyFord,TimAquilino,DebbieBeebe,Bill
Simpson,AnnetteTaylor,FredWills,CarleszaHarris,GardnerMcBride,Cindy
McBride,JimFlyzik,RobGuerra,JohnCoffey,LyleBeall,BobbieBeall,andto
RoyPatterson,who–withJimBauchspies-assignedmetomyfirstOracle
project.AndtoToddandCindyBauchspies,MikeandKateWatersandGavin,
JamesandClaudiaWaters,PhilandCharlotteJones,HarrietMarinandJoe
Motz,andDannaHenderson.
Tothosewhoarenolongerwithus:Aaron“Eppie”Epstein,MartinKuhn,
JohnCosgrove,MikeShanahan,GordonGustin,HelenKamajian,Georgine
Bauchspies,EileenWaters,andJackHenderson.
ToDanandBrendaHinkle,whogavemeoutstandingopportunitiesandfrom
whomIlearnedagreatdealaboutOracleandentrepreneurship.
TomyverymanyoutstandingOraclestudentsovertheyears,toonumerousto
mentionhere.Irememberoneclassthatgavemeagoing-awaypresentofa
smallantiquewaterpump,symbolicforhowlearningisasimportanttoone’s
lifeasiswaternecessaryforsurvival.Thatsymbolicgesturewasmoving
beyondwords,andIhaveneverforgottenit.
TomylongtimeprofessionalassociateandclosefriendBillBryant,whohas
mentoredandcoachedmeonmanyaspectsoftechnology,business,theworld,
andlife.
Tomyfather,Don,abrilliantengineer,excellentprojectmanager,published
author,greatprofessional,andgreatdadandtowhomIdedicatedmysecond
book.
Tomymother,Joan,thebestmotherintheworld,whoIlovewithallmy
heartandtowhomIdedicatedmyfirstbook.
Averyspecialthank-youtoLisa,theloveofmylife,forbeingwonderful,
sweet,patient,brilliant,soloving,andsoveryencouraging!
Andfinally,toJimBauchspies,whoislikeasecondfathertomeinmany
ways,andtohislatewife,Georgine,whoseinfectiouslaughandwarmthand
lovearetreasuredmemoriesIwillneverforget.JimgavememyfirstOracle
opportunity,aswellasagreatdealofadviceonallthingspersonaland
professionaloverthemanyyearsI’vebeenprivilegedtoknowhim.ItistohimI
dedicatethis,mythirdbook.
R
PREFACE
ecentlyIattendedatechnicalconferencehostedbyaleadingbigdatavendor.
Ifoundmyselfspeakingwithanexhibitorabouthisstartupcompany’s
NoSQLproduct.Nowfolks,Iloveallformsofdatasystems;theyallhavetheir
place.Key-valuepairs,dynamicschemas—theyallhaveause.Butthis
particularvendorboldlydeclaredthattherelationaldatabasewasuselessand
“SQLisdead.”Hedescribedhowhissystemcouldharvesttext-basedcomments
andinfersentimentacrossmillionsofrecordsandsupportallsortsofcleveruse
cases—allofwhich,incidentally,isdoablewithOracle-drivenSQL-based
systems.ButhewasconvincedthatOracle’srelationaldatabasemanagement
system(RDBMS)wasirrelevant.
SoIaskedhim,“Let’ssayIplaceanorderforthisproductofyours.Areyou
goingtotrackthatorderinaNoSQLdatabase?Ordoesyourofficerelyonan
RDBMStocaptureorders?”
Hethoughtaboutit.“Goodpoint,thatisarelationaldatabasesystem.”
“OK,andhowaboutyouremployees?Whenyourcompanytracksyour
hours,whatdotheyuse?”
“True,true,that’saSQLdatabasetoo.”
“Howaboutsupplymanagement?Shipping?Generalledgerandother
accountingfunctions?Inventorymanagement?Andtheotherofficesystems?”
“OK,yougotme—thosearealsoRDBMSservers,allSQLsystems,true.”
“Soanythinginvolvingorders,customers,employees,vendors,partners,
products,inventory,manufacturing,payroll,andjustabouteveryotheraspectof
thebusinessisaSQLsystem.”
“True,it’strue.”
“ButifIwanttoanalyzecommentsonmywebsite,yourcompany’sproduct
isagoodchoice.”
“Yes!Exactly!”Heseemedrelievedtobebackonfamiliarterritory.“Andwe
cananalyzemillionsofcommentspersecond.”
“OK,soifIgetmillionsofcommentspersecondonmywebsite,I’dbe
interested.”
“Yes.Twitterusesus.”
“Cool.SoifIwanttoperformsometextanalysisonamassivescale,Icould
theoreticallystilluseOraclebutyourproductmightbebetteroptimizedfor
massivelylargevolumesofinsert-onlyprocessingifI’mTwitter.”
“Exactly.”
“Awesome.Oneproblem.I’mnotTwitter.HowmanyTwittersarethereout
there?LastIcheckedtherewasone.Nowgranted,Iknowotherorganizations
haverequirementstoprocessmillionsofrecordspersecond.Butwho?
Facebook?OrGoogle?Soperhapstwo,ten,orthirtywebsites?”
“Well…probablymorethanthat.”
Sure,probably.Andweallknowthatnumberisgrowing.Butstill—to
suggestthismeansthedeathofOracle?
AndatthispointIdecidedtoreallyfreakhimout.“Yourproductisprobably
writteninJava,isn’tit?”
“Yes,itis.”
“YouknowOracleownsJava,right?”Helookedhorrifiedanddeniedthatit
wastrue.
Folks,I’masexcitedaboutthebigdatarevolutionandthepotentialofthe
InternetofThings(IoT),machinelearning,andalltechnology.Iworkinthe
worldofbigdatasystemsandamyriadofexoticdatamodelingalternatives.I
lovecutting-edgedevelopments.Butattheendoftheday,thereisnoquestion
thattheworkhorseofallindustryandgovernment,thebackboneofautomated
systems,thetechnologyonwhichvirtuallyalllargeorganizationsrelyhasbeen
—andcontinuestobe—therelationaldatabasemanagementsystem.Andthe
OracleRDBMSisthebestinthebusiness.
IrecentlyattendedatechnicalsessionatapopularJavaconferencewherethe
speakerpresentedsomethinglike32usecasesforvarioussituationswheresome
newNoSQLsystemwouldperformfasterorotherwisemoreoptimallythan
Oracle’sRDBMS.Eachexamplewasbasedonauniqueand—tome—unusual
(perhapssomewouldsaycontrived)usecase.“Soifyouhavethisunusual
combinationofdatastructuresandyourbusinessobjectiverequiressome
particulartypeofanalytics,sure,youcoulduseOracle,butifyouwantashorter
developmentcycleorfasterperformance,youshouldusethisNewNoSQLOpen
SourceTool#17.”Foroneexample,theSQLcoderequiredwas30linesin
length,butdoingthesamejobwiththealternativenewtoolrequiredonly23
linesofcode.OK,sure,soI’mgoingtolearn,install,configure,code,test,and
deployadifferenttooleachtimeforeveryoneof32differentusecasessoIcan
typesevenfewerlinesofcode.Yeah,let’sdothat.
Ornot.HowaboutIjustuseOracleandbedonewithit?
Again,folks,don’tgetmewrong—allsystemshavetheirplace.Buteven
today,themostpowerfulinformationtoolintheworldisstilltherelational
database.Asofthiswriting,theofficialrankingatDB-ENGINES.comliststhe
topfourdatabaseenginesinusetodayasbeingoftherelationaldatabasemodel,
withsevenofthetopteninusefallingintothatcategory(seehttp://db-
engines.com/en/ranking).Atthetopofthatlististhesamedatabasethathasled
theworldforyearsnow:Oracle’sRDBMS.
Oracle’sMySQLisnumbertwo.
ThecorelanguageatthefoundationofallOracleproductsisOracle’s
StructuredQueryLanguage(SQL),alanguagethatiscommontoallmajor
relationaldatabasesofallvendorsworldwide.
Evenmanyoftheneweralternativedatastoresthataren’tnecessarilybased
onarelationaldatabasemodelarestrugglingtoimplementSQL-likelanguages,
suchasCassandra’sCQLorIBM’s“SQL-likequeryinglanguageHiveQL”
(https://www.ibm.com/developerworks/library/bd-sqltohadoop2/)forusewith
Hadoopsystems.
Therelationaldatabasemodelisstillthenumber-onedatabasemodelinthe
world,andSQListheonlylanguagecommontoallrelationaldatabasemodels.
It’salsothestandardagainstwhichnewspecial-purposedatabasemodelspattern
newlanguagefeatures.
Thisbookisdesignedtohelpyoubecomecertifiedinthissignificant,
powerful,importantlanguageatthecoreofthesuccessfuloperationsof
governmentsandindustryworldwide.
YouhaveamadeabrilliantchoicetostudyandworkwithSQLandtouse
thisbooktoworktowardcertification.
Welcome!
InThisBook
Thisbookisorganizedinsuchawayastoserveasanin-depthreviewforthe
OracleDatabaseSQLexamforbothexperiencedOracleprofessionalsand
newcomerstoSQLtechnologies.Eachchaptercoversamajoraspectofthe
exam,withanemphasisonthe“why”aswellasthe“howto”ofworkingwith
andsupportingrelationaldatabaseapplications.
DigitalContent
Formoreinformationregardingthedigitalcontent,pleaseseetheAppendix,
“AbouttheDownload.”
ExamReadinessChecklist
AttheendoftheintroductionyouwillfindanExamReadinessChecklist.This
tablehasbeenconstructedtoallowyoutocross-referencetheofficialexam
objectiveswiththeobjectivesastheyarepresentedandcoveredinthisbook.
Thechecklistalsoallowsyoutogaugeyourlevelofexpertiseoneachobjective
attheoutsetofyourstudies.Thisshouldallowyoutocheckyourprogressand
makesureyouspendthetimeyouneedonmoredifficultorunfamiliarsections.
InEveryChapter
I’vecreatedasetofchaptercomponentsthatcallyourattentiontoimportant
items,reinforcevitalpoints,andprovidehelpfulexam-takinghints.Takealook
atwhatyou’llfindineverychapter:
EverychapterbeginswithCertificationObjectives—whatyou
needtoknowtopassthesectionontheexamdealingwiththechapter
topic.Theobjectiveheadingsidentifytheobjectiveswithinthechapter,
soyou’llalwaysknowanobjectivewhenyouseeit!
ExamWatchnotescallattentiontoinformationabout,andpotential
pitfallsin,theexam.Thesehelpfulhintsarewrittenbytheauthor,who
hastakentheexamandreceivedhiscertification—whobettertotellyou
whattoworryabout?Heknowswhatyou’reabouttogothrough!
OntheJobnotesdescribetheissuesthatcomeupmostoftenin
real-worldsettings.Theyprovideavaluableperspectiveoncertification-
andproduct-relatedtopics.Theypointoutcommonmistakesandaddress
questionsthathavearisenfromon-the-jobdiscussionsandexperience.
TheCertificationSummaryisasuccinctreviewofthechapterand
arestatementofsalientpointsregardingtheexam.
✓ TheTwo-MinuteDrillattheendofeverychapterisachecklistofthemain
pointsofthechapter.Itcanbeusedforlast-minutereview.
Q&A
TheSelfTestoffersquestionsintendedtocheckyourknowledgeof
eachchapter.Theanswerstothesequestions,aswellasexplanationsof
theanswers,canbefoundattheendofeachchapter.BytakingtheSelf
Testaftercompletingeachchapter,you’llreinforcewhatyou’velearned
fromthatchapter.
SomePointers
Onceyou’vefinishedreadingthisbook,setasidesometimetodoathorough
review.Youmightwanttoreturntothebookseveraltimesandmakeuseofall
themethodsitoffersforreviewingthematerial.
1.RereadalltheCertificationSummaryandTwo-MinuteDrillsections,
orhavesomeonequizyou.Youalsocanusethedrillsasawaytodoa
quickcrambeforetheexam.Youmightwanttomakesomeflashcardsout
of3×5indexcardsthathavetheTwo-MinuteDrillmaterialonthem.
2.Re-readalltheExamWatchnotes.Rememberthatthesenotesare
writtenbytheauthor,whohastakentheexamandpassed.Heknowswhat
youshouldexpect—andwhatyoushouldbeonthelookoutfor.
3.Re-taketheSelfTests.TakingtheSelfTestsrightafteryou’vereadthe
chapterisagoodideabecausethequestionshelpreinforcewhatyou’ve
justlearned.However,it’sanevenbetterideatogobacklateranddoall
thequestionsinthebookinonesitting.Pretendthatyou’retakingthelive
exam.Whenyougothroughthequestionsthefirsttime,youshouldmark
youranswersonaseparatepieceofpaper.Thatway,youcanrunthrough
thequestionsasmanytimesasyouneeduntilyoufeelcomfortablewith
thematerial.
4.Takethepracticeexams,timedandwithoutyourbook,toseehowyou
did.Makenotesasyouprogresstokeepalistoftopicsyouthinkyouneed
tostudyfurtherbeforetakingtherealexam.(SeeAppendixAformore
informationaboutthepracticeexams.)
T
INTRODUCTION
hisbookhelpsyoubecomecertifiedintheStructuredQueryLanguageby
preparingyoufortheOCAOracleDatabaseSQLCertifiedAssociateexam,
1Z0-071.Theobjectiveofthisstudyguideistoprepareyouforthe1Z0-071
exambyfamiliarizingyouwiththetechnologyandbodyofknowledgetestedon
theexam.Becausetheprimaryfocusofthebookistohelpyoupassthetest,I
don’talwayscovereveryaspectofSQL.Someaspectsofthetechnologyare
coveredonlytotheextentnecessarytohelpyouunderstandwhatyouneedto
knowtopasstheexam,butIhopethisbookwillserveyouasavaluable
professionalresourceafteryourexam.
Chapter1startswithasectionthatwillprovideyouwithsomeintroductory
informationabouttheexamandtheexamexperience.TherestofChapter1
delvesrightintothetopicsofthecertificationobjectives.
Thebookalignstothecertificationexam’sstatedobjectives,publishedby
OracleCorporationandstatedbythecompanytobethetopicsfromwhichthe
examdrawsitsquestions.Thisbookwillnot—andcannot—revealactualexam
questionsortheircorrespondinganswers.Thoseofuswhohavetakentheexam
areforbiddentorevealthatinformation.Butthisbookwillfocusonthetopics
thattheexamaddressesandwillteachyoutheinformationthat,asofthis
writing,youneedtoknowabouttheexam.
Thisbookiscomprehensiveandfocused.NotethatOracleCorporationhas
madeseveralmanualsavailableonlinethatdescribethefullfunctionalityofits
products.Butthoseofuswhohavebeeninthebusinessawhileknowthatwhile
thesearevaluableresources,theyarehuge—somearethousandsofpageslong
—andsometimestheyareoverwhelmingtonavigateeffectivelywithina
person’sprofessionallifetimewithoutsomesortofguide.Thisbookisyour
guide,butitismuchmorethanthat;itisaself-containedstudyguide,complete
withfulldescriptions,syntaxdetails,samplecode,self-tests,andpracticeexams
thatsimulatetherealcertificationexamexperience.Inotherwords,youare
holdingatreasuremaptothenuggetsofwisdomyouneedtoknowtopassthe
examandwinyourcertification.Itistheproductofyearsofexperience,earned
throughhardwork,testedamongveteranOracleprofessionalsfromaroundthe
worldandwithmanybackgroundsandstrengths,andconsolidatedintoone
clearlyorganizedformattoempoweryoutopreparequicklyandefficientlyto
becomecertified.
Thebookisdesignedtoservethefollowingaudiences:
Fortheveteranwhowantstozeroinontopicsonanàlacartebasis,
thebookiscategorizedbycertificationobjective.Ifyouhavealready
seenthepublishedcertificationobjectivesandwanttostudyuponafew
areas,youcandothatwiththisbook—findtheappropriatetopicand
studythosechapters.
Forthereaderwhowantsamorecomprehensivereview,the
objectivesandchaptersaresequentiallyorderedtobeginwiththe
fundamentalsandworkuptothemoreadvancedtopics.Youcanstudy
thebookstraightthroughandexperienceacompletepresentationofthe
knowledgeyouneedtopasstheexam.
Fortheseasonedpractitionerwhowantstojumpstraighttotheexam
experience,gototheonlinepracticeexamsandtakeanexam.(Seethe
Appendixonhowtoaccessthepracticeexams.)
The1Z0-071examhasbeenvalidatedagainstOracleDatabaseversions11g
Release2(version11.2.0.1.0)andupto12cRelease1(12.1.0.1.0).Forthis
book,IusedOracleDatabase12cRelease1.Forthescreenshots,Iusedscreen
capturesoftwareto“grab”imagesofSQLstatementsasdisplayedineither
SQL*PlusorSQLDeveloper.NotethatintheSQLDeveloper’sScriptOutput
display,numericdatadisplaysleftjustifiedbydefault,asopposedtoSQL*Plus,
wherenumericdatadisplaysrightjustifiedbydefault.Fortheentity-relationship
diagrams,IusedOracleSQLDataModeler.
Goodreading,studywell,andthebestoflucktoyou.Yourfeedbackis
invitedandwelcome:soh@corbinian.com.
Exam1Z0-071
1
OracleandStructuredQueryLanguage
(SQL)
O
CERTIFICATIONOBJECTIVES
1.01TheExam:AnOverview
1.02IdentifytheConnectionBetweenanERDandaRelationalDatabase
1.03ExplaintheRelationshipBetweenaDatabaseandSQL
1.04DescribethePurposeofDDL
1.05DescribethePurposeofDML
1.06BuildaSELECTStatementtoRetrieveDatafromanOracleDatabase
Table
✓Two-MinuteDrill
Q&ASelfTest
racleCorporation’simplementationoftheStructuredQueryLanguage(SQL)
isarguablythemostpowerfulandmostsignificantcomputerlanguageused
intheworldofgovernmentandbusinesstoday.Thischapterbeginstheprocess
ofpreparingyoutosuccessfullytakeandpasstheOracle1Z0-071exam,Oracle
DatabaseSQLCertifiedAssociate.First,I’lldiscussafewparticularsaboutthe
examandhowitisdifferentfromotherOraclecertificationtests.You’lllearn
whatyoucanexpectonexamday.Next,I’llmakesomesuggestionsaboutstudy
materials.ThenI’llusetherestofthechaptertoanalyzethefirstexamobjective,
forwhichthischapterisnamed.Inthefirstofthesubobjectives,I’lldiscussthe
conceptsofarelationaldatabasemanagementsystem(RDBMS)andexplain
entity-relationshipdiagrams(ERDs).NextI’lltalkabouttherelationship
betweentheRDBMSandSQL,andyou’lllookcloselyattwoimportantsubsets
ofSQL:DataDefinitionLanguage(DDL)andDataManipulationLanguage
(DML).Finally,youwilllearnhowtobuildaSQLSELECTstatement.Thiswill
completethefirstobjectiveandsetthestagefortheremainderofthisbookas
youstudyeachsubsequentobjectiveandprepareforthetest.
IfyouareaveteranOracle-certifiedprofessionalwhoisalreadyfamiliarwith
theexamprocess,youmightskipthenextsectionabouttheexam.Infact,you
maychoosetojumptoonlythoseexamobjectiveswhereyouthinkyouneed
study.However,Iencourageyoutoreviewallthematerialinthisbook,evenif
youthinkyouknowitallalready.Theexamwillchallengeyouonfinepoints
andnuances,anditwilltrytotrickyouwithconceptsandkeywordsthatalmost
soundcorrectbutarenot.Youwantyourknowledgeofthematerialtoberock-
solid.Forthepurposeoftheexamaswellastothebenefitofyourcareer,itis
crucialthatyoumaintainyourSQLskillsatthehighestlevel,asthisiswhat
organizationsintheworldtodayrequire—andtheexamdemandsthesamefrom
you.Beconfidentinyourknowledgeandyou’lldramaticallyincreaseyourodds
ofsuccessonexamdayandinyourcareer.
Let’sgetstarted!
CERTIFICATIONOBJECTIVE1.01
TheExam:AnOverview
TheOracleDatabaseSQLCertifiedAssociateisademandingexam.Itposes
questionsthattestthefullbreadthofyourknowledgeofSQLsyntaxand
processinganditsapplicationtobusinessrules.Atypicalquestionontheexam
mightgosomethinglikethis:
Youmaybeaskedtoreviewanexhibit,whichcouldbeasetofdata
outputinahalf-dozencolumnsandperhaps20or30rows—oritmight
beanentity-relationshipdiagram(ERD)containingasmanyasahalf-
dozenentitiesormore.
YoumaybeaskedtoreviewarelatedsetofSQLstatementsthatare
intendedtooperateontheexhibityouwerejustshown,withanumberof
SQLstatementsinwhichtheremightbeaseriesofnestedscalar
functions,aggregatefunctions,subqueriesofvariousforms,andtheuse
ofdifferentstatementsandclausesshowcasingfeaturessuchasvery
largedatatypes,complexjoinconditions,andsoon.
Someofthecodemaybecorrect,andsomemaynot.You’llneedto
recognizethedifference.
WiththesampleexhibitandSQLcodeinfrontofyou,youmaybe
askedtoidentifytheresultingstatusofthedatabaseaftertheSQL
statementsexecute.
YoumaybeaskedtoidentifytheinternalworkingsoftheOracle
database,inorder,inaccordancewiththeSQLstatementsyou’vebeen
shown.
Thelistofpossibleanswersmayincludemorethanonecorrect
response,andyoumustidentifyeachofthem.
Doesthatsoundlikealottodoforasinglequestion?Thenconsiderthis:for
theentireexam,youareallowed100minutestoanswer73questions.Thatisan
averageof1.36minutesperquestion,orabout82secondseach.
LikemanyofOracle’scertificationexams,the1Z0-071examincludes
manymultiple-choicequestionsthathavemorethanonecorrectanswer.
Inotherwords,asinglequestionmayrequireyouto“selectallofthe
followinganswersthatarecorrect.”Theresult:youmustevaluateeach
individualanswer.Onceyoufindacorrectanswer,youaren’tdone—you
mustcontinuecheckingthemall.Onthesetypesofquestions,youcan’t
ruleoutanyoftheanswersbasedontheprocessofeliminationsinceall
answersarepossiblecandidatesforbeingcorrect.Onequestioninthis
formatismorelikeseveralquestionsrolledintoone.Theresultisamore
demandingtestthatrequiresyoutobemoreknowledgeableandrequires
moreofyourtimetoanswer.Sostudywell.Reviewthisbookthoroughly.
Thisisnotasimpleexam.Butyoucandoit—equippedwiththisbook,
youroddsofsuccessincreasedramatically.
Thinkyoucanhandleit?Doyouhavewhatittakestobeaformally
recognizedandofficiallycertifiedOracleDatabaseSQLCertifiedAssociate?
Whetheryoudoornotremainstobeseen,butonethingisforcertain.This
bookwillprepareyou,strengthenyourknowledge,fillinthegaps,and
dramaticallyincreaseyouroddsofsuccess.
Sogetreadyforafunandrewardingchallengeandanimportantmilestonein
yourcareer.Getreadytoentertheworldofthetechnicalelite,tojointhecrème
delacrème,andtoberankedwiththebestofthebest!
WhattoDoandWhattoExpect
Hereishowtoregisterfortheexamandwhatyoucanexpectasyougothrough
theprocess.
TestLogistics
Hereareinstructionsforhowtoregisterandtaketheexam.(Pleasenotethat
Oracle’sregistrationprocessissubjecttochange.SomeofthespecificsI
describeheremayhavechangedbythetimeyoureadthis.)
Toregisterforanexam,visittheOracleCorporationwebsite
(www.oracle.com),clicktheCertificationlink,andlookforthe1Z0-071exam
page.Fromthere,clickthelinkaskingtoregisterfortheexam.Yourbrowser
willnavigatetothewebsiteforthecompanythatproctorstheexam,Pearson
Vue,atwww.pearsonvue.com.Fromthatwebsite,youcanlocatealocalfacility
atwhichyoucantaketheexam.Lookforanavailabletime—oddsareyou’ll
havetoplantotaketheexamatleastonedayinadvance,ifnotlonger,perhapsa
week.Provideyourcreditcardinformationfortherequiredpayment,andyou’ll
bebookedtotaketheexamattheprecisetimeandlocationyouselected.
Whenyouarriveattheexamlocation,youmaybeaskedtoturnoffyour
mobilephoneandgiveittoastaffmember.Inmycase,thestaffmemberlocked
mymobilephoneinaportableheavy-dutybag.Thestaffretainedthekeytothe
bagbuthandedthebagcontainingmymobilephonetome.IwastoldIwouldbe
abletotakethebagwithmeintothetestingroom,unabletoaccessitinsidethe
lockedcontainer.IwastoldIcouldrecovermyphoneaftertheexam.
You’llneedtoprovidetwoformsofIDtothestafftocompleteyoursign-in
process.Afterthat,you’llprobablybeescortedintoaroomwithadeskwitha
computer,loggedintoanautomatedtestingsystem.Ifyouwanttotakenotesfor
useduringtheexamonly,youmaybeprovidedwithafewblanksheetsofpaper
andapenoradry-eraseboard.(Notethatwhatevernotesyoumighttake,you
willberequiredtoturntheminattheendoftheexam.)
Oddsareyou’llbeleftaloneatthatpoint,butnotethattheexamhasnotyet
started.Onthecomputer’sautomatedtestingsystem,you’llbepresentedwitha
seriesofdisclosuresandagreementstoreview,andwhenyou’reready,youcan
clickabuttontoinitiatethetimedexam.Thetimerwillstartwiththefirst
question.Atimeronthescreenwilltrackyourremainingtimeasyouprogress
throughtheexam.
Allthequestionswillbemultiple-choicequestions.Manyofthequestions
willrequireyoutoclickabuttontodisplayanexhibit.Theexhibit—once
displayedbyyou—willprobablypopupinaseparatewindow,automatically
sizedjustbigenoughtoshowwhatevertheexhibitisdisplaying.Theexhibit
maybeanentity-relationshipdiagram,oritcouldbealistingofdatathatcould
havebeenthecontentsofatableortheoutputofareport.Manyquestions
includeSQLcode.
Duringmyexamexperiences,Ihavenoticedthatmanyquestionsareoften
accompaniedbyagoodnumberofdiagramsorcodeordataoutputnot
necessarilyrelevanttothepointofthequestion.Mostquestionswillpresentto
you,forexample,anERDandadatalisting,aswellasabriefexplanationof
somebusinessrulesorbackground,andfinallyasktheactualquestion.You’ll
eventuallyrealizethatyoucanwasteagoodamountofthetimeanalyzing
detailsofexhibitsbeforeyoufinallyreadthequestion,onlytorealizethatyou
didn’tneedtostudytheentireexhibitafterall.Manyquestions,onceunderstood,
canbeansweredataglanceoftheERD.Sodoyourselfafavor:whenyou
encounteranewquestion,skippastthecodeandthedataoutput(thereport,
exhibit,orwhatever)andskipaheadtotheactualquestion,whichisoftenthe
finalsentencejustbeforethemultiple-choiceanswersarepresented.Readthe
questionandthengobackandquicklyskimtheprecedingmaterial;you’llfind
thatyoucanidentifytheanswermuchmorequicklythiswaythanbyreadingall
thebackgroundmaterial.
Yourtimeislimited.Lookforthequestionfirst.Stayfocusedonthe
question.Don’tletalargeexampleofSQLtextdistractyou.Youhave73
questionstoanswerin100minutes.Thatis82secondsperquestion.
Somequestionswilltakeseconds;somewilltakemuchlonger.Watch
yourtime.
Thequestionswillbepresentedonthescreenoneatatime.ClickNextto
advancetothenextquestion.Youcanskipquestions;youaren’trequiredto
answereachquestionbeforeadvancing.Toflagaquestionforlaterreview,each
questiondisplayhasanoptionalMarkcheckboxintheupper-leftcorner,which
youcanuseto“mark”anyquestionforfuturereference,whetheryouhave
answereditornot.
Onceyouhaveprogressedthroughallthequestions,youwillreacha
summaryscreenshowingthenumbercorrespondingtoeveryquestionofthe
examinasingulartabularlisting.Thequestionswillbeidentifiedbynumber
only,andnexttoeachnumberwillbetheletter—orletters—oftheanswersyou
haveprovided.Anyquestion“marked”willbeindicatedbyahighlightedMnext
toit.AnyquestionnotfullyansweredshowswithahighlightedI—for
“incomplete”—nexttoit.You’llbeabletoeasilyreviewandcompletethe
answersandreviewanyquestions,includingthoseyouhavemarked,beforeyou
indicatethatyouhavecompletedtheexam.
Onenuancetokeepinmindoccurswhenyouencounteraquestionwithmore
thanonecorrectanswer.Toscorethosequestions,youwillhavetoprovidethe
correctnumberofcorrectanswers.Thequestionmaystate“choosethetwo
correctanswers,”forexample.Youwillhavetoprovidetwoanswers.Ifyoutry
toprovidethree,theautomatedsystemwillstopyou.Itwillpopupasmall
messagewindowtellingyoutofirstdeselectanexistingchoicetoensureyou
providenomorethanthecorrectnumberofanswerselections.
Butwhathappensifyouselecttoofew?Forexample,whathappenswhena
questionrequiresthreeanswersbutyouselectonlytwoandthenmoveontothe
nextquestion?Nothinginthesystemwillstopyoufromtakingthatstep.Ifyou
dothat,you’llbeleavingthequestionincompletewith—inthisexample—only
twoofthethreerequiredanswers.Youcanalwaysadvanceandleaveany
question“incomplete.”However,beforeyoucansubmittheexamforgrading,
youwillbeautomaticallypresentedwiththesummaryscreenattheend,in
whichanyincompletequestionswillbeflaggedclearlywithanIfor
“incomplete.”Youwillbeabletogobackandreview.
Reviewthesummaryscreencarefullyforanyunansweredquestions.
Lookforyour“marked”questionsthatmightrequirereview.Anddon’t
worry—youcan’tsubmittheexamforgradingwithoutfirstgoing
throughthesummaryscreen.Keepaneyeoutforit,andinspectit
carefully.
Whenyouaredonewiththequestionsandaresatisfiedthatyouhave
answeredeverything,clickExitonthesummaryscreen.Thetestscorewillbe
instantlyevaluated,andyoumaybeshownyourscoreandpassinggradeonthe
screen.Ifnot,you’llprobablybee-mailedtheresultswithin24hours.
Atthatpoint,pickupanypapersyoumayhaveorlockedbagscontaining
yourvaluablessuchasyourmobilephone,andvisitthefrontdeskofthetesting
center,whereaclerkmayprovideyouwithacopyofyourtestresults.Theclerk
canalsounlockthecontainercontainingyourmobilephone,whichyoucan
retrieve,andyoucanexitthefacilityknowingyouhavesatisfiedthe
requirementstobecomeahappyOracleDatabaseSQLCertifiedAssociate.
OracleSQLvs.ANSISQL
ThecertificationexamwilltestyouonOracleSQL.OracleSQLiscloseto,but
notidenticalto,thestandardestablishedforSQLbytheAmericanNational
StandardsInstitute(ANSI),alsoknownasANSI-standardSQL.Youwillnotbe
requiredtoknowthedifferencesbetweenthem.
OracleSQLvs.OracleSQL*Plus
ThecertificationexamwilltestyouonOracleSQLbutnotonOracle’s
enhancementstoSQLknownasSQL*Plus,withtwoexceptions:theDESC
commandandsubstitutionvariables.
SQL*Plusisasetofcommands,anditisalsoasoftwaretoolwithan
interfaceintowhichyoucantypeSQLandSQL*Pluscommandsandmonitor
theirexecution.SQL*Pluscommandsincludealargenumberofoptions,many
ofwhicharedevotedtoformattingoutput.Thosecommandsarenotincludedin
theexam.Youwon’tbestudyingSQL*Pluscommandsinthisbook,otherthan
DESCandsubstitutionvariables.
NotethatIwillusetheSQL*Pluscommand-lineinterfacefromtimetotime
todemonstrateOracleSQLcommands.
SQLFundamentalsIvs.SQLCertifiedAssociate
Sinceyou’replanningonobtainingyourcertificationbytakingthe1Z0-071
exam,thenchancesareyoumayhavealreadylookedat,oreventaken,the1Z0-
051exam,SQLFundamentalsI.Thetwoexamssharesomecommonobjectives,
but1Z0-071goesbeyond1Z0-051.SeeTable1-1foracomparisonofthose
objectives,includingwherethetwoexamsaresimilarandwheretheyare
different.Thetableliststheobjectivesfor1Z0-051ontheleftand1Z0-071on
therightandlinesuptherowstoshowwheretheexamssharecommon
objectivesandwheretheyvaryfromeachother.Herearesomeexamples:
1Z0-051testsontheCartesianproduct(6.4),but1Z0-071doesnot.
Bothexamstestonthe“RestrictingandSortingData”objectiveand
itsthreesubobjectives,but1Z0-071addstwoadditionalobjectivestoit,
coveringampersandsubstitutionandtheSQLrowlimitingclause.
Only1Z0-071testsoncorrelatedsubqueries,EXISTS,NOT
EXISTS,andWITH,aswellasthedatadictionary,controllinguser
access,multitableinserts,andMERGE.
Only1Z0-071testsontheobjectives“ManagingObjectsUsingData
DictionaryViews,”“ControllingUserAccess,”and“ManipulatingLarge
DataSets.”
ThosearejustsomeexamplesoftheinformationinTable1-1.Notethat
Oracledoesnotnumberitsobjectives,soItookthelibertyofassigningnumbers
totheobjectives,respectingthesequenceoftheoriginallypublishedlistat
Oracle’swebsite.
TABLE1-1 Comparisonofthe1Z0-051and1Z0-071ExamObjectives
Asyoucansee,theSQLCertifiedAssociateexamgoesfurtherthanthe
topicsaddressedbytheSQLFundamentalsIexam.
TheSQLFundamentalsIexamconsistsof64questionsin120minutes;SQL
Associateconsistsof73questionswithin100minutes.Atthetimeofthis
writing,thepassingscorerequirementspublishedattheOracle.comwebsiteare
60percentforSQLFundamentalsI
63percentforSQLAssociate
However,notethatpassingscorerequirementsaresubjecttochangewithout
notice.OracleCorporationreservestherighttosubstituteoneversionofthetest
withanotherversion,anddependingonthecomplexityofthespecificquestions
includedinanewversion,thepassingscoremaybeadjustedaccordingly.Oracle
publishesthisnoticeonitswebsiteregardingtherequiredpassingscoreforany
givenexam:
OracleroutinelypublishesnewversionsofitsOracleCertification
exams.Thepassingscoreforeachexamversionissetindependentlyto
maintainaconsistentscoringstandardacrossversions.Forexample,to
maintainaconsistentstandardforsuccess,anewversionofanexamwhich
containsmoredifficultquestionsthanthepriorversionwillbeassigneda
somewhatlowerrequiredpassingscore.Forthisreason,passingscores
mayvarybetweendifferentexamsinyourcertificationtrack,andbetween
laterandearlierversionsofthesameexam.Oracledoesnotrecommendan
exampreparationstrategytargetingthepassingscore,aspassingscoresare
subjecttochangewithoutnotice.
Inotherwords,studywell,anddon’tlimityourgoaltosimplyachievingthe
minimalpassingscorerequirement.Instead,dothebestyoupossiblycanto
increaseyourchancesofvictory.
SubjectAreas
Manyquestionschallengeyourknowledgeofseveralfactsatonce.Forexample,
Iencounteredonequestionthatpresentedseveralnestedscalarfunctionsina
seriesofSELECTstatements.Ihadtodothefollowing:
Understandclearlywhateachindividualscalarfunctiondid
Recognizesyntaxissuesthroughoutthecode
Understandthedatatypetransformationsasonefunctionpassedon
resultstoanother
Confirmwhethertheparameterpositioningwasaccurate
Identifytwofactsabouttheprocessandendresult,allwithinthe
contextofthegivenERD
Themoraltothestoryisthatyoushouldstudythisbookwell,understand
everythinglistedinthecertificationobjectives,andgetallofyourfactsdown
cold.Ontestday,showuprestedandontimeanddon’tgetdistracted.Witheach
question,seekouttheactualquestionfirstandthenlookattheexhibitsandcode
listings.Andwatchthetime.
You’llbegladyoudid.
ConfirmAppropriateMaterialsforStudy
Thissectiondiscussessomeitemsyoumaywanttogatherasyouprepareto
studyfortheexam.IfyouareaseasonedveteranintheSQLbusiness,youmay
notneedanyofit—thisbookwillsuffice.Butifyou’dliketoputforththatextra
bitofeffort,itmightbeagoodideatogetyoursoftwareanddocumentation
togetherasdescribedinthissection.
Software
OracleCorporationstatesthatithasvalidatedthe1Z0-071examquestions
againstOracleDatabase11gRelease2(11.2.0.1.0)andupto12cRelease1
(12.1.0.1.0).Iusedversion12c,Release1,inpreparingtheSQLstatementsfor
thisbook.
Ifyoudon’thavethesoftwareyouneed,youcandownloaditfromthe
officialOracleCorporationwebsite,atwww.oracle.com.
Ifyouhaven’tjoinedtheOracleTechnologyNetwork(OTN),thenyoushould
doitrightaway.Thereisnochargeforit.Visitwww.oracle.com/technetwork/
andsignuptoday.Fromthere,youcandownloadagreatdealofOracle
softwareforevaluationandstudy,includingthedatabaseitself.
IfyouinstallthepersonalversionofOracle,you’llprobablygetSQL*Plus
andSQLDeveloper,eitherofwhichyoucanuseforenteringandexecutingSQL
statements.Ifnot,thenbesuretodownloadoneortheothertoinstallanduse
withthedatabase.You’llneedoneorbothofthoseor,ifnotthem,thensome
sortoftoolforenteringandexecutingSQLcommands.Chancesareyoualready
havesomethingthatyou’reusingorelseyouprobablywouldn’tbeconsidering
certification.
Oracle’sToolsforWorkingwithSQL
MostofOracle’svariousproductsandtoolsuseSQL.ThisincludesOracle
productssuchasOracleFusionMiddleware,includingOracleSOASuite,as
wellasOracleAPEXandothers.Manydevelopmenttools,suchasOracle
JDeveloper,providetheabilitytoenterSQLstatementsandexecutethem.Two
ofthemostcommonlyusedtoolsforthispurposeareOracle’sSQL*Plus
command-lineinterfaceandOracleSQLDeveloper.
TheSQL*PlusCommand-LineInterfaceTheSQL*Pluscommand-line
interfaceisasimplewaytotypeSQLcommands,executethem,andobservethe
result.Itisauniversalsystemthatoperatesthesamewayineveryoperating
system.
SeeFigure1-1foranexampleofwhatthecommand-lineinterfacelookslike.
FIGURE1-1 TheSQL*Pluscommand-lineinterface
Theadvantagetothecommand-lineinterfaceisthatitfunctionsidenticallyin
theWindows,Unix,andLinuxoperatingsystems.Thatisoneofthemany
advantagesthatOraclehasalwaysoffered—easeofuseinanyoperatingsystem.
SQLDeveloperTheSQLDeveloperinterfaceisaninteractive,point-and-click,
menu-drivengraphicaluserinterface(GUI)thatispowerfulandgives
developersaquickoverviewoftheentiredatabase.Somecommandscanbe
enteredbyeithertypingthemorusingapoint-and-clickinteractionwitha
graphicmenu.SeeFigure1-2foranexampleofwhatSQLDeveloperlookslike.
FIGURE1-2 TheSQLDevelopertool
ThereareothertoolsthatprocessSQLstatements:
OracleJDeveloper
OracleApplicationExpress
SQLWorkshop
Others
Forthepurposesofthecertificationexam,yourchoiceofinterfaceis
irrelevant.SQLstatementsexecutecorrectlyinallOracleinterfaces.
TheexamwilltestyourknowledgeofthesyntaxofSQL,notyour
abilitytopointandclickyourwaythroughaGUI.Thefactthatyou
mightbeabletocreateaSQLtableusingacodegeneratorthrougha
point-and-clickinterfacewillnothelpyouduringtheexam.Ifyouarea
seriousapplicationsarchitect/programmer,therewillcomeatime—
probablyfrequently—whenyouneedtodesignorprogramafeatureas
partofalargerapplicationanddesignandembedSQLcodeintoother
programminglanguagesthathavenoaccesstotheniceGUItoolsduring
applicationruntime.Furthermore,asyou’llseeinnumerousinstances
inthisbook,therearemanytypesofSQLstatementsinwhichyoucan
combinefeaturesandclausesinsuchawaythattheyappeartobe
correct,executewithouterror,andproducelotsofoutput—allofwhich
canbetotallyerroneous.AtrainedeyeglancingattheSQLcodewill
recognizethemistake;anuntrainedeyewillnotevenrealizethereisa
problem.Inotherwords,thereisnoalternativetohavingcomprehensive
knowledgeofthesyntaxofSQL,neitherintheworldoftheserious
softwaredevelopernoronthecertificationexam.Knowyoursyntax.As
youstudyforthisexam,typeyourcommands,makesuretheyarecorrect,
andmakesureyouunderstandthemthoroughly.
Documentation
Thebookyouhaveinyourhandsisanoutstandingreferenceandisallyouneed
inthewayofdocumentation.Thisbookisthesinglebestguideyoucould
possiblygettoprepareyoufortakingtheexam.
Butifyoucravemore,youcandownloadadditionaldocumentationfromthe
OracleTechnologyNetworkwebsite,atwww.oracle.com/technetwork/.The
amountofdocumentationisalmostoverwhelming,particularlytoanewcomer.
Butonevolumeinparticularisofinterestforthepurposeofthecertification
exam:theSQLLanguageReferenceManual.Itisahugebook,withcloseto
2,000pages.ThesizeofthePDFversionismorethan14MB.Itssyntaxcharts
arecomplexandgobeyondtheneedsoftheexam.Thebookcontainsfarmore
informationthanwhatyou’llneedtopass,allofwhichisyetanotherreasonwhy
you’rebrillianttohaveobtainedthisbookyounowhaveinyourhands.Iwill
refertotheSQLLanguageReferenceManualfromtimetotime,butIwillfocus
onlyonthepartsthatarerelevanttopasstheexam.
OtherusefulreferencesincludeOracle’sAdvancedApplicationDeveloper’s
Guide,Concepts,SecurityGuide,GlobalizationSupport,andAdministrator’s
Guide.
Thequestionsforexam1Z0-071havebeentestedagainstthefollowing:
OracleDatabase11gRelease2
OracleDatabase12cRelease1
IwillrefertothesetofmanualsforOracleDatabase12c,Release1,whichis
alsoreferredtoas12.1.
CERTIFICATIONOBJECTIVE1.02
IdentifytheConnectionBetweenanERDanda
RelationalDatabase
Fortheremainderofthisbook,Iwillexamineeachoftheobjectivesoftheexam
itselfindetail.InthissectionIdiscusstheconceptofanentity-relationship
diagramandtalkabouthowitistransformedintoarelationaldatabase.Along
thewayI’lldiscussbusinessrequirements,datamodeling,theroleofprimary
andforeignkeys,andtheconceptofdatanormalization.
Entity-RelationshipDiagramsandDataModeling
Generallyspeaking,thereasonadatabaseexistsistosupportanexisting
businessprocessormodelsomeexistingreal-worldsystem.Forexample,a
typicalbusinesshasemployeeswhoservecustomersbyprovidingsomesortof
productorservice.Ifyouaretaskedwiththeresponsibilityofbuildingan
automatedbusinesssystem,youmightcreateadatamodelofthebusiness’s
operations.Tocreatethedatamodel,youidentifythebusiness’sbasic“things”
(orentities).Anentitymightbeacustomer,anemployee,oraproduct.You
mightaddmoreabstractconceptsasentities,suchasanorder,areturn,a
transaction,acustomer’sstorevisit,andsoon.
Asyouidentifyyourentities,you’llneedtodeterminetherelationships
amongthoseentitiesintermsofone-to-one,one-to-many,ormany-to-many
relationships.Forexample,you’llprobablyallowforanyonecustomertoplace
zero-to-manyorders.Whywouldyouhaveacustomerwithnoorders?It
dependsonyourbusinessrules—youmaywanttotrackpotentialcustomerswho
haveaskedforaprintcopyofyourcatalogbutperhapshaven’tyetordered
anything.
You’llprobablywanttoallowforanyoneordertoconsistofmultipleline
items,eachofwhichistakenfromyourmasterlistofavailableproducts.Each
one-lineitemmaybereturned—butnomorethanonceandideallynotatall.
SeeFigure1-3foranexampleentity-relationshipdiagramillustratingthis
initialdatamodel.
FIGURE1-3 Entity-relationshipdiagram
ThisexampleERDshowsfiveentitiesandtherelationshipsbetweenthem.
Eachentityisabox;eachrelationshipisalineconnectingtwoboxeswithsome
symbolstodetailthenatureoftherelationship.Forexample,anyonecustomer
willhavezero,one,ormanyorders.ThisisindicatedinbetweenCustomersand
Ordersbythelinethatshowsthecircle(zero)withthecrow’sfoot(many)onthe
sideofthelineconnectingtoOrders.Thecircleandcrow’sfootspecifythat
theremaybezero-to-manyordersforanygivencustomer.
ForanyonerowinOrders,theremaybeone-to-manyLineItemsentries,
indicatedbytheline(one)withthecrow’sfoot(many)neartheLineItemsentity
onthelinefromtheOrdersentity.
AnyoneProductsentrymaybeorderedzero-to-manytimesasaLineItem.
AndasingleLineItemsrowmaybereturnedzero-to-onetime,indicatedbythe
circle(zero)andbar(one)attheReturnsentity.
Onceyou’veestablishedtheinitialsetofentitiesandtheirrelationships,you
mightenhanceyourERDwiththeadditionof“attributes”toeachentity.See
Figure1-4.
FIGURE1-4 ERDwithattributes
Forexample,foreachcustomeryoumightwanttotrackthecustomer’sname
andcontactinformationsuchasane-mailaddressandmailingaddress.Foreach
order,you’llwanttocapturetheorderdateandperhapsthetermsofpayment.
Foreachlineitem,you’llwanttoknowthequantityorderedandperhapsa
discountfortheparticularlineitem,ifappropriate.
Let’sconsideranotherexample.ThefictionalCoddCruiseLinesisa
companythatprovidescruisevacationstoitscustomers.Thecompanyoperates
ships,andeachshipisassignedtoasinglehomeport.Eachshipisfilledwith
cabinsthatcustomersreservefortheircruisevacations.Thecompanyhas
employeeswhoareassignedtooneshipatatime.
Figure1-5isanexampleofwhatanERDforthiscruiselinemightlooklike.
FIGURE1-5 ERDforCoddCruiseLines,initial
Theexampleshowsthatforeachport,thereareoneormoreships,and
conversely,eachshipisassignedtooneandonlyonehomeport.Eachshiphas
zeroormoreemployees,suggestingthatyoumightstarttrackingshipsinyour
datamodelbeforetheyhaveemployeesassignedtothem—perhapswhilethe
shipisstillunderconstruction,inmaintenance,andnotinservice.Also,each
shipconsistsofoneormorecabins.
Ifyouweretostartassigningattributestotheentities,youmightendupwith
theexampleshowninFigure1-6.
FIGURE1-6 ERDforCoddCruiseLines,withattributes
Forexample,foreachshipyoumightwanttocapturetheship’ssizeand
capacity.Foreachemployeeyoumightwanttotracktheemployee’sname,start
date,andcurrentsalary.Whathappenswhentheemployeegetsaraise—doyou
retainarecordofthehistoricsalary?Notinthisexampledatamodel,butyou
couldextendthemodelbyaddinganentityfor“salaryhistory”orsomething
comparableandthenassignthatentitysomeattributes,suchassalaryamount,
initialdate,andfinaldateofserviceatthatsalary,andperhapsyoucouldeven
recordtheindividualauthorityintheorganizationwhograntedthatsalaryinthe
firstplace.
Thereisnosingleabsoluterightorwrongwaytomodelareal-worldbusiness
process.Theappropriatemodelwillvarybasedonwhatyouintendtocapture
andhowyouintendtoworkwiththesystem.Thefinalauthorityisthesetof
real-worldbusinessrequirementsyouaresupporting.Yourdatamodelisan
attempttorepresentthosereal-worldbusinessrequirements.
Forexample,inthefictionalCoddCruiseLines,youarecapturinghome
portstowhichshipsareassigned.Intherealworld,thereexistmanythousands
ofports.Areyouintendingtocapturethemall?No,notinthismodel,becauseit
isn’tnecessaryforthebusiness.Areyouintendingtocaptureeveryporttowhich
yourshipswilltravel?Notinthismodel.Youareintendingtocaptureonlythe
homeports.Butyoucouldmodifythemodelifyourbusinessrequirements
changedandyourintendedpurposeofyourautomatedsystemweretochange.
Thepurposeofadatamodelisnottorepresenteverypossibilitythatexistsinthe
realworldbuttocapturethatnecessarysubsettowhichtheautomatedsystem
willprovidesupport.
RelationalDatabases
Nowlet’sstarttouseanERDtocapturesomeactualdata.Rememberthatan
ERDisalogicalrepresentationofareal-worldsystem.Arelationaldatabaseisa
physicalimplementationofthatERDand,assuch,willneedtocaptureactual
data.Therelationaldatabasebuildsontheentitiesandtheirrelationshipsby
specifyingattributesoftheentities.Intherelationaldatabase,you’lladdprimary
keystouniquelyidentifyeachrowwithineachentity.Youmayalsoaddforeign
keystosomeentitiestorelatetherowsofthatentitytoanotherentity’srows.
Let’slookathowthisworks.ConsiderTable1-2,whichshowsalistofships
withthefictionalCoddCruiseLines.Thislistiswhatyoumightusetocreatea
databasetable.ThelisthascolumnsforShipIDandattributesoftheShips
entity.ThereasonyouneedaShipIDistomakesureyouhaveaunique
identifierforeachrowinthelist.Thefirstrowhasauniqueidentifierof1,the
secondrowhasauniqueidentifierof2,andsoon.Thisuniqueidentifierisakey
toidentifyingaparticularship’srow.ThevaluesfoundintheShipIDcolumn
uniquelyidentifyeachship.Thiscolumnisconsideredtobeaprimarykey
column.
TABLE1-2 CoddCruiseLinesShips
Now,let’ssayyoualsowanttocreatealistofemployees.You’llcreatea
primarykeycalledEmployeeIDandcapturealltheattributesofourEmployees
entity,alongwithsomethingadditional:ShipID.SeeTable1-3.
TABLE1-3 CoddCruiseLinesEmployees
Now,ifIweretoaskyoutoidentifytheshiptowhichMikeWestwas
assigned,whatwouldyousay?
Naturallyyouwould(orshould)sayitwastheCoddVictorious,andyou
woulddeterminethisbylookinginthelistofemployees,findingtherecordfor
MikeWest,“relating”thatrecord’sShipIDvaluetothelistofships,andfinding
thatShipID4“relates”totheshipnamedCoddVictorious.
ShipIDistheforeignkeyforEmployees.Aforeignkeyforagiventable
pointstotheprimarykeyofanothertable—inthiscase,Ships—toindicate
whichrowrelatestothecurrentrow.
Theselistsarewhatyouwillstoreindatabasetables.Andthedatacontained
withinthelistsareexamplesofthesortofdatathatarelationaldatabasemight
containintablesandthesortofprocessingitdoesto“relate”datainonetableto
datainanothertable.
Atypicaldatabaseconsistsofanynumberoftables,manyofwhichcontain
keyinformation(suchastheEmployeeIDandShipIDvaluesinthefigures)that
isusedtorelaterowsofonetabletorowsofanothertable.Themechanismused
toidentifyauniquerowwithinalistisaprimarykey,andyouuseaforeignkey
torelatedatafromonetabletoanother.
ThePRIMARYKEYisauniqueidentifierforarowinaparticular
table.
TheFOREIGNKEYisacopyofsome(orall)ofonetable’s
PRIMARYKEYdatainasecondtablesothatthesecondtablecanrelate
tothefirst.
Manyoftheexamquestionswillaskyoutoconsultan“exhibit”that
willfeatureanERDandthenaskyouaSQLquestionbasedonthetables
presentedintheERD.Thisbook’sselftestsincreasinglydothesameas
youprogressthroughthebook,andthepracticeexamsusethesame
approachastheofficialcertificationexam.
Many-to-ManyRelationships
Oneofthemostcommonchallengesintransformingalogicalmodelintoa
typicaltransactionalphysicalmodelhastodowiththesituationofamany-to-
manyrelationshipbetweentwoentities.Rememberthatthenatureofthe
relationshipbetweentwoentitiesisdefinedbytherequirementsofthebusiness
model.IntheearlierexampleofthefictionalCoddCruiseLines,thebusiness
requirementwasonlytotrackanemployee’scurrentlyassignedship.Butwhatif
therequirementweredifferent?Whatifyouneededtotrackallshipstowhichan
employeewereeligibletowork?Thiswouldsuggestthatanyoneemployee
couldbeassociatedwithzeroormoreships,andanyoneshipcouldbe
associatedwithzeroormoreemployees.
Whyzero-or-more?Itdependsonthebusinesslogic—let’ssayyoudecide
youwanttostarttrackingshipsbeforeemployeesareassignedandyoucapture
informationaboutemployeeswhoaren’tnecessarilyassignedtoships.Because
ofthosebusinessrules,you’llgowiththezero-to-manyrelationshipsinboth
directions.However,ifthebusinessdoesn’thavetheserequirements,thenyou
mightrequireone-to-manyrelationshipsinstead—itdependsonthebusiness
requirements.
Butregardlessofwhetherthesearezero-orone-to-manyineitherdirection,
thisparticularapproachtothebusinessresultsintwoentitieswithamany-to-
manyrelationshiptoeachother;seeFigure1-7.
FIGURE1-7 Many-to-manyrelationship
Theexampleshowsthattheships-to-employeesrelationshipismany-to-
many,meaningthatyouhaveone-to-manyrelationshipsinbothdirections:one
employeemaybeassignedtomultipleships,andoneshipmayhavemultiple
employeesassignedtoit.
Thepresenceofamany-to-manyrelationshipinanERDisamajorflagina
datamodel.Themessage:thedatamodelismissinganentity.Whileit’sfineto
showamany-to-manyrelationshipasyouareintheprocessofbuildingadraft
model,thereisneveramany-to-manyrelationshipinafinishedphysicalmodel.
Thereason:itdoesn’twork.Imaginetryingtotransformthisintothesortoflists
—ortables—youjustlookedatinthepreviousexample.Trytocreateyourown
lists—oneofships,anotherofemployees.Assignprimarykeyvaluestoeach
list.Thentrytofigureouthowyou’regoingtomaketheforeignkey
assignments.Youcouldtrytoaddoneforeignkeycolumntoonetableandthen
theother—evenboth.Butyou’lldriveyourselfcrazytryingtolistthedataso
thateachrowofshipsislistedonce,eachemployeeislistedonce,andthereare
foreignkeystorepresentthemultipleinterrelationshipsthatmightexist.Itwon’t
work.
Here’swhatworks:athirdentity.SeeFigure1-8.Thepresenceofamany-to-
manyrelationshipbetweentwoentitiesisalwaysanindicationthatathirdentity
belongsinbetween,andit’softenanentitythatismoreabstractinnature.Inthis
case,nametheentityRosteranduseittolisteachassignmentofanygiven
employeetoanygivenship,alongwithstartandstopdatesofwhenthe
employeeisassignedtoworkontheship.Thisenablesyoutolistasmany
repeatinglinesasrequiredforanygivenship—onceforeveryemployee
assigned—andtodothesamethingintheotherdirection,listingevery
employee’sassignmenttoshipaftership,asmanyasisrequired.
FIGURE1-8 Many-to-manyrelationshiptransformed
ThisisstandardoperatingprocedurewhenbuildinganERDandpreparingto
buildarelationaldatabase.
DatabaseNormalization
Gooddatabasedesignrequiresconsiderationfordatanormalization.Afull
analysisoftheconceptofdatabasenormalizationisbeyondthetaskofthisbook,
whichistoprepareyoufortheexam.Butitisworthnotingtherulesof
normalization,whicharerulesthatdrivethedesignofanysetoftables
composingarelationaldatabase.
Table1-4summarizesthemostcommonlevelsofnormalization.
TABLE1-4 LevelsofNormalization
Adatabaseadherestothefirstnormalform(1NF)whentablesarestructured
inaone-to-manyrelationship.Forexample,intheearlierexampleofshipsand
employees,itwouldhavebeenaviolationof1NFifyouhadinsteadplacedall
theshipnamesintheEMPLOYEEStableandrepeatedeachship’snamewith
eachrecordofeachemployeethatmighthappentobeassignedtothatship.By
separatingshipandemployeedata,yousatisfiedtherequirementfor1NF.
Secondnormalform(2NF)existswhennononkeyattribute(column)is
dependentuponpartofacompositekey.
Thirdnormalform(3NF)iswhentheone-to-manyrelationshipswithinadata
modelarestrictlyrespected—thatis,whenmany-to-manyrelationshipsareeach
transformedintoone-to-many-to-onerelationshipsasyoujustdidintheprevious
section.3NFrequiresthatprimarykeyvaluesareassociatedonlywithlogically
relatedattributes,andotherdata—suchaslookupdata—ismovedtoseparate
tables.
3NFdesignsareidealwherelotsofdataentryandupdatesareinvolved,as
theirdesignminimizesthepossibleduplicationofdataandtheassociatedriskof
dataconflicts,resultinginconflictingdatawithinthedatabase.Forexample,ifa
customeraddressisstoredinmultiplelocationsandthecustomercontactsthe
organizationwithanewaddress,youdon’twanttoruntheriskthatthenew
addressisrevisedinonelocationbutnotelsewhere.3NFreducesandeven
eliminatessuchrisk.
1NFand2NFfavorheavyread-onlyusecases.Forexample,ifyouneedto
producereportsthatconnect(orjoin)thecustomeraddresswiththecustomer
orderhistoryandtheitemsordered,thenthelessyourqueryhastogosearching
indifferenttables,thefasteryourreportwillexecute.Forsystemswithmillions
ofrecords,lotsofcomplexquerying,andnoneedtoaddnewdataorupdate
existingrecords,1NFand2NFofferfasterexecutionwithoutthedownsiderisk
ofconflictingdatathatmightexistina3NF.
Nothingintheexamobjectivesnorinmyexperienceofhavingtaken
theexamindicatesthatthetestinvolvesanythingotherthantypicalthird
normalformscenarios.
Forthesereasons,generallyspeaking,mosttransaction-baseddatabase
applicationsaredesignedtobe3NF.Datawarehousesandotherapplications
intendedtosupportanalysisandreportingaregenerallydesignedat2NFor1NF.
Many“bigdata”systemsaredesignedtoworkwith2NFor1NFmodels.
Mostdataentersanorganizationthroughatransaction-basedsystem(a3NF)
andisthenmovedintoadatawarehouseordatalakeforanalysis(a2NFor
1NF).Forthisreason,3NFisseenasastartingpointformostdata,and1NFor
2NFmodelsaresaidtobedenormalized,whichistosaythattheyadhereto
somelevelofnormalizationbelow3NF.“Bigdata”systemsareoftendescribed
asdenormalizedsincetheytendtoadhereto1NFor2NFdesign.
Thesedescriptionsaremerelyarefresherandarenotintendedtobean
exhaustiveanalysisofdatabasenormalization.Forthat,Ireferyoutoother
booksintheOraclePresslinethatdealwiththefundamentalsofdatabase
design.
Thereisnosinglerightorwrongwaytomodeleverysystem.Somedesign
decisionsinvolvetrade-offs,suchasbetterperformance(speedofresponse)
versuslessduplicatedata,oranefficientdatamodelversusamorecomplex
application.ThesearejustsomeofthechallengesadatamodelerorSQL
developerfaces.
CERTIFICATIONOBJECTIVE1.03
ExplaintheRelationshipBetweenaDatabaseand
SQL
Arelationaldatabaseisaphysicalrepresentationofabusinesssystem.Itis
sometimesdescribedasapersistentstore,meaningthatitisusedtoretain
informationthatmightbegeneratedorcapturedwhenasoftwareapplicationis
executing,butitretainsthatdataaftertheapplicationhasceasedexecution—the
data“persists”beyondthelifeofagivenapplication.Adatabasehousesdata
outsideoftheapplicationitselfandmakesthatdataavailabletoanyauthorized
inquiringsoftwareapplicationorservice.
SQListheindustry-standardlanguageforcreatingandinteractingwitha
relationaldatabase.SQLisamechanismtocreateandinteractwiththedatabase;
itisnotthedatabaseitself.SQLcommandscanbeusedonastand-alonebasis,
ortheycanbeinvokedfromwithinotherapplicationswritteninotherlanguages.
Mostpopularsoftwarelanguages,suchJava,PHP,andothers,havethe
capabilitytoissueSQLstatementstoarelationaldatabase.Thoselanguageswill
havetheabilitytotransfertheirowndataintoSQLstatements,sendtheSQL
statementtoadatabaseforprocessing,andthencapturethereturningdatafor
additionalprocessing.
Anumberoftoolsexistthatenableadeveloperorotherdatabaseusertoissue
SQLstatements.Forexample,Oracle’sSQL*PlusandSQLDevelopertools
empowerausertobuildandexecuteSQLstatementstobuildandinteractwith
databases.ThesetoolsissueSQLstatementsandreceiveoutputthesameasany
softwarelanguageorotherclientapplicationmightdo.
SohowdoyoupronounceSQL?Somepeoplepronounceitbyspellingout
theletters,asin“ess-cue-ell.”Mostofuspronounceitas“sequel.”Both
pronunciationsarefine,andbothareusedbyrespectedprofessionalsinthe
industry.Whateveryoudo,justdon’tcallit“squeal.”
Ioncehadaguycalltheofficelookingforajob,andheclaimedthathehad
fiveyearsofexperiencewith“Squeal.”Hedidn’tgetthejob.Don’tbethat
guy.
SQLisalanguageto
Createdatabasesandtheobjectswithinthem
Storedatainthosedatabases
Changeandanalyzethatdata
Getthatdatabackoutinreports,webpages,orvirtuallyanyother
useimaginable
TherearemanySQLstatements.Table1-5showssomeofthosethataremore
commonlyused.Foreachstatementshowninthistable,therearemanyclauses,
parameters,andotheradditionalfeaturesforeachone.Laterinthebook,you
willlookingreatdetailateachcommandthatiscoveredbytheexam.
TABLE1-5 SomeoftheMoreCommonlyUsedSQLStatements
AllSQLstatementsarecategorizedintooneofsixtypes.Table1-6showsthe
sixtypesofSQLstatementsinOracleSQL.Asyoucanseeinthetable,the
examignoresmanySQLstatements.Naturallyyouareconcernedonlywiththe
exam,sointhisbookyouwilllookatonlythreetypesofSQLstatements:Data
DefinitionLanguage,DataManipulationLanguage,andTransactionControl
Language.
TABLE1-6 SixTypesofSQLStatementsinOracleSQL
CERTIFICATIONOBJECTIVE1.04
DescribethePurposeofDDL
DataDefinitionLanguageconsistsofthoseSQLstatementsthatareusedto
builddatabaseobjects.Specifically,DDLstatementsareusedto
Create,alter,anddroptablesandotherdatabaseobjects
Addcommentsonaparticularobjecttobestoredinthedatabaseand
associatedwiththatobject
Issueprivilegestouserstoperformvarioustasksinthedatabase
Initiateperformanceanalysisonobjectsusingbuilt-intools
ThefollowinglistbrieflydescribesDDLstatementsthataretestedbythe
exam:
CREATEUsedtocreateauser,table,view,index,synonym,or
otherobjectinthedatabase.
ALTERUsedonanexistingobjectinthedatabasetomodifythat
object’sstructure,name,orsomeotherattribute.(Twoexceptionsarethe
usesofALTERwiththereservedwordsSESSIONandSYSTEM.
ALTERSESSIONandALTERSYSTEMarenottechnicallyconsidered
DDLstatementsbutfallunderadifferentcategory.Neitherisincludedon
thisexam.)
DROPUsedtoremoveadatabaseobjectfromthedatabasethathas
alreadybeencreatedwiththeCREATEstatement.
RENAMEChangesthenameofanexistingdatabaseobject.
TRUNCATERemovesalltherows—inotherwords,data—froman
existingtableinthedatabase.TRUNCATEissomethingofabrute-force
alternativetotheDELETEstatement,inthatTRUNCATEgivesup
recoveryoptionsofferedbyDELETEinexchangeforfaster
performance.ThesedifferencesinapproacharethereasonTRUNCATE
iscategorizedasDDLwhileDELETEisDML.
GRANTProvidesprivileges,orrights,touserobjectstoenable
themtoperformvarioustasksinthedatabase.
REVOKERemovesprivilegesthathavebeenissuedwiththe
GRANTstatement.
FLASHBACKRestoresanearlierversionofatableordatabase.
PURGEIrrevocablyremovesdatabaseobjectsfromtherecyclebin.
COMMENTAddscommentstothedatadictionaryforanexisting
databaseobject.
EachDDLstatementisrichwithoptionsandclauses.Iwillreviewand
provideexamplesofmostofthesestatementsasyouprogressthroughthebook.
SQLkeywords,suchasCREATE,arenotreally“commands”or“statements”
bythemselvesbutbecomecommandswhencombinedwithotherreserved
words,asinCREATETABLEorCREATESEQUENCE,whichare
commandsorstatements.Inpractice,CREATEcanbecalledastatementor
commandbyprofessionalsinthefield,andevenbyOracleCorporationin
variousformsofdocumentation.Technicallythereisadifference.However,
thisisn’tanissueontheexam.Similarly,thetermscommandandstatement
tendtobeusedinterchangeablybyOracle’sdocumentation.Ifyouconduct
somesearchesintheSQLLanguageReferenceManual,you’llfindplentyof
examplesofSQLstatementsbeingreferredtoascommands.Eitherisfine.
Andnoneoftheseissuesisaconcernontheexam.
CERTIFICATIONOBJECTIVE1.05
DescribethePurposeofDML
DMLreferstothosestatementsinSQLthatareusedtoworkwithdatainthe
objects.DMLstatementsareusedtoadd,modify,view,anddeletedataina
databaseobject,suchasatable.
ThefollowinglistbrieflydescribeseachDMLstatementthatistestedbythe
exam:
SELECTDisplaysdataofadatabasetableorview
INSERTAddsdatatoadatabasetable,eitherdirectlyor,insome
situations,throughaview
UPDATEModifiesexistingdatainatable,eitherdirectlyor,in
somesituations,throughaview
DELETERemovesexistingdatafromatable,eitherdirectlyor,in
somesituations,throughaview
MERGEPerformsacombinationofINSERT,UPDATE,and
DELETEstatementsinasinglestatement
TheSELECTstatementisratherinvolvedandwillgetseveralchapters’worth
ofreview.TheotherDMLstatementsarereviewedinthischapterandinvarious
sectionsthatfollow.
TransactionControlLanguage
InadditiontotheseDMLstatements,threemoreSQLstatementsareimportant
forworkingwithDML.ThesestatementsarenotpartofDMLbutinsteadare
categorizedasTCL.ThesestatementsarespecificallyidentifiedbyOracle
withinthecertificationobjectivesforDML,soI’lldiscusstheminthischapter.
Thesearethestatementsyouneedtostudy:
COMMITSavesasetofDMLmodificationsperformedinthe
currentdatabasesession
ROLLBACKUndoesasetofDMLmodificationsperformedduring
thecurrentdatabasesession
SAVEPOINTMarksapositioninasessiontoprepareforafuture
ROLLBACKtoenablethatROLLBACKtorestoredataataselected
pointinasessionotherthanthemostrecentcommitevent
InadditiontotheexplicitCOMMITcommand,anyDDLstatementwillcause
animpliedcommitactiontooccur.Inotherwords,ifyouissueanUPDATE
statementontableAandthenissueaGRANTstatementtouserBfor
accessingtableC,animpliedcommiteventwilloccur,andthedatayou
updatedtotableAwillbecommitted,eventhoughyouhaven’tissuedan
explicitCOMMIT.
CERTIFICATIONOBJECTIVE1.06
BuildaSELECTStatementtoRetrieveDatafroman
OracleDatabaseTable
Let’slookatasimpleexample.ConsidertheshipslistedearlierinTable1-2.A
validSQLcommandtocreateatableinwhichyoucouldstorethatinformation
mightlooklikethis:
Isay“might”looklikethisbecausethereareanumberofoptionsyoucould
includehere,includingprimaryorforeignkeydeclarations,datafiltering,
storageassignment,andotheroptionsthatgobeyondthissimpleexample.
You’lllookatmanyofthoseoptionslaterinthebook.Butthiscodesample
worksinanOracleSQLdatabase.
Next,here’saSQLcommandtoaddasamplerecordtothistable:
Again,thisisavalidcommand,albeitasimplifiedversion.Itinsertsone
recordofinformationaboutoneshipintothenewtableSHIPS.
Finally,let’screateaSQLcommandtodisplaythecontentsofthenewly
populatedSQLtable.
Ifallhasgonecorrectly,youshouldgetadisplaythatappearssomethinglike
thedisplayinFigure1-9.(Note:Figure1-9showstheoutputintheOracletool
SQLDeveloper.)
FIGURE1-9 OutputofthesampleSQLSELECTstatement
Asyoucansee,thedataisstoredinthetable,anditisstillthere.SELECT
merelydisplaysthedata;itdoesn’tchangethedataatall.Atitssimplestlevel,
thisiswhatSQLisallabout—writingstatementstocreatedatabaseobjectsand
thenworkingwiththoseobjectstostoreandretrievedata.
TheSELECTstatementisapowerfulSQLstatementthatcanbeusedto
querydatafromoneormoretablesinasinglestatement.AsingleSELECT
statementcanbeusedtotransformdata,aggregatedata,joinmultipletables,
filteroutunwanteddata,andmuchmore.Therestofthisbooklooksindetailat
avarietyofSQLstatementsastheypertaintothecertificationexam.
CERTIFICATIONSUMMARY
Thecertificationexamisatimed,multiple-choiceexamthatwilltestyouusing
entity-relationshipdiagrams,codeexamples,andmore.Itwillchallengeyou
withquestionspertainingtothecorrectuseofsyntax,thelogicalresultsofSQL
statements,andtheuseofvariousfunctionsandothercapabilitiesofSQL.This
bookistheidealtoolforexampreparation.Youshouldalsohaveaccesstoa
functionalinstallationofOraclesoftwarethatyoucanobtainfromOracle’sweb
site.
Theactofmodelingareal-worldbusinesssystemoftenincludesthecreation
ofadatamodel,whichisdepictedinanentity-relationshipdiagram.When
buildingarelationaldatabase,entitiesaretransformedintotables,andanentity’s
attributesareimplementedasthetable’scolumns.Agivenentity’srowsare
uniquelyidentifiedusingaprimarykey,andforeignkeyscanbeusedto
establisharelationshipbetweenonetableandanother.Databasenormalizationis
thepracticeofdesigningyourdatamodeltoserveyourbusinessapplicationat
anoptimallevel.Thethirdnormalformindicatesyourdatamodelisfreeof
duplicatedata,usesprimarykeystouniquelyidentifyasetofattributes,andhas
fullytransformedanymany-to-manyrelationshipsintoone-to-many
combinations.
SQListhemostwidelyusedlanguageforinteractingwithrelational
databases.Thelanguagecanbeusedtocreateandinteractwithdatabases.SQL
statementscanbeissuedfromwithinotherapplicationsandincorporatedwith
variouslanguages.
DDLstatementsarethoseSQLstatementsusedtocreatedatabaseobjects.
DMLstatementsareSQLstatementsusedtoworkwithexistingdatabase
objects.ThereareadditionalcategoriesofSQLstatements,includingTCL.
ASELECTstatementisthemostcommonlyusedSQLstatementandcanbe
usedtoquerydatafromoneormoretables,andsimultaneouslyitcantransform
andevenaggregatedatathatitreturns.
✓TWO-MINUTEDRILL
TheExam:AnOverview
Thischapterprovides
introductorymaterialthatisimportanttounderstandinpreparingforthe
exam.
The1Z0-071exam,OracleDatabaseSQLCertifiedAssociate,
whichisthesubjectofthisexamguide,has14certificationobjective
categories.Itshares11objectiveswithanotherexam,1Z0-051,SQL
FundamentalsI.But1Z0-071goesintomoredetailinthoseobjectives
andaddsthreemore.Also,1Z0-071tendstoemphasizetheobjectives
andsubobjectivesnotaddressedon1Z0-051.
Theexamincludes73questionsandallows100minutesto
completethem.Thatisanaverageofabout82secondsperquestion.
Thisbookwillprepareyoutostudyandsuccessfullytakeandpass
theexam.
Oracle’sSQLLanguageReferenceManualisoverkillasanexam
studyguide,asitcontainsfarmorethanyou’llneedfortheexam.Butit
isagoodreferencecompaniontothisbook.
IdentifytheConnectionBetweenanERDandaRelational
Database
TheERDisalogicalmodelofanexistingbusiness.
TheentitiesinanERDarethe“things”thatformthebasisofa
businessinformationsystemandthataretransformedintotablesina
database.
TheERDisalogicalrepresentationofabusiness;therelational
databaseisthephysicalmodelinwhichactualdatacanbehousedand
processedinsupportofthebusinessprocess.
ExplaintheRelationshipBetweenaDatabaseandSQL
Adatabaseisapersistentstoreofinformationthatcontinues—or
persists—beyondtheexecutionofagivenapplication.
SQListhemostwidelyusedlanguageforinteractingwitha
database.
SQLstatementscanbeissuedbyanyoneormoreapplicationstoa
singledatabase.Thoseapplicationscanbewritteninavarietyof
languagesthatsupportSQLcalls,includingsoftwarewrittenin
languagessuchasJava,PHP,andothers.
DescribethePurposeofDDL
DDLstatementsincludeCREATE,ALTER,andDROP.
DDLstatementsareasubsetofSQLandareusedtocreatenew
databaseobjectsoralterthestructureofexistingdatabaseobjects,
includingremovingthem.
DescribethePurposeofDML
DMLstatementsincludeSELECT,UPDATE,andINSERT.
DMLstatementsareasubsetofSQLandareusedtoworkwith
existingdatabaseobjects.
BuildaSELECTStatementtoRetrieveDatafromanOracle
DatabaseTable
TheSELECTstatementisthemostcommonlyusedSQLstatement.
SELECTcanbeusedtoquerydatafromasingletableorjoindata
togetherintwoormoretablestoreturndatathatislogicallyconnected.
SELECTcanbeusedwithfunctionsandothercapabilitiesto
transformdatainvariousways,whichisdiscussedatlengthlaterinthis
book.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Thefirstfivequestionstestyouonthe
backgroundinformationIdiscussedearliertoprepareyoufortheexam.The
remainingquestionsbegintotestyouonthespecificobjectivesoftheexam
itself.Furthermore,thesequestionsarewritteninthestyleandformatofthe
certificationexam,sotheycanbegoodpracticetohelpyougetgoing.Asisthe
casewiththeexam,someoftheseselftestquestionsmayhavemorethanone
correctanswer,soreadcarefully.Chooseallthecorrectanswersforeach
question.
TheExam:AnOverview
1.WhichofthefollowingtopicsarenotincludedintheSQL
FundamentalsIexambutareaddressedontheSQLAssociateexam?
(Chooseallthatapply.)
A.MERGE
B.Conversionfunctions
C.FLASHBACK
D.Externaltables
2.Ifyoufocusontryingtoachievetheminimumpassinggrade
requirementfortheexam,youcanstudymoreefficiently.
A.True
B.False
3.Theexamistimed.
A.True
B.False
4.The1Z0-071exam(whichisthesubjectofthisbook)hasbeen
officiallyvalidatedbyOracleCorporationagainstwhichofthefollowing
versionsoftheOracledatabase?(Chooseallthatapply.)
A.Everyversion
B.9i
C.11g
D.12c
5.Thebestexamguideyoucouldpossiblygetforpreparingtotakeand
passthe1Z0-071certificationexam,SQLAssociate,iswhichofthe
following?(Chooseallthatapply.)
A.Thisbook.
B.Thebookyouareholdingrightnow.
C.Thisherebook.
D.Don’tmakemetellyouagain.
IdentifytheConnectionBetweenanERDandaRelational
Database
6.WhentransforminganERDintoarelationaldatabase,youoftenuse
anentitytobuildadatabase’s:
A.Table
B.Column
C.Attribute
D.Relationship
7.Theuniqueidentifierofarowinadatabasetableisa(n):
A.ID
B.Primarykey
C.Primarycolumn
D.Column
ExplaintheRelationshipBetweenaDatabaseandSQL
8.WhichofthefollowingistrueofSQL?
A.Itisthemostcommonlyusedlanguageforinteractingwitha
database.
B.Itistheonlylanguageyoucanusetocreateadatabase.
C.Itistheonlylanguageyoucanusetointeractwithadatabase.
D.Noneoftheabove
9.WhatcanyouusetosubmitSQLstatementsforexecution?(Choose
allthatapply.)
A.PHP
B.Java
C.SQLDeveloper
D.SQL*Plus
DescribethePurposeofDDL
10.WhatisoneofthepurposesofDDL?(Choosethebestanswer.)
A.Querydatafromagiventable
B.Issueprivilegestousers
C.Removeexistingdatafromadatabasetable
D.Noneoftheabove
11.WhatcanDDLbeusedfor?(Choosethree.)
A.Addcommentstoadatabasetable
B.Addcolumnstoadatabasetable
C.Adddatatoadatabasetable
D.Addprivilegesforausertoadatabasetable
DescribethePurposeofDML
12.WhichoneofthefollowingisaDMLstatement?
A.ADD
B.ALTER
C.UPDATE
D.MODIFY
13.Whichofthefollowingcanbeusedtoremovedatafromatable?(Choose
two.)
A.DELETE
B.UPDATE
C.MODIFY
D.ALTER
BuildaSELECTStatementtoRetrieveDatafromanOracle
DatabaseTable
14.WhatcanaSELECTstatementbeusedtoquery?(Choosethebestanswer.)
A.Onlyonereport
B.Onlyonetable
C.Oneormorereports
D.Oneormoretables
15.WhichofthefollowingisnotacapabilityoftheSELECTstatement?
A.Itcantransformquerieddataanddisplaytheresults.
B.Itcanremovedatafromatable.
C.Itcanjoindatafrommultipletables.
D.Itcanaggregatedatabasedata.
SELFTESTANSWERS
TheExam:AnOverview
1. A,B,C,andD.SeeTable1-1forafulllistingofallthetopics
includedinbothoftheexams.
Alloftheanswersarecorrect.
2. B.Granted,itisasubjectiveissue,butOracleCorporation
specificallywarnsagainstthis.Onereasonisthatthepublishedminimum
requirementforapassingscorecanbechangedwithoutnotice.
Aisincorrect.Thestatementisfalse.
3. A.Yes,theexamistimed.
Bisincorrect.Theexamistimed,anditisimperativethatyoumanage
yourtimewellwhenyoutaketheexam.
4. CandD.Thetesthasbeenofficiallyvalidatedagainstthesetwo
versionsofthedatabaseandnottheothers.
AandBareincorrect.Theexamtestsforfunctionalitythatdidnotexist
inearlierversionsoftheOracledatabase.
5. A,B,C,andD.Duh.
Alloftheanswersarecorrect.
IdentifytheConnectionBetweenanERDandaRelational
Database
6. A.Thetableisaphysicalimplementationofanentity.
B,C,andDareincorrect.Acolumnisaphysicalimplementationofan
entity’sattribute.Arelationshipspecifieshowtwoentitiesrelatetoeach
other.
7. B.Theprimarykeyistheuniqueidentifierinatable.
A,C,andD.ThereisnoparticularunderstandinginERDsofrelational
databasesofanIDoraprimarycolumn.Bothmightbeusedtonamea
particularcolumnorotherobjectinthedatabase,buttheycarryno
particularspecificmeaning.Acolumnisanattributeofanentityina
relationaldatabase.
ExplaintheRelationshipBetweenaDatabaseandSQL
8. A.SQListhecommonlyusedlanguageforinteractingwith
databases.
B,C,andDareincorrect.SQLisnottheonlylanguageforcreatingor
interactingwithdatabases,butitisthemostcommonlyused.
9. A,B,C,andD.YoucanissueSQLstatementsfromanyofthelisted
options.
Alloftheanswersarecorrect.
DescribethePurposeofDDL
10. B.TheGRANTstatementispartofDDLandisusedtoissueprivilegesto
auser.
A,C,andDareincorrect.QueryingdataisperformedusingtheDML
statementSELECT.UsetheDMLstatementsUPDATEorDELETEto
removedatafromadatabasetable.UPDATEcanbeusedtoremovedata
fromoneormorecolumnsinagivenrow,andDELETEcanbeusedto
removeanentirerow.“Noneoftheabove”doesnotapplysinceoptionBis
correct.
11. A,B,andC.TheDDLstatementALTERcanbeusedtoaddcolumnsor
commentstoatable.UsetheDDLstatementGRANTtoaddprivileges.
Cisincorrect.ThereisnoDDLstatementtoremovedatafroma
databasetable.Forthis,useeitherUPDATEorDELETE.UPDATEcanbe
usedtoremovedatafromoneormorecolumnsinagivenrow,and
DELETEcanbeusedtoremoveanentirerow.
DescribethePurposeofDML
12. C.UPDATEisusedtochangedatainanexistingrow.
A,B,andDareincorrect.ThereisnoADDorMODIFYstatementin
SQL.ALTERisaDDLstatement.
13. AandB.TheDELETEstatementisusedtoremoveoneormorerows
fromagiventable.UPDATEisusedtochangedatainoneormoreexisting
rowsinagiventable,andthechangemayincludetheremovalofavaluein
acolumn,includingtheassignmentofNULLtoagiventable’scolumn
valueforthecandidateroworrows.
CandDareincorrect.ThereisnoMODIFYstatementinSQL.ALTER
isaDDLstatement.
BuildaSELECTStatementtoRetrieveDatafromanOracle
DatabaseTable
14. D.TheSELECTstatementcanbeusedtoqueryoneormoretables.
A,B,andCareincorrect.TheSELECTstatementdoesnotquery
reports;rather,itisusedtocreatereports.TheSELECTisnotlimitedto
queryingasingletable.
15. B.TheSELECTstatementisnotusedtoremovedatafromatable.Theact
ofqueryingmerelycopiesdataoutofatableforreportingandother
comparablepurposes,buttheSELECTstatement—asastand-alone
statement—alwaysleavesthedataitencountersuntouchedand
unmodified.However,itispossibletoincorporatefeaturesoftheSELECT
withinthecontextofotherstatements,suchasINSERTandUPDATE,
whicharedescribedlaterinthisbook.
A,C,andDareincorrect.TheSELECTstatementiscapableof
transformingdata,joiningdata,andaggregatingdata.
2
UsingDDLStatementstoCreateandManage
Tables
T
CERTIFICATIONOBJECTIVES
2.01CategorizetheMainDatabaseObjects
2.02CreateaSimpleTable
2.03ReviewtheTableStructure
2.04ListtheDataTypesThatAreAvailableforColumns
2.05ExplainHowConstraintsAreCreatedattheTimeofTableCreation
2.06DropColumnsandSetColumnsUNUSED
2.07CreateandUseExternalTables
✓Two-MinuteDrill
Q&ASelfTest
hischapterbeginstoexaminetables.Tablesaredatabaseobjectsthat
programmerscreatetostorethedatathatpopulatesthedatabase.
CERTIFICATIONOBJECTIVE2.01
CategorizetheMainDatabaseObjects
Databaseobjectsarethefoundationofanydatabaseapplication.Database
objectshouseandsupporteverythinganydatabaseapplicationneedsinorderto
formaworkingapplication.Thissectiontakesahigh-levellookatthedatabase
objectsthatcanbecreatedinanOraclerelationaldatabasemanagementsystem
(RDBMS),focusingonthoseobjectsthataretestedontheexam.Herewewill
separatedatabaseobjectsintocategoriesanddiscusstherelationshipbetween
objectsandschemas.Therestofthebookwilldelveintogreaterdetailoneach
databaseobjectthatisincludedintheexam.
WhatAreDatabaseObjects?
YoucancreatemanydifferenttypesofdatabaseobjectsintheOracleRDBMS.
Theexamlooksateightofthoseobjectsingreatdetail.
TheCompleteList
Adatabaseconsistsofoneormoredatabaseobjects.Thefollowinglistshows
objectsthatadatabasedevelopercancreateintheOracle12cRDBMS.Those
markedwithanasterisk(*)areincludedontheexam.(Source:SQLLanguage
ReferenceManual.)
Clusters Objecttables
Constraints* Objecttypes
Contexts Objectviews
Databaselinks Operators
Databasetriggers Packages
Dimensions Restorepoints
Directories Roles*
Editions Rollbacksegments
Externalprocedure
libraries Sequences*
Indexes* Stored
functions/procedures
Index-organizedtables Privatesynonyms*
Indextypes Publicsynonyms*
Javaclasses,etc. Tables*
Materializedviewlogs Tablespaces
Materializedviews Users*
Miningmodels Views*
Note:Nonschemaobjectsareitalicized;allothersareschemaobjects.Seethe
section“Schemas”formoreinformation.
Theexamdoesn’ttestforalloftheseobjects.Itignoresobjectssuchas
PL/SQLprogramunitsandJavaprogramunits,aswellasobjectsthatareof
moreinteresttodatabaseadministrators.Wewillconcernourselvesinthisbook
onlywiththosedatabaseobjectsthatareincludedintheexam.Thetypesof
databaseobjectsontheexamarelistedhere,inalphabeticalorder:
Constraints Synonyms
Indexes Tables
Roles Users
Sequences Views
ABriefDescription
Let’stakeabrieflookatthetypesofobjectsthatarethesubjectoftheexam:
TABLEAstructurethatcanstoredata.Alldataisstoredincolumns
androws.Eachcolumn’sdatatypeisexplicitlydefined.
INDEXAnobjectdesignedtosupportfastersearchesinatable.An
INDEXperformsmuchthesamewayasanindextoabook,bycopying
arelativelysmall,selectamountofinformation,sortingitforspeedy
reference,andtyingitbacktolocationsinthetableforsupportingquick
lookupsofrowsinthesourcetable.
VIEWA“filter”throughwhichyoucansearchatableandinteract
withatablebutthatstoresnodataitselfandsimplyservesasa“window”
ontooneormoretables.VIEWobjectscanbeusedtomaskportionsof
theunderlyingtablelogicforvariousreasons—perhapstosimplify
businesslogicortoaddalayerofsecuritybyhidingtherealsourceof
information.AVIEWcanbeusedtodisplaycertainpartsofatablewhile
hidingotherpartsofthesametable.
SEQUENCEAcounter,oftenusedtogenerateuniquenumbersas
identifiersfornewrowsastheyareaddedtoatable.
SYNONYMAnaliasforanotherobjectinthedatabase,oftenused
tospecifyanalternativenameforatableorview.
CONSTRAINTAsmallbitoflogicdefinedbyyoutoinstructa
particulartableabouthowitwillaccept,modify,orrejectincomingdata.
USERSThe“owners”ofdatabaseobjects.
ROLESAsetofoneormoreprivilegesthatcanbegrantedtoa
user.
Iwillrevieweachoftheseobjectsingreaterdetailthroughoutthebook.
Eachdatabaseobjectisconsideredtobeeithera“schemaobject”ora
“nonschemaobject.”Thisbegsthequestion,whatisaschema?
Schemas
Thissectiondescribesschemas—whattheyareandhowtheyrelatetodatabase
objects.
WhatIsaSchema?
Aschemaisacollectionofcertaindatabaseobjects,suchastables,indexes,and
views,allofwhichareownedbyauseraccount.Youcanthinkofaschemaas
beingthesamethingasauseraccount,butthereisaslightdifference—theuser
accounthousestheobjectsownedbyauser,andtheschemaisthatsetofobjects
housedtherein.Onedefinitionofschemathatyou’lloftenfindinOracle’s
documentation(andelsewhere)isthataschemaisa“logicalcollectionof
databaseobjects.”Technicallythat’strue,butitdependsonhowlogicaltheuser
choosestobewhenbuildingandplacingthoseobjectswithinhisorheruser
account.Ideallythereshouldbesomesensetowhyallthoseobjectsareinthere,
andideallya“schema”shouldn’tbejustarandomcollectionofobjects.
However,thereisnothingbuiltintotheOracleorSQLsystemsthatpreventsa
userfromdoingjustthat—randomlycollectingobjectsintoauseraccountand
thuscreatinga“schema”ofrandomobjects.Ideally,though,auseraccount
shouldbeseenandusedasalogicalcollectionofdatabaseobjects,drivenby
businessrulesandcollectedintooneorganizedentity—theschema.
Aschemahasthesamenameastheuseraccount.Auseraccountisidentified
byausernameandisassociatedwithasetofprivilegesandroles,whichare
coveredinChapter14,aswellasotherattributesnotaddressedontheexam.A
useraccount“owns”asetofzeroormoredatabaseobjects,andtogether,these
objectsconstituteaschema.Whileuseraccountsareoftenassociatedwitha
humanbeing,itisentirelypossibletocreateaschema(inotherwords,auser
account)whose“owner”isn’tahumanbeingatallbutperhapsisanapplication
process,someothersortofvirtualentity(perhapsaparticularbackground
process),orwhatevermakessensetosuitthebusinessrulesthatareinforce.So
inotherwords,oneuserwilloftenhaveoneuseraccountandthereforeone
schema.Buttheoppositeisn’tnecessarilytrue.Therecanbemoreuseraccounts
thanthereareactualusers.
Nowthatyouunderstandwhataschemaisandwhatauseraccountis,wecan
begintolookatdifferenttypesofdatabaseobjects,someofwhichareownedby
auserandarethereby“schema”objectsandsomeofwhicharenotschema
objectsbutarestilldatabaseobjectsnonetheless.
SchemaandNonschemaObjects
Alldatabaseobjectsfallintooneoftwocategories,ortypes.Thesetypes,asthe
Oracledocumentationcallsthem,areschemaandnonschema.
Table2-1showsthelistofbothschemaandnonschemaobjectsthatare
subjectsoftheexam.
TABLE2-1 Schemavs.NonschemaDatabaseObjects
Schemaobjectsarethoseobjectsthatcanbeownedbyauseraccount.
Nonschemaobjectscannotbeownedbyauseraccount.
Forexample,theUSERobjectisanonschemaobject.Auseraccountcannot
ownitself,anditcannotbeownedbyanotheruseraccount.Therefore,theUSER
object,whichisauseraccount,isanonschemaobjectandisapropertyofthe
databaseasawhole.ThesameistrueforROLEobjects.ROLEobjectsrepresent
oneormoreprivilegesthatcanbegrantedtooneormoreUSERobjects.Thus,a
ROLEinherentlyexistsataleveloutsideofanindividualUSERaccount—and
isthereforeanonschemaobject.APRIVATESYNONYMisownedbyauser
accountandisthereforeaschemaobject,butaPUBLICSYNONYMisa
variationontheSYNONYMobjectthatisownedbythespecialuseraccount
PUBLIC,whoseownedobjectsareautomaticallyavailabletotheentiredatabase
bydefinition.
AllotherobjectsareschemaobjectssuchasTABLE,INDEX,VIEW,andthe
otherslistedinTable2-1.
CERTIFICATIONOBJECTIVE2.02
CreateaSimpleTable
Theexamexpectsyoutobeabletorecognizethecorrectcodetocreateasimple
table.By“simple,”Oraclemeansthatyou’llberequiredtodefinethetable’s
name,columnnames,datatypes,andanyrelevantconstraints.
Tocreateatable,weusetheSQLcommandCREATETABLE.Theword
CREATEisaSQLreservedwordthatcanbecombinedwithjustaboutany
databaseobject(butnotall)toformaSQLcommand.Thesyntaxforthe
CREATEobjectTypestatementisshowninthiscodelisting:
where
objectTypeisareferencetoanobjectlistedinTable2-1.Hereare
someexceptions:
YoucannotcreateaCONSTRAINTinthisway.Also,whileCREATE
PRIVATESYNONYMobjectNameiscorrect,youusesimplyCREATE
SYNONYMobjectNameforpublicsynonyms,neverCREATEPUBLIC
SYNONYMobjectName,whichisincorrect.
objectNameisanameyouspecifyaccordingtothenamingrulesand
guidelinesdescribedlaterinthischapter.
attributesisanywherefromzerotoaseriesofclausesthatare
uniquetoeachindividualobjectType,whichwe’llreviewlater.
OneofthemostfrequentusagesoftheSQLcommandCREATEistocreatea
TABLE.Whenyoucreateatable,you’llalsocreatethetable’scolumnsand
optionallysomeassociatedobjects.
Let’slookatanexampleofabasicCREATETABLEstatement:
Ifyouweretoexecutethiscommandinaschemathatdidn’talreadyhaveatable
namedwork_schedule(that’simportant),thenyou’dgettheresultshownin
Figure2-1.
FIGURE2-1 ResultsofCREATETABLEwork_schedulestatement
Let’sanalyzethesyntaxoftheprecedingexampleofaCREATETABLE
statement:
ThereservedwordCREATE.
ThereservedwordTABLE.
Thenameofthetable,chosenbyyou,inaccordancewiththerules
ofnamingobjects,whichwereviewnext.
Apairofparentheses,inwhichareaseriesofcolumndeclarations,
eachseparatedbyacomma.Columndeclarationsconsistofthe
following:
Thenameofthecolumn,chosenbyyou,inaccordancewiththe
rulesofnamingobjects
Thedatatypeofthecolumn,takenfromthelistofavailabledata
types
Acommatoseparateeachcolumndefinitionfromthenext.
Asemicolontoendthestatement,asisthecasewithallSQL
statements.
Tofullyunderstandthesyntaxasjustdescribed,youneedtoexaminetwo
importantissues:therulesofnamingdatabaseobjectsandthelistofavailable
datatypes.Let’slookatnamingrulesnext;afterthatyou’lllearnaboutdata
types.
NamingaTableorOtherObject
Beforemovingonwiththedetailsofcreatingatable,let’stakealookatthe
rulesfornamingdatabaseobjects.Theserulesapplytotables,views,indexes,
andalldatabaseobjects—includingatable’sconstraints,ifanyarecreated.The
samenamingrulesalsoapplytoatable’scolumns.
Alltableshaveaname.Eachtableconsistsofoneormorecolumns,andeach
columnhasaname.(Forthatmatter,eachdatabaseobjectinthedatabasehasits
ownname—eachindex,view,constraint,synonym,andobjectinthedatabase
hasaname.)
WhenyouusetheSQLkeywordCREATEtocreateadatabaseobject,you
mustcomeupwithanameandassignittotheobject,andsometimes—asinthe
caseofatable—toindividualcomponentswithintheobject,suchasthecolumns
ofatable.
Thereisaspecificsetofrulesfornamingdatabaseobjects—includingtables,
tablecolumns,views—anythingyoumustnameinthedatabase.Thenext
sectionlooksatthosenamingrules.
NamingRules—Basics
Therulesfornamingtables,andanydatabaseobject,includethefollowing:
Thelengthofthenamemustbeatleast1characterandnomorethan
30characters.
Thefirstcharacterinanamemustbealetter.
Afterthefirstletter,namesmayincludeletters,numbers,thedollar
sign($),theunderscore(_),andthepoundsign(#),alsoknownasthe
hashmarkorhashsymbol.Nootherspecialcharactersareallowed
anywhereinthename.
Namesarenotcase-sensitive.
NamescannotbereservedwordsthataresetasideforuseinSQL
statements,suchasthereservedwordsSELECT,CREATE,andsoon.
SeethefollowingcompletelistofreservedwordsfromOracle’sSQL
LanguageReferenceManual.Thesewordsareoff-limitswhenyoucreate
namesforyourdatabaseobjects.
Theserulesareabsolute.Ifyouattempttocreateatableoranyotherdatabase
objectwithanamethatviolatestheserules,theattemptwillfail,you’llreceive
anerrorcodefromthedatabase,andyourobjectwillnotexist.
QuotedNames
WhilenotrecommendedbyOracle,itispossibletocreatedatabaseobjectnames
thatare“quoted.”Aquotednameissurroundedwithdoublequotes,suchasthe
"Companies"object.Here’sanexample:
Quotednamesmustalwaysbereferencedwiththeirquotationmarks.
Quotednamesvaryfromnonquotedinseveralways.Forexample,quoted
namesmaybeginwithanycharacter.Namesmayincludespaces.
Quotednamesarecase-sensitive.Forexample,nowthatI’vecreatedatable
called"CompanyEmployees",thisquerywillwork:
Butthefollowingwillnot:
Quotednamesmayincludereservedwords.Andtoreiterate,quotednames
mustalwaysbereferencedwiththeirquotationmarks.
Generally,mostdatabaseobjectsarecreatedwithouttheuseofdouble
quotationmarks,andOracleadvisesagainsttheiruse.Butyoumayneedto
knowaboutthemanyway.
UniqueNamesandNamespaces
Whathappensifyoutrytocreateadatabaseobjectwithanamethatmatchesthe
nameofanotherdatabaseobjectthat’salreadyinthedatabase?Canyoudoit?
Whathappenstotheexistingdatabaseobject?Willyoubeabletousethe
resultingdatabaseobject?Theansweristhatitdependsonyourobject’s
relationshiptotheotherobjectthatalreadyexists,aswellasonsomethingcalled
thenamespace.
Anamespaceisalogicalboundarywithinthedatabasethatencompassesa
particularsetofdatabaseobjects.Thereareseveralnamespacesatworkatany
giventime,dependingonthecontextinwhichyouareworking.
Understandingthenamespaceisnecessaryinordertounderstandwhether
youmayormaynotspecifyduplicatenamesforanyparticulardatabaseobject.
SeeFigure2-2foradiagramthatdemonstratesthenamespaceboundaries.Note
thateachsquareenclosesadifferentnamespace.InFigure2-2,thereareseveral
namespacesidentified:
FIGURE2-2 Diagramofnamespaceboundaries
USERandROLEobjectsareintheirowncollectivenamespace.
PUBLICSYNONYMobjectsareintheirownnamespace.
TABLE,VIEW,SEQUENCE,PRIVATESYNONYM,anduser-
definedTYPEobjectshavetheirowncollectiveuniquenamespace
withinagivenschema.(NotethatIhaven’tpreviouslymentioneduser-
definedtypes.Theyaren’tontheexam.Iincludetheminthisdiscussion
tobecomplete,butyouwon’tneedtounderstandthemfortheexam.)
INDEXobjectshavetheirownnamespacewithinagivenschema.
CONSTRAINTobjectshavetheirownnamespacewithinagiven
schema.
Whatallofthismeansisthatyoumustprovideuniquenamesforanobject
withinitsownnamespace.Objectsthatshareanamespacemusthaveunique
nameswithinthatnamespace.Objectsindifferentnamespacesareallowedto
haveidenticalnames.Herearesomeexamples:
IfyoucreateatableinoneschemacalledWORK_SCHEDULE,
thenyoucannotcreateanothertablecalledWORK_SCHEDULEwithin
thatsameschema.Butyoucandoitinanotherschema,providedthere
isn’talreadyaWORK_SCHEDULEinthatschema.
Let’ssayyouhaveaschemacalledHR(asinHumanResources).In
theHRschema,youcancreateatablecalled,say,PAYROLL.You
cannotcreateaVIEWinthatsameschemacalledPAYROLL.Butyou
cancreateanINDEXcalledPAYROLL.Youcanalsocreatea
CONSTRAINTcalledPAYROLL.ButyoucannotcreateaSEQUENCE
calledPAYROLL.
Intheentiredatabase,eachUSERobjectmusthaveauniquename
andsomusteachROLEobject.
Notethatlateryou’llseeyoucancreateaTABLEandgiveitaprimarykey
CONSTRAINT.Ifyoudothis,you’llhavetheoptionofnamingthat
CONSTRAINT.Ifyoudo,thesystemwillautomaticallycreateanINDEXfor
theCONSTRAINT,anditwillnametheINDEXwiththesamenameasthe
CONSTRAINT.Youcanoverridethisandassignyourownnamewiththe
USINGINDEXclauseoftheCREATETABLEstatement,somethingyou’ll
learnaboutlater.
Whennamingobjects,choosedescriptivenamesthatcanbepronounced.Be
consistent:ifyourtablesofEMPLOYEES,CUSTOMERS,andVENDORS
eachincludeareferencetoaperson’sname,makethosecolumnnamesallthe
same—NAME,LAST_NAME,andFIRST_NAME,whatever.Justbe
consistent.Considernamingalltablesinpluralform,sinceeachmostlikely
containsmultiplerecords.Considerusingastandardprefixforeverydatabase
objectthat’sassociatedwithaparticularapplication.Forexample,fora
HumanResourcesapplication,prefixeachtablewithHR_,butavoidusing
prefixesthatOracleCorporationusesforitssystem-definedobjects:SYS_,
ALL_,DBA_,GV$,NLS_,ROLE_,USER_,andV$.
System-AssignedNames
You’llseeabitlaterthatyoumaycreateanobjectindirectly.Thishappens,for
example,whenyoucreateatableandwithintheCREATETABLEstatement
youoptionallydefineanassociatedconstraint,butwithoutprovidinganamefor
theCONSTRAINT.ThelanguagesyntaxoftheCREATETABLEstatement
allowsthistohappen,asyou’llsoonsee,andtheresultisnotonlyyournewly
created—andnamed—table,butalsoanewlycreatedconstraintforthattable.
Somedevelopersrefertotheseconstraintsasanonymous,buttheyaren’t
anonymousatall.Thesystemwillautomaticallygenerateanameforthat
constraint—anamelikeSYS_C001234,withaprefixofSYS_C,followedbya
numbergeneratedautomaticallybythesystem.
TheSQLStatementCREATETABLE
TheSQLstatementCREATETABLEisacomplexstatementwithmanyclauses
andparameters.Theexamtestsforonlysomeofitsfunctionality,includinghow
tocreatecolumns,specifydatatypesforthosecolumns,andcreateconstraints.
Here’sanexampleofarelativelysimpleCREATETABLEstatement:
Inthisexample,youarecreatingatablewithsevencolumnsandtwoconstraints.
Eachofthecolumnsisgivenanameandadatatype.Thedatatypesprovide
somerulesandrequirementsforthedatathat’senteredintothecolumns.For
example,onlynumberscanbeenteredintoCRUISE_TYPE_ID.Onlydate
valuescanbeenteredintoSTART_DATE.
NotethattheSTATUScolumnhasadefaultvalueof'DOCK'.IfanINSERT
statementomitsthevalueforSTATUS,then'DOCK'willbethevaluefor
STATUS.
AttheendoftheCREATETABLEstatementisanadditionallinethatcreates
aCONSTRAINT.ThisparticularCONSTRAINTdefinestheCRUISE_ID
columnasaprimarykey,whichmeansthatanyrowaddedtotheCRUISES
tablemustincludeavalueforCRUISE_ID,andthatvaluemustbeunique—it
cannotduplicateanypreexistingvalueforCRUISE_IDinanyotherrowalready
presentinthetable.
There’salsoaNOTNULLconstraintthat’sappliedtotheCAPTAIN_ID
column.ThatCONSTRAINTisn’texplicitlynamed,butit’saCONSTRAINT
nonetheless,anditwillbeassignedasystem-generatedname.
Intheremainderofthischapter,you’lllearnhowtoreviewthestructureofa
table.You’lllookatthedifferentdatatypesyoucanusetocreatecolumnsina
table.Thechapterwillconcludebylookingatconstraintsandhowtheycanbe
createdatthetimeyoucreateatable.
CERTIFICATIONOBJECTIVE2.03
ReviewtheTableStructure
Onceyouhavecreatedatablesuccessfullyinthedatabase,youcanreviewthe
table’sstructurewiththeDESCRIBEstatement.TheDESCRIBEstatement,
oftenabbreviatedasDESC,isn’taSQLstatement;it’saSQL*Plusstatement
thatisuniquetoOracle.(Someotherproductvendorshavesinceimplemented
DESCintheirownSQLproducts.)TheDESCstatementisn’taSQLstatement
—itisnotdescribedintheOracleDatabaseSQLLanguageReferencemanual.
DESCfallsunderthecategoryofoneoftheseveralSQL*Plusenhancements,
uniquetoOracle,anddocumentedinOracle’sSQL*PlusUser’sGuideand
Referencemanual,whichdetailstheDESCstatement.Buteventhoughitisnot
consideredSQL,DESCisimportanttounderstandsinceDESCisusefulfor
quicklyreviewingatable’sstructure.
OnenoteaboutSQL*Plusstatements:theydon’trequireasemicolonatthe
end.You’llseeDESCstatementswithoutasemicolonintheexamplesthat
follow.NotethataSQL*Plusstatementconcludesattheendofitsfirstline
unlessacontinuationcharacterisplacedattheendofthelinetoexplicitly
indicatethatthestatementcontinuestothenextline.Thisisasignificant
differencefromSQLstatements,whichrequireasemicolonattheirend,and
continuetomultiplelinesuntilthesemicolonisencountered.TheSQL*Plususe
ofthecontinuationcharacterandthefullsyntaxofSQL*Plusstatementsare
beyondthescopeofthisbook.TheonlypointtonotehereisthatSQL
statementscontinueuntilasemicolonmarkstheend,spanningmultiplelinesif
required.ButaSQL*Plusstatementdoesnotbehavethatwayandendsonits
firstline,withorwithoutasemicolon,unlessacontinuationcharacterisused,
andwewon’tseetheneedforthatinourexamplesthatfollow—we’lljustsee
theDESCstatementendwithoutasemicolon.Alsonote:youcanactuallyplace
asemicolonattheendofaSQL*Plusstatementand—technically—itwillhave
noeffect.Youwon’tgetanerrormessage,norisitrequired.Butdon’tforget:a
semicolonisalwaysrequiredattheendofaSQLstatement.
Let’stakealookatanexampleofDESC.ConsidertheCREATETABLE
CRUISESstatementyousawearlier:
AssumingthisSQLstatementwasexecutedinthedatabasesuccessfully,
resultinginthetableCRUISESbeingstoredinthedatabase,thenyoucould
issuethefollowingSQL*Pluscommand:
DESCcruises
Figure2-3displaystheresult.Noticetheoutputlistshowsathree-column
display.
FIGURE2-3 ResultofthecommandDESCcruises
Thefirstcolumnintheoutputlistingistitled“Name”andshowsthe
table’scolumnnamesthatyouspecifiedwiththeCREATETABLE
statement.
Thesecondcolumnintheoutputlistingistitled“Null”andshows
whetherthereisaNOTNULLconstraintappliedtothatparticular
columninthetable.Inotherwords,willanyrowthat’saddedtothe
databasebeallowedtoomitthisparticularvalue?
Thethirdcolumnintheoutputlistingistitled“Type”andshowsthe
datatypefortheparticulartable’scolumninquestion.
Forexample,theDESCCRUISESoutputshowsthattheCRUISEStablehas
acolumntitledCAPTAIN_ID,itsdatatypeisNUMBER,andithasaNOT
NULLCONSTRAINTappliedtoit.
CERTIFICATIONOBJECTIVE2.04
ListtheDataTypesThatAreAvailableforColumns
ThissectionlistsandexplainsdatatypesprovidedbyOraclethatcanbe
assignedtocolumnsinatable.We’lllookatexamplesinlaterchapters—for
nowwe’reinterestedonlyinlistinganddescribingthem.
DatatypesareassignedtodifferenttypesofobjectsintheSQLdatabaseand
throughouttheOraclesystem.Inatable,eachcolumnmustbeassignedadata
type.Acolumn’sdatatypedefineswhatsortofinformationis—andisnot—
acceptedasinputintothecolumn.Itdetermineshowthevaluesinthecolumn
canbeused,howtheywillbehavewhencomparedtoothervaluesorevaluated
inexpressions,andhowtheyaresorted.
Oracle’sowndocumentationreferstodatatypesasbothdatatypesand
datatypes.Thesetwoexpressionsarethesamething.
Mostdatatypesfallunderoneofthegeneralcategoriesofnumeric,character,
ordate.There’smoretoitthanthis,butmostdatatypesfallintooneofthese
threegeneralcategories.Inadditiontothesethreeisacategoryreferredtoas
largeobject,orLOB,datatypes.LOBscanincludecharacterdatabutcannotbe
includedinaprimarykey,DISTINCT,GROUPBY,ORDERBY,orjoins.
Character
Characterdatatypesarealsoknownastextorstringdatatypes,andtheyinclude
thefollowing:
CHAR(n)ThenameCHARisshortfor“character.”Thisisafixed-
lengthalphanumericvalue.Anyalphanumericcharacterisacceptedas
input.Thenindicateshowlongthevaluewillbe.TheCHAR(n)data
typeacceptsvalidinputandpadsanyremainingunusedspacewith
blankstoensurethatthelengthofyourvaluewillalwaysequalthevalue
ofn.Forexample,ifyoudeclareacolumnwithdatatypeofCHAR(5),
thenavalueof,forexample,“A”willbestored—andretrieved—as“A”
whereAisfollowedbyfourblankspaces.Anyattempttoenteravalue
thatislongerthannwillresultinanerror,andthevaluewillnotbe
accepted.WhendeclaringaCHARdatatype,theinclusionofnis
optional;ifitisomittedinthedeclaration,avalueof1isassumed.For
example,astatementofCREATETABLEcruises(cruise_idCHAR)will
resultinaCRUISE_IDcolumnwithadatatypeofCHAR(1).The
maximumallowedvaluefornis2000.
VARCHAR2(n)ThenameVARCHARissortofanabbreviationfor
“variablecharacter.”Thisisavariable-lengthalphanumericvalue.Then
indicatesthemaximumallowablelengthofthevaluestoredwithin,but
contrarytoCHAR,theVARCHAR2formatwillnotpaditsvalueswith
blanks.Itslengthvariesaccordingtothedataitcontains.Alsodifferent
fromtheCHARdatatypeisthatVARCHAR2requiresntobespecified.
Theminimumvalueofnis1;themaximumallowablelengthof
VARCHAR2is4000.(Note:Theissueofamaximumvaluein
VARCHAR2isactuallyabitmorecomplexthanthis—themaximumis
technically4,000bytesandnotreally4,000characters,andbydefault
mostOracledatabaseimplementationsareconfiguredsothatone
characterequalsonebyte.Butit’spossibletooverridethis,whichwould
theoreticallychangethemaximumnumberyoucanusefornina
VARCHAR2declaration.Furthermore,beginningwithOracle12c,there
isaninitializationparameterMAX_STRING_SIZEthatcanbesettothe
valueEXTENDED,enablingVARCHAR2declarationsofupto32,767.
Forourpurposeshereitdoesn’treallymatter—ithasn’tbeenanissueon
theexam.Butkeepaneyeoutforthis;itmaybeintroducedintothe
examinthefuture.)
Numeric
Numericdatatypesincludethefollowing:
NUMBER(n,m)Thisdatatypeacceptsnumericdata,including
zero,negative,andpositivenumbers,wherenspecifiesthe“precision,”
whichisthemaximumnumberofsignificantdigits(oneithersideofthe
decimalpoint),andmisthe“scale,”meaningthetotalnumberofdigits
totherightofthedecimalpoint.Bothnandmareoptional;ifbothare
omitted,bothdefaulttotheirmaximumvalues.Ifnisspecifiedandmis
omitted,mdefaultstozero.Thevalueforncanrangefrom1to38;the
valueformcanrangefrom–84to127.Notethatthesearenotthelargest
valuesyoucanhavebutratherthelargest(andsmallest)specifications
forvaluesyoucanhave—Oracle’sSQLLanguageReferenceManual
carefullystatesthatthevaluesacceptedforaNUMBERdatatyperange
from1.0×10–130upto“butnotincluding”1.0×10126.Ifavalueentered
intoaNUMBERcolumnhasaprecisiongreaterthanthespecifiedvalue,
anerrormessagewillresult,andthevaluewillberejected.Ontheother
hand,ifavalueisenteredthatexceedsthedeclaredscale,theentered
valuewillberoundedoff(.5isroundedup)andaccepted.Also,a
negativevalueformidentifieshowmanysignificantdigitstotheleftof
thedecimalpointwillberoundedoff.SeeTable2-2foranexampleof
howallofthisworks.It’sconsideredgoodpracticetospecifythe
precisionandscaleaspartoftheoveralldataintegritychecktoplace
someboundariesaroundthelimitsofwhatthebusinesslogicoftheintent
ofthecolumnwillaccept.
TABLE2-2 ExamplesofNUMBERPrecisionandScale
Date
DatedatatypesaresometimesreferredtoinOracle’sdocumentationas
datetimes.Eachdatedatatypeconsistsoffields,andeachfieldisacomponent
ofadateortime,suchashours,minutes,orthemonthvalue,andsoon.See
Table2-3foralistofthefieldsthatareusedinvariouscombinationstoform
datedatatypes.
TABLE2-3 DatetimeFields
Thedatatypesthatsupportdateandtimeinformationincludethefollowing:
DATEThisacceptsdateandtimeinformation.Thefieldsstored
includeyear,month,date,hour,minute,andsecond.Datevaluesmaybe
storedasliteralsorusingconversionfunctionsthatyou’llseelaterin
Chapter6.Dateliteralsareenclosedinsinglequotationmarksandmay
bespecifiedinanumberofways.ThedefaultOracledateformatfora
givencalendardayisdefinedbytheparameterNLS_DATE_FORMAT.
TheinitializationparameterNLS_DATE_FORMATspecifiesthe
defaultdateformatforyourdatabase.However,itisalsopossiblethat
NLS_DATE_FORMATisnotexplicitlysetbutisinsteaddefaultedtothe
associateddateformatofanotherinitializationparameter,
NLS_TERRITORY.Toseethevaluespecifiedfortheinitialization
parameterNLS_TERRITORYinyourdatabase,useSHOW
PARAMETERSNLS_TERRITORY.Toseewhetheravaluefor
NLS_DATE_FORMATwasspecifiedforyourdatabase,useSHOW
PARAMETERSNLS_DATE_FORMAT.Regardlessofwhetherthe
NLS_DATE_FORMATwasexplicitlysetforyourdatabase,youcansee
itsvaluewiththisquery:
TheNLS_DATE_FORMATparametercanbechangedwithALTER
SESSIONorALTERSYSTEM,whichareSQLstatementsthatarenot
includedontheexam.Bydefault,installationsintheUnitedStatesand
UnitedKingdomusetheNLS_DATE_FORMATofDD-MON-RR,
whereDDisthetwo-digitday,MONisthethree-letterabbreviationfor
themonth,andRRisthetwo-digityear,wherevaluesofRRranging
from00to49areassumedtobeinthetwenty-firstcentury(2000to
2049),whileRRvaluesrangingfrom50to99areassumedtobeinthe
twentiethcentury(1950through1999).Forexample,'01-NOV-10'isthe
firstofNovemberin2010.(Note:ThesamedateinANSIformatis
'2010-11-01'.ANSIformatis'YYYY-MM-DD',whereYYYYisthe
four-digityear,MMisthetwo-digitmonth,andDDisthetwo-digitday.)
SeeChapter6formoreonthesetopics.
TIMESTAMP(n)ThisisanextensionofDATEthataddsfractional
secondprecision.TIMESTAMPstoresyear,month,day,hours,minutes,
seconds,andfractionalseconds.Thevaluefornspecifiestheprecision
forfractionalseconds.Therangefornis0–9.Ifnisomitted,itdefaults
toavalueof6.
TIMESTAMP(n)WITHTIMEZONEThisisavariationof
TIMESTAMPthataddseitheratimezoneregionnameoranoffsetfor
timezone.TIMESTAMPWITHTIMEZONEisusedintrackingdate
informationacrossdifferenttimezonesandgeographicalareas.The
rangefornis0–9.Ifnisomitted,itdefaultstoavalueof6.
TIMESTAMP(n)WITHLOCALTIMEZONEThisisavariation
ofTIMESTAMP.TheTIMESTAMPWITHLOCALTIMEZONEdiffers
fromTIMESTAMPWITHTIMEZONEinthatthetimezoneoffsetis
notstoredwiththecolumn’svalue,andthevalueretrievedissenttothe
userintheuser’slocalsessiontimezone.Inotherwords,whiletheoffset
isnotstoredwithTIMESTAMPWITHLOCALTIMEZONE,the
systemcalculatestheoffsetautomaticallywhenthevalueisaccessed
fromadifferenttimezone.Endusersseethetimeintheirownlocaltime
zone,regardlessofthetimezonewherethedatabaseserverhappensto
reside.Theoffsetiscalculatedautomatically.Ifnisomitted,itdefaultsto
avalueof6.
INTERVALYEAR(n)TOMONTHThisstoresaspanoftime
definedinonlyyearandmonthvalues,wherenisthenumberofdigits
usedtodefinetheYEARvalue.Therangeofacceptablevaluesfornis
0–9;thedefaultfornis2.Thisdatatypeisusefulforstoringthe
differencebetweentwodatevalues.
INTERVALDAY(n1)TOSECOND(n2)Thisstoresaspanoftime
definedindays,hours,minutes,andseconds,wheren1istheprecision
fordays,andn2istheprecisionforseconds.Therangeofvaluesforn1
is0–9,andthedefaultis2.Thevalueforn1specifieshowmanydigits
areacceptedindeclaringthesizeofanumberforDAYtobespecified.
Thevalueforn2isthefractionalsecondsprecisionforSECOND;the
rangeforacceptablevaluesis0–9,andthedefaultis6.Thisisusefulfor
storingthedifferencebetweentwodatevalues.
Thedatatypesthathandletimezonedifferencesareimportanttothe
exam.You’lllookatfunctionsinChapter6thatdealwiththesedata
types.
LargeObjects
Theexamwilladdressyourknowledgeofhowtouselargeobject,orLOB,data
typesinSQLlanguagesyntax.LOBscangenerallybeusedlikeotherdatatypes.
TablesmayhavemultiplecolumnswithLOBdatatypes.However,LOBscannot
beprimarykeys,andtheycannotbeusedwithDISTINCT,GROUPBY,
ORDERBY,orjoins.
LOBsincludethefollowing:
BLOBThenameBLOBisanabbreviationfor“binarylargeobject.”
BLOBacceptslargebinaryobjects,suchasimageorvideofiles.
Declarationismadewithoutprecisionorscale.(Themaximumsizeis
calculatedbywayofaformulathatincludesseveralitemsnotonthe
exam,includingastartingsizeof4GB,somethingcalledtheCHUNK
parameter,andthesettingforthedatabaseblocksize,whichisasetting
thataffectsallstorageinthedatabase.)
CLOBThenameCLOBisanabbreviationfor“characterlarge
object.”CLOBacceptslargetextdataelements.Declarationismade
withoutprecisionorscale,andthemaximumsizeiscalculatedinthe
samemannerthatitisfortheBLOBdatatype.
NCLOBThisacceptsCLOBdatainUnicode.Themaximumsizeis
calculatedinthesamemannerthatitisfortheBLOBdatatype.
RegardingUnicode—itisacharactersetthatservesasanalternativeto
ASCIIandrepresentsamoreuniversalstandardthatsupportsallmajor
languagesmoreeasilythantheotherimplementationsinusetoday.
OracleandmostothermajorvendorshaveadoptedUnicodeintotheir
products,andcommonwebtechnologiesalreadysupportit.Giventhe
increasingroleofglobalizationandmultilanguagesupport,anylegacy
applicationdeployedwithoutUnicodemayinevitablyrequirea
conversioneffortdowntheroad.OracleCorporationisofficially
recommendingtheuseofUnicodeasthedatabasenationalcharacterset
forallnewsystemdevelopment.
Here’sanexampleofatablethatincludesacolumnoftheCLOBdatatype:
Theprecedingexamplecreatesatablewithtwocolumns,thesecondofwhich
isaCLOB.Thatcolumncanreceiveextremelylargetextdataasinput.
OracleCorporationdiscouragestheuseoftheoldLONGdatatypeand
encouragesyoutoconvertLONGdatatypestoLOBdatatypes,whichhave
fewerrestrictions.Forexample,youcanaddmorethanoneLOBcolumntoa
table,youcanselectLOBcolumns,youcaninsertintotableswithLOB
columns,andyoucandeleterowswithLOBvalues.However,asIstatedearlier,
youcannotuseLOBsinGROUPBYorORDERBYclauses.
Allofthedatatypesyou’veseensofararebuiltinbyOracleandincludedwith
SQL.Allofthesedatatypesareknownas“built-in”datatypes.However,it’s
possibleforuserstocreatetheirownunique“user-defined”datatypes.User-
defineddatatypesarecreatedusingtheSQLstatementCREATETYPE.They
areusedinPL/SQLcodeandarenotasubjectoftheexam.
CERTIFICATIONOBJECTIVE2.05
ExplainHowConstraintsAreCreatedattheTimeof
TableCreation
YoucancreateaCONSTRAINTtosupportotherobjects,specificallyTABLE
objects.Butthereisn’taCREATECONSTRAINTstatement;youcreatea
CONSTRAINTaspartofanotherstatement,suchasCREATETABLEor
ALTERTABLE.WhenyoucreateaCONSTRAINT,youcanchoosetonameit
yourselforletthesystemautomaticallyassignaname.Thecreationofcertain
constraints—PRIMARYKEY,UNIQUE,andFOREIGNKEY—will
automaticallytriggerthecreationofacorrespondingindexobjectofthesame
name.
Here’sanexampleofaCREATETABLEstatementthatincludesthesyntax
tocreateaCONSTRAINT:
Intheprecedingexample,wecreateaTABLEcalledPOSITIONS,which
consistsofthreecolumns,POSITION_ID,POSITION,andEXEMPT.Afterthe
EXEMPTcolumnisdefined,thisparticularexampleshowsanadditionallineof
codetocreateaCONSTRAINT.(Thereareotherformatsforcreating
constraints,asyouwillsoonsee.)Inthisexample,wearechoosingtonamethe
CONSTRAINT,somethingthatwedon’tnecessarilyhavetodo.Thenamewe
areassigningtothisCONSTRAINTisPOSITIONS_PK.We’respecifyingthat
thisCONSTRAINTisoftypePRIMARYKEY,andwe’reapplyingthe
CONSTRAINTtothecolumninthistablethat’scalledPOSITION_ID,which
wedefinedfirst.
Let’slookatsomespecificsnext.
CreatingCONSTRAINTSintheCREATETABLE
Statement
TherearetwowaysinwhichaCONSTRAINTcanbecreatedatthetimeof
TABLEcreation:inlineandoutofline.
CREATETABLE:In-LineConstraints
HereisanexampleofhowtocreateaPRIMARYKEYconstraintinline:
Inthisexample,wecreateaPRIMARYKEYconstraintonthecolumn
PORT_ID.TheconstraintonPORT_IDisspecifiedaspartofthePORT_ID
declaration.Itis“inline”withthecolumnuponwhichtheconstraintisapplied.
WhenIsay“inline,”Imeanthatafterwedeclareacolumntowhichwewantto
applyaconstraint,weincludetheconstraintspecification(inthiscase,fora
primarykey)beforethecommathatseparatesthecolumnspecification
(PORT_IDinthisexample)fromthenextcolumnspecification,whichis
PORT_NAME.Thefactthattheexamplehappenstoincludethewords
PRIMARYKEYonthesamelineasPORT_IDisincidentalandunnecessaryto
makethisan“inline”format.
Inthisexample,weomittheinclusionofaspecifiednamefortheconstraint,
whichcausestheOracledatabasetogenerateaconstraintnameautomatically,of
theformSYS_Cn.Here’sanexample:
You’llseehowyou’llbeabletoidentifythesystem-assignednamewhenyou
lookatthedatadictionaryinChapter12.
Alternatively,youcanoptionallyspecifytheconstraintnameatthetimeof
creation,byprecedingthereservedwordsPRIMARYKEYwiththereserved
wordCONSTRAINT,followedbyanameyoumakeupaccordingtotherulesof
namingdatabaseobjects,likethis:
Thesetwoapproachesarereferredtoasin-lineconstraints,sinceinboth
examplesthedeclarationoftheconstraintisincludedwiththecolumndefinition,
beforethecommathatendsthiscolumnspecificationandenablesasubsequent
columnspecification.
Here’sanotherexampleofin-lineconstraints.Thisexamplecreatesatable
withaNOTNULLconstraint:
TheresultofthisconstraintistoensurethatavalueforSTATUSmustbe
includedwitheachrowenteredintoVENDORS.Thevaluemightbezeroorany
othersingledigit,butitmustbeprovided—itcannotbeleftout.Itcannotbe
unknowntothedatabase.Inotherwords,itcannotbeNULL.
Hereisthesametablewithanameassignedtotheconstraint:
YoumaycombinemultipleconstraintdeclarationsinasingleCREATE
TABLEstatement,likethis:
EachconstraintspecificationistreatedasastandaloneclauseoftheCREATE
statement.Youcanmixandmatchdefinitiontypes;youcanchoosetonamethe
constraintinsomeclausesandnotinothers.Youcanalsomixandmatchin-line
constraintswithout-of-lineconstraints,towhichweturnourattentionnext.
CREATETABLE:Out-of-LineConstraints
Inadditiontoin-lineconstraints,youmayoptionallydefineaconstraintwithina
CREATETABLEstatementafterthecolumnspecifications.Here’sanexample
ofaPRIMARYKEYdefinedwiththeout-of-linesyntax,inthisexampleonline
4:
Afterthefinalcolumnisdefinedforthetable,weincludeacomma,followed
bythereservedwordsPRIMARYKEY.Noticethattheout-of-linesyntax
requiresthatyouindicatewhichcolumn(orcolumns)isaffectedbythe
constraint.Sinceyou’renot“inline”withthecolumnspecification,the
statementcannotknowwhichcolumnyou’reintendingtoconstrain,unlessyou
specificallyindicateitwithintheclause.
Here’sanout-of-lineexamplethatnamestheconstraint:
Thisexamplegivestheconstraintanamethatwe’vechosen.Asisthecase
within-lineconstraints,anyout-of-lineconstraintinwhichyoudonotprovidea
namewillcausetheOracledatabasetoautomaticallygenerateaconstraintname.
AdditionalWaystoCreateConstraints:ALTERTABLE
TheCREATETABLEstatementisn’ttheonlywaytocreateaconstraint.
ConstraintscanalsobecreatedusingtheALTERTABLEstatement.For
example,youcanfirstcreatethePORTStablelikethis:
Afterward,youcanALTERthetabletoaddaconstraintbymodifyingthe
definitionforacolumn.
Intheprecedingcode,we’remodifyingthedeclarationofthecolumnitselfby
addingtheprimarykeyandlettingthesystemassignaname.Thissyntaxresults
inthesameCONSTRAINTasifwehadusedthisinstead:
Inaddition,youcanusethedatadictionarytodeterminewhatthesystem-
generatedconstraintnameis.
Onceyoulearnthesystem-generatednameoftheconstraint(let’ssayit’s
SYS_C0011505),thenyoucanrenameitifyouwish,likethis:
Thosearethein-lineequivalentsofALTERTABLE.Herearetheout-of-line
equivalents.First,hereisanALTERTABLEthataddsaconstraintwithout
specifyinganame:
Alternatively,youcannametheconstraintyourself.
You’llworkwiththedatadictionaryinChapter12.
Warning:NOTNULLIsDifferent
We’reabouttolookatthefivedifferenttypesofconstraints,butbeforewedo,a
wordofwarningaboutthesyntaxvariationsforoneparticularconstraint:the
NOTNULLconstraintisabitdifferentwhenitcomestosyntax.TheNOT
NULLconstraintcannotbecreatedoutofline.Inotherwords,thisisinvalid:
Thisisalsoinvalid:
Eitherofthosewillproduceerrormessagesifyoutrythem.Notableor
constraintwillbecreated.Andyet,thesamesyntaxisperfectlyfineforother
typesofconstraints.Forexample,here’stheUNIQUEconstraint:
Andofcourse,thisisfine,too—thisisthePRIMARYKEYconstraint:
Soremember,NOTNULLcannotbedeclaredwiththe“out-of-line”format.
Theotherscan.Butwait,there’smoreaboutNOTNULL.Thiswon’twork
either:
Andthiswon’teither:
Thosewon’tworkbecausetheyaretheALTERTABLEequivalentsforout-
of-linedeclarations.ButtheALTERTABLEin-lineequivalentsarefine.
Andthisisalsofine:
Thelesson:beware.NOTNULLisabitunusual.It’savalidconstraintand
canbecreatedusingtheotherformsofsyntaxbutnotwiththeout-of-line
format.
Thelistofcertificationobjectivesspecificallystatesthatyouwillbe
testedonthetopicofcreatingconstraintsatthetimeoftablecreation.
Thiscanincludeanyoneofthein-lineorout-of-linecombinationsfor
anyconstraint.Thesyntaxistricky.Studyitthoroughlyandknowitwell.
TheTypesofCONSTRAINTS
Severaltypesofconstraintscanbeappliedtoatable.TheyarePRIMARYKEY,
FOREIGNKEY,NOTNULL,CHECK,andUNIQUE.(NotethattheREFtype
isnotincludedontheexam.)Let’sexploreeachoftheseindetail.
NOTNULL
TheNOTNULLconstraintissimple—whenappliedtoacolumn,itensuresthat
foranyrowthatisaddedtotheTABLE,thecolumnonwhichtheNOTNULL
constraintisappliedwillalwaysbeprovidedwithavalue.Meanwhile,the
column’sdatatypeensuresthatthedataenteredintothecolumnisconsistent
withthedatatype’srules.
Tofullyappreciatethisconstraint,ithelpstounderstandwhattheconceptof
NULLis.Let’stakealook.
TheConceptofNULLThereservedwordNULLis,inmyever-so-humble
opinion,oneofthemostmisunderstoodaspectsoftheSQLdatabase.The
definitionofNULListhe“absenceofinformation.”Sometimesit’s
mischaracterizedas“zero”or“blank,”butthatisincorrect—a“zero,”afterall,is
aknownquantity.Soisablank.ButNULLis“unknown.”It’sthewaythe
databaseacknowledgesthatit,thedatabase,ismerelyanimperfectrepositoryof
informationaboutsomereal-lifebusinesssituationorsomeotherapplicationout
thereintheworld,andthedatabaseisultimatelydependentonthedatait’sbeen
giventomirrorthatreal-lifesituation.Butultimately,it’sreallife—notthe
database—thatisthefinalauthority.So,it’sentirelypossible—andquitelikely
—thatsomeinformationhasn’tbeenprovidedtothedatabase.NULLisa
placeholderforwherethatinformationgoes,specifically,wherethedatabasehas
notbeengivenclearinstructionaboutwhetheravalueexists,andifitdoesexist,
whatvalueitmightbe.
Forexample,considerthefollowingtablecontainingthenamesofcustomers:
Let’saddarowtothistable.
NoticethatnovalueisprovidedhereforMIDDLE_NAME.Whenthis
happens,thenintheabsenceofotherinformation,thedatabasestoresaNULLin
itsplace.
Doesthismeanthatsomewhereoutthereintheworldisareal-lifeperson
namedAngelinaEllisonwhohasnomiddlename?Well,maybeshedoes,and
maybeshedoesn’t.Thepointisthatthedatabasedoesn’tknowwhethershehas
amiddlenameornot—thevalueisunknowntothedatabase.
Thisbecomesimportantwhenitcomestosuchsituationsasmathematical
expressions.Considerthefollowingexpression:
Let’ssaythatthevalueforCRUISE_PRICEis300,andthevaluefor
DISCOUNTisNULLinthedatabase.Inotherwords,maybethere’sadiscount
value,andmaybethereisn’t.Thedatabasedoesn’tknoweitherway—it’s
unknowntothedatabase.ThevalueisNULL.Ifthat’sthecase,thenwhatisthe
answertotheequationgiveninthisexpression?
Theanswerfortheequationof300timesNULLis...what?
Giveup?
TheanswerisNULL.Thereasonissimple:300multipliedby“Idon’tknow”
resultsin...“Idon’tknow.”
Inotherwords,perhapstheequationreallydoeshaveananswer,butifyou
don’tknowwhattheDISCOUNTvalueis,thenyoudon’thaveenough
informationtocalculatetheansweroftheexpression.Therefore,theansweris
unknown—inotherwords,NULL.
We’lladdressNULLsomemoreinthesectiononfunctions.Fornow,allthat
we’reconcernedwithistheNOTNULLconstraint.WhentheNOTNULL
constraintisappliedtoacolumn,you’rerequiringthatanyrowsaddedtothe
tableincludeavalueforthatcolumn.
Let’sgobacktotheearlierexample.IfwehadappliedaNOTNULL
constrainttotheMIDDLE_NAMEcolumnoftheCUSTOMERStable,thenwe
neverwouldhavehadarowlike“AngelinaEllison”withnomiddlename.The
NOTNULLconstraint,ifappliedtotheMIDDLE_NAMEcolumn,wouldhave
requiredamiddlenamevalueforanyrowbeingaddedtothetable.
Intherealworld,therereallyarepeoplewithoutamiddlename.Insuch
situations,anapplicationissmarttousetheNMNorNoMiddleNameentry
toconfirmthatthereisnomiddlenameandthusavoidaNULLvalue,which
isambiguous.
Bydefault,allcolumnsallowNULLvalueswhenfirstcreated.Youmust
choosetoapplyaNOTNULLconstraint—oranequivalent—toacolumnifyou
wanttorequiredataforthatcolumn.
WhenIsay“oranequivalent,”Imeanthattherearealternativewaysto
requiredatainacolumn.OnewayisthePRIMARYKEYconstraint,whichisa
NOTNULLrulecombinedwiththeUNIQUEconstraint,whichyou’llseenext.
IfyouapplyaPRIMARYKEYconstraintonacolumn,youdonotneedto
alsoapplyaNOTNULLconstraint.ButifthereisnoPRIMARYKEY
constraintforagivencolumn,theNOTNULLconstraintwillensurethatany
rowsaddedtothetablewillincludeavalueforthatparticularcolumn.
UNIQUE
TheUNIQUEconstraint,whenappliedtoacolumn,ensuresthatanydataadded
tothecolumninthefuturewillbeuniquewhencomparedtodataalready
existinginthecolumn.Nootherrowwillpossessthesamevalueforthat
particularcolumn.
ThefollowingareafewnotesaboutUNIQUE:
AsingleUNIQUEconstraintcanbeappliedtoonecolumnorto
multiplecolumnsincombination.You’lllearnmoreaboutthisinafew
sentences.
UNIQUE,byitself,allowsNULLvaluestobeaddedtothecolumn.
Itonlyrestrictsdatathat’sprovidedforthecolumntobeingoneofakind
forthecolumn.
NotethatthePRIMARYKEYconstraintrepresentsthecombinationofNOT
NULLandUNIQUE.UsethePRIMARYKEYconstraintinsteadoftheNOT
NULLandUNIQUEconstraintsifyourintentistocreateasingleunique
identifierforeachrowinthetable.
CompositeUNIQUEConstraintYoumaycreateaUNIQUEconstraintthat
appliestomultiplecolumnssimultaneously.Thishastheeffectofrequiringthe
combinationofcolumnstobeunique.Inotherwords,eachindividualcolumn
mayrepeatdata,butcollectivelythecombinationofdatainallofthecolumns
foranygivenrowwillhavetobeunique.
PRIMARYKEY
ThePRIMARYKEYdefinesoneormorecolumnsinatablethatwillformthe
uniqueidentifierforeachrowofdatathatisaddedtothetable.ThePRIMARY
KEYconstraintisacombinationoftheNOTNULLandUNIQUEconstraints.
AtablemayhaveonlyonePRIMARYKEYconstraint.
Asingle-columnPRIMARYKEYisthemostcommonform,anditensures
thatforallrowsofdataaddedtothetableinthefuture,thecolumnuponwhich
thePRIMARYKEYconstrainthasbeenappliedwillalwayscontainavalueand
thatvaluewillalwaysbeuniquewhencomparedtoexistingvaluesthatare
alreadyinthetableforthatparticularcolumn.
HereisanexampleofaCREATETABLEstatementthatcreatesaPRIMARY
KEYconstraint:
Intheprecedingexample,wecreateaPRIMARYKEYconstraintonthe
EMPLOYEE_IDcolumn.Inthisexample,we’vegiventheconstraintanameof
EMPLOYEES_PK.(ThePKsuffixisnotrequired;itispresentedhereasjust
oneofmanygooddesignapproachesthatclarifiestoanyonewhomightreviewa
longlistofdatabaseconstraintslaterthatthisparticularconstraintisaprimary
key.)Nowthatwe’vecreatedthistablewiththePRIMARYKEYconstraint,any
rowthat’saddedtotheEMPLOYEEStableinthefuturewillrequireaunique
valueforeachrowadded.
CompositePrimaryKeysAmulticolumnPRIMARYKEYisbasedontwoor
morecolumnsthatcollectivelyservethesamepurposeasasingle-column
PRIMARYKEY.Inotherwords,thecombinationofcolumnvalueswill
collectivelyhavetobeunique,andallcolumns—individuallyandcollectively—
willhavetocontainvalues.
SeeFigure2-4forsomesampledata.NoticethethreecolumnsCATEGORY,
YEAR,andTICKET.Individuallyeachshowsdatathatrepeatsthroughoutthe
datalisting.Buttogethereachrowofcombinedcolumnsrepresentsuniquedata.
FIGURE2-4 SampledatafromHELP_DESKtable
Here’sanexampleofaCREATETABLEstatementthatwouldcreatea
compositePRIMARYKEYconstrainttosupportFigure2-4:
TheprecedingcodehastheeffectofcreatingNOTNULLandUNIQUE
constraintsacrossallthreecolumns.ForeachrowenteredinthetableHelpDesk,
avaluewillberequiredineachofthethreecolumnsHD_Category,HD_Year,
andHD_Ticket_No,andthecombinationofthosethreevalueswillneedtobe
uniqueforeveryrow.Asyousawintheearliersampledata,it’spossibleto
repeatvaluesintheindividualcolumns,butthecombinationmustalwaysbe
uniqueineachrow.
FOREIGNKEY
AFOREIGNKEYconstraintappliestooneormorecolumnsinaparticular
tableandworksinconjunctionwithareferredtable’sPRIMARYKEY
constraint.AFOREIGNKEYisthefeaturethathelpsensurethattwotablescan
“relate”toeachother,andinmanywaysthisreallyrepresentsthe“heartand
soul”ofwhatarelationaldatabaseisallabout.
TheFOREIGNKEYconstraintdoesthefollowing:
Itidentifiesoneormorecolumnsinthecurrenttable;let’scallthis
thechildtable.
Foreachofthosecolumns,italsoidentifiesoneormore
correspondingcolumnsinasecondtable;let’scallthistheparenttable.
ItensuresthattheparenttablealreadyhaseitheraPRIMARYKEY
orUNIQUEconstraintonthosecorrespondingcolumns.
ItthenensuresthatanyfuturevaluesaddedtotheFOREIGNKEY–
constrainedcolumnsofthechildtablearealreadystoredinthe
correspondingcolumnsoftheparenttable.
Inotherwords,aFOREIGNKEYconstraintonthechildtable,alongwiththe
PRIMARYKEYconstraintontheparenttable,enforcesreferentialintegrity
betweenthetwotables.Thismeansthattheconstraintsworktoensurethatany
futuredatathatisaddedtooneorbothofthetablescontinuestosupportthe
abilitytorelatedatafromonetabletoanother.
Note:ThereferencedtableisnotactuallyrequiredtohaveaPRIMARYKEY
constraintonthereferencedcolumnsbutonlyaUNIQUEconstraintonthe
referencedcolumns.Butyou’llrecallthataPRIMARYKEYconstraintisa
combinationoftheUNIQUEandNOTNULLconstraints,sothePRIMARY
KEYsatisfiestherequirementforaUNIQUEconstraint.
Let’slookatasamplescenario.First,hereisalistingofdatainthePORTS
table:
Next,hereisalistingofinformationintheSHIPStable:
Asyoumighthavealreadysurmised,thevalueforeachship’s
HOME_PORT_IDvalueshouldcorrespondtoaPORT_IDvalueinthePORTS
table.
Toensurethatthetwotablesonlyacceptdatathatsupportsthisbusinessrule
(inotherwords,thatrequiresallHOME_PORT_IDvaluestobevalidPORT_ID
values),youcancreateaPRIMARYKEYconstraintonthePORTStable(ora
UNIQUEconstraint)andthenaFOREIGNKEYconstraintontheSHIPStable
thatcorrelatesbacktothePRIMARYKEYconstraintonthePORTStable.
First,hereisthePORTStable(linenumbersadded):
Next,hereistheSHIPStable:
NotethattheforeignkeyconstraintclauseintheCREATETABLESHIPS
statementstartsonline11andcontinuesthroughline12.Itreferencesthe
PORTStableandthePORTStable’sPORT_IDcolumn,whichalreadyhasa
PRIMARYKEYconstraintappliedtoit.Ifitdidnotalreadyhaveeithera
PRIMARYKEYconstraintoraUNIQUEconstraintonit,thentheCREATE
TABLESHIPSstatementwouldresultinanerrorandletyouknowthatthe
PORTStablealreadymustexistandmusthaveaPRIMARYKEYorUNIQUE
constraintonthePORT_IDcolumn.
TheFOREIGNKEYonSHIPSmakessurethatanyrowaddedtotheSHIPS
tablewillacceptvaluesforHOME_PORT_IDonlyifthatvaluealreadyexistsin
thePORTStable.NotethattheHOME_PORT_IDvalueisnotrequired;ifyour
goalistoensurethattheHOME_PORT_IDvalueisalwaysprovided,you’ll
havetoalsoaddaNOTNULLconstraintonHOME_PORT_IDaswellas
FOREIGNKEY.Thisisonewaytodothat:
Intheprecedingexample,wecreatetwoseparateconstraints.Ofthosetwo
constraints,oneofthemisonlines11through12andexiststomakethe
HOME_PORT_IDcolumnaforeignkey,andtheotherconstraintisattheendof
line10andensuresthatthereisalwaysavalueenteredforHOME_PORT_ID.
Inmyprofessionalexperience,Ifinditmucheasiertocreateforeignkeys
withALTERTABLEstatementsinsteadofwithCREATETABLEstatements.
Onereasonisthattheresultingcodeismoremodular.Notethatyoucannot
createaforeignkeyconstraintthatreferstoatablethatdoesn’texist.Ifyour
goalistobuildascriptforcreating(andifnecessary,re-creating)yourentire
databaseandthenyoutrytocreateallofyourtableswithforeignkeyconstraints
withinyourCREATETABLEstatementssothattheyoccurafterthecreationof
theirrespectiveprimarykeytables,allofthatcansuddenlyturnintoquitea
puzzleoftryingtoensureyourCREATETABLEstatementsallruninthe
correctordersothatyourreferredtablesalreadyexistbeforeyoucreatetables
withforeignkeyconstraintsagainstthoseprimarykeytables.Notonlyissuch
aneffortdifficult,itmayprovetobeimpossibleinadatamodelwherethe
relationshipsruninbothdirections.Allofthisisanunnecessaryeffortwhenyou
caneasilybuildallofyourtablesfirst,thenalterthosetablestoaddforeignkeys
withinaseriesofALTERTABLEstatements,andfinallyplacethemallafter
yourCREATETABLEstatementsasawhole.Thecomplexityjustdescribed
(the“puzzle”)iseliminatedwiththatapproach.Othercomplicationsyoumight
avoidincludethefactthatyoucannotcreateaforeignkeywithinaCREATE
TABLEstatementthatusesthe“asquery”approach—thatapproachcreatesthe
tableandpopulatesitwithdatausingasubquery’sSELECTstatementallat
once.Inthatsortofsituation,theclausetocreateaforeignkeyconstraintisn’t
allowed.Givensuchrestrictions,Ifindnobenefittostrugglingtobuildaforeign
keyfromwithintheCREATETABLEstatementandwouldjustassoonusean
ALTERTABLEstatementwheretheserestrictionsdon’texist.But...that’sjust
me.
ONDELETETheforeignkey/primarykeyrelationshipbetweentwotables
introducessomeadditionalconsiderations.Whatshouldbethebehaviorwhen
rowsareremovedfromtheparenttableforwhichthereisachildrowinachild
table?
UsingtheearlierexampleofPORTSandSHIPS,aSHIPSrowmightcontain
avalueforPORT_ID,indicatingthehomeportoftheship.Butwhatifthecruise
lineceasestodobusinesswithaparticularportandremovestherowforthat
portfromthePORTStable?
OneoptionwouldbetomanuallyeditSHIPSandremoveallreferencestothe
PORT_IDvaluefortheformerport.
Analternative(andbetter)approachistoincludetheONDELETEclause
whenwecreatetheFOREIGNKEYconstraint.
ThepreviousCREATETABLESHIPSstatementdiffersfromtheearlier
exampleintwoways:
TheHOME_PORT_IDcolumn(line10)isnolongerconstrainedby
NOTNULLsincewewanttheoptionofhavingaNULLvaluefor
HOME_PORT_ID.
TheforeignkeyconstraintnowincludesthekeywordsON
DELETESETNULLaspartoftheconstraintdefinition(notethatitis
withintheclosingparenthesesthatendthecreationoftheconstraintbut
notthecreationofthetableSHIPS).
Now,whenaparentrowinPORTSisremoved,theOracledatabasewill
automaticallyinspectrowsinSHIPStoseewhetheranySHIPspecifiedthe
removedport’sprimarykeyintheHOME_PORT_IDcolumn.Ifyes,anyrows
withavaluefortheremovedPORT_IDwillhavethosePORT_IDvalues
replacedwithaNULLvalue.
Asanalternative,youcouldchoosetoremovetheSHIPSrowcompletelyifa
correspondingparentrowinPORTSisremoved.
ThisoptionwillremoveallSHIProwsassignedtoaPORTrowuponthe
PORTrow’sremovalfromthePORTStable.
CHECK
ACHECKconstraintattachesanexpressiontoaconstraint.Inotherwords,it
appliesasmallbitofcodetodefineaparticularbusinessruleonincomingrows
ofdata.ACHECKconstraintmay,forexample,restrictincomingdatasothatall
incomingvaluesarerequiredtobegreaterthansomeminimumvalueorfall
withinasetofpredeterminedoptionalvalues.ACHECKconstraintcanensure
thatatwo-charactercolumnacceptsonlyvalidabbreviationsforAmerican
states,forexample,orthatthedateenteredinonecolumninatableisalways
greaterthanthedateenteredinanothercolumninthesametable.
Here’sanexampleofaCHECKconstraintthatonlyallowsrowsinthe
VENDORStablewithaSTATUSvalueofeither4or5:
WhilerowsmaybeaddedtoVENDORSwithnoSTATUSvalue,theycanbe
givenaSTATUSvalueonlyifitiseither4or5.
AnyvalidSQLexpressionmaybeusedinaCHECKconstraint,withsome
limitations.TheCHECKconditioncannotincludereferencestothefollowing:
Columnsinothertables(notethatothercolumnsinthesametable
areaccepted)
PseudocolumnsCURRVAL,NEXTVAL,LEVEL,orROWNUM
Subqueriesandscalarsubqueryexpressions
User-definedfunctions
Certainfunctionswhosevaluecannotbeknownatthetimeofthe
call:SYSDATE,SYSTIMESTAMP,CURRENT_DATE,
CURRENT_TIMESTAMP,DBTIMEZONE,LOCALTIMESTAMP,
SESSIONTIMEZONE,UID,USER,andUSERENV
Forarowofdatatobeacceptedasinputtogiventable,anyCHECK
constraintpresentmustevaluatetoeitherTRUEorunknown,duetoaNULL.
MultipleConstraints
Atablemaybedeclaredwithmultipleconstraints.Here’sanexample:
Intheprecedingexample,wehaveasingleCREATETABLEstatementthat
createsatablealongwithfiveconstraints:
Auser-namedPRIMARYKEYonVENDOR_ID
Asystem-namedNOTNULLconstraintonVENDOR_NAME
Auser-namedNOTNULLconstraintonSTATUS
TwoCHECKconstraints:oneonSTATUSandanotheron
CATEGORY
AnysingletablemayhaveonlyonePRIMARYKEYconstraint.Itcanhave
anyothercombinationofanyotherconstraints.
FullList
Table2-4displaysafullsetofsampleconstraintstatementsforeachconstraint
typeandeachstatementformat.
TABLE2-4 ConstraintReview
TakeparticularnoteoftheFOREIGNKEYexamples.Themostimportant
portionoftheFOREIGNKEYconstraintdeclarationisnotthekeywords
FOREIGNKEYbutthekeywordREFERENCES.ThetermFOREIGNKEY
appearsinonlyoneformatofthestatement.
DataTypeRestrictions
Therearesomerestrictionsonsomeconstraints.SeeTable2-5forasummaryof
datatyperestrictionsonconstraints.Theserestrictionsmeanthatthedatatypes
identifiedcannotandwillnotreceiveaconstraintappliedagainstthemifthey
areofthetypesindicatedinthetablewitha“No”intheappropriatefield.For
example,thePRIMARYKEYconstraintcannotincludeanycolumnswithadata
typeofBLOB,CLOB,orTIMESTAMPWITHTIMEZONE.(Note,however,
thatconstraintsmaybeappliedtocolumnsthathavethedatatypeof
TIMESTAMPWITHLOCALTIMEZONE.)
TABLE2-5 DataTypesandConstraintRestrictions(No=NotAllowed)
CERTIFICATIONOBJECTIVE2.06
DropColumnsandSetColumnUNUSED
Thissectionlooksatwhatyoucandowhenyoufindthatyouhavecolumnsyou
nolongerwishtokeepinatable.Youcanchoosetodropacolumnfromthe
databaseor,asanalternative,youmayrenderitUNUSED.Thissectionlooksat
howtodoeitherofthesetasks.
DroppingColumns
Alteringatabletodropcolumnsthatarenolongerusedcanfreeupstorage
spaceandpotentiallyimproveperformanceofthetable.Anyconstraintsor
indicesonthecolumnwillalsobedroppedwhenyoudropthecolumn.
Herearetwoexamples—onewithoutparenthesesaroundthecolumnname,
anotherwiththeparentheses:
BotharevalidstatementstodroptheCRUISE_ORDER_DATEcolumn.Note
thatthekeywordCOLUMNisrequiredinthefirstvariation,wheretheDROP
clausesyntaxomitstheparentheses.Inthesecondvariation,thekeyword
COLUMNisomitted,andtheparenthesesareused.
ThefirstvariationislimitedtodroppingonecolumnperSQLstatement.
Usingthesecondvariation,however,youcandropmultiplecolumnsbyusing
thekeywordDROPonetime,omittingthekeywordCOLUMN,andthen
includingapairofparentheses,followedbyalistofthecolumnnamesyouwish
todrop.Forexample:
Youcannotdropallofthecolumnsinatable.Atablemusthaveatleastone
column.
Restrictions
Ifacolumnisreferencedbyaforeignkeyconstraintinanothertable,thenthe
precedingsyntaxwilltriggerawarningmessageandtheattempttodropthe
columnwillfail.
Forexample,considerthiscode:
TheseSQLstatementswillcreatetwotables.CRUISE_ORDERSiscreated
withaPRIMARYKEYconstraint,andORDER_RETURNSiscreatedwitha
FOREIGNKEYconstraintthatreferencestheprimarykeyof
CRUISE_ORDERS.SeeFigure2-5forthedatamodelrepresentingthe
relationship.
FIGURE2-5 DatamodelforCRUISE_ORDERSandORDER_RETURNS
IntheCRUISE_ORDERStable,wecannotsimplydropthe
CRUISE_ORDER_IDcolumn:
InordertodroptheCRUISE_ORDER_IDcolumnweneedtoaddressthe
constraint:
ThestatementaboveworkswhenweaddthekeywordsCASCADE
CONSTRAINTStoindicatethatwewanttodropthecolumnandalsodropany
constraintsonthecolumnaswell.
WhenusingthekeywordsCASCADECONSTRAINTS,notethatboth
CONSTRAINTandCONSTRAINTSworkequallywell.Oracledocumentation
specifiesthekeywordsintheplural:CASCADECONSTRAINTS.
Thereasonwe’repreventedfromdroppingtheCRUISE_ORDER_IDcolumn
inCRUISE_ORDERSisbecauseaforeignkeyconstraintelsewhereis
dependingonthatcolumn.However,thereferencingtabledoesnothavethe
samerestrictionondroppingcolumns.Forexample,thiswillworksuccessfully
withouttheCASCADECONTRAINTSkeywords:
TheDROPCOLUMNstatementexecutessuccessfully,andwhileitmaynot
bereadilyapparent,theFOREIGNKEYconstraintisalsodroppedasaresultof
thisstatement.Afterall,theFOREIGNKEYconstraintisbasedonthe
CRUISE_ORDER_IDcolumninORDER_RETURNS,andsincewe’vedropped
thecolumninthattable,theconstraintisdroppedaswell,withoutthe
CASCADECONSTRAINTSkeywords.However,youmayincludethemifyou
wish:
Thiswouldhaveworkedaswelleitherway.
However,let’slookaslightvariationofthisscenarioandseewhathappens
whenwehaveacompoundkeyasourforeignkey.Seebelow:
Thecodeabovecreatesthesametwotableswesawearlier—
CRUISE_ORDERSandORDER_RETURNS.Asbefore,thereisaforeignkey
constraintonORDER_RETURNSreferencingCRUISE_ORDERS,butnowitis
acompoundforeignkey—thisforeignkeyisbasedontwocolumns:
CRUISE_ORDER_IDandORDER_DATE.
IfwetrytodroponeofthosecolumnsinORDER_RETURNS,wegetan
errormessage:
Onealternativehereistodropbothforeignkeycolumnsatonce:
Alternatively,wecouldstaywithouroriginalplantodroponecolumn,but
accountfortheconstraintintheprocess.IfweaddthekeywordsCASCADE
CONSTRAINTStotheDROPCOLUMNstatementonjustthe
CRUISE_ORDER_IDcolumn,thestatementwillexecutesuccessfully.See
Figure2-6foranexampleoftheresults.
FIGURE2-6 DROPCOLUMNwithCASCADECONSTRAINTS
TheeffectoftheCASCADECONSTRAINTkeywordswiththeDROP
COLUMNclauseistodropthecolumnandalsotodroptheassociated
constraintsonthecolumnthatmightpreventthecolumnfrombeingdropped.
Anadditionalnoteaboutdroppingcolumns:youcannotdropthefinal
remainingcolumninatable;atleastonecolumnmustremaininthetable.
UNUSED
Insteadofdroppingatablecolumnyouarenolongerusing,youmayelectto
declareitunusedandleaveitinplace.OnceyousetacolumnasUNUSED,itis
neveragainavailable;itisasthoughithasbeendropped.Aswithdropped
columns,anyconstraintsorindicesonthecolumnwillalsobedropped.Youwill
neverbeabletorecoveracolumnthatissettoUNUSED.AROLLBACK
statementwillhavenoeffect—anUNUSEDcolumnwillnotberecoveredina
ROLLBACKoperation.OnceacolumnissettoUNUSED,youcanaddnew
columnsthathavethesamenameasanyunusedcolumnsforthetable.
OnceacolumnhasbeensettoUNUSED,itcanneverberecovered.
Sowhywouldn’tyoujustDROPacolumninsteadofsettingittoUNUSED?
OnereasonistheperformancefortheDROPstatementversustheSET
UNUSEDapproach.Ifyou’reworkingwithaverylargetableorsetoftables,
andyouneedtodropsomecolumns,youmayfindthatthesystemperformance
forexecutingtheDROPistemporarilyunacceptable,particularlyforasystem
thatisinheavyproduction.Ifthisisanissue,andyouneedtoachievethelook-
and-feelofadroppedcolumnimmediately,thentheSETUNUSEDalternativeis
awelcomeoption.Theperformanceisspeedy,theresultsare—forallpractical
purposes—thesame,andyoucanalwaysscheduleatimelatertocomebackand
dropthecolumnduringaperiodoflowactivityinthedatabase.
Onethingtokeepinmind:there’salimittothetotalnumberofcolumnsany
giventablecanhave.Thatlimitis1,000—youcannotcreatemorethana
thousandcolumnsinanyonetable.IfyousetacolumntobeUNUSED,that
columnwillstillcountaspartofthethousandcolumnstowardyourlimit,until
youeventuallyDROPthecolumn—whichyoucando;we’lldiscusshowtodrop
anunusedcolumninabit.
ThesyntaxforSETUNUSEDisvirtuallyidenticaltotheALTERTABLE...
DROPsyntax.SimplyreplaceDROPwiththekeywordsSETUNUSED,andthe
restisthesame.Forexample:
Note:intheaboveexample,ifthecolumnCRUISE_ORDER_DATEdoesn’t
alreadyexist,thestatementwillfailwithanerrormessage.Andaswesawwith
DROP,ifthecolumndoesexistandalsoisconstrained—ifthereisanexisting
constraintonthecolumn—theALTERwillfail.
AswithDROP,thesyntaxforchangingmultiplecolumnstotheUNUSED
staterequiresparenthesesandeliminatestheCOLUMNreservedword,likeso:
YoucansetasmanycolumnstoUNUSEDasyouwish.Theonlyrequirement
isthatyoumust,asyoumightguess,satisfyallconstraintsandother
requirementsofatableanditsstructure—forexample,thetablestillmusthave
atleastonevalidcolumnatanytime—soyoucannotsetallofitscolumnsto
UNUSED.
TablesthathaveanycolumnsthataresettoUNUSEDcanbefoundinthe
datadictionaryviewUSER_UNUSED_COL_TABS.However,thisviewdoesn’t
revealanycolumnnamesthatareunused;itsimplygivesyouthenamesofany
andalltablesthatcontainunusedcolumns,andanumericcountofhowmany
unusedcolumnseachonecontains.Youcannotrecovertheunusedcolumns,nor
canyouevenidentifythem.Butyoucandropthem.Todropthoseunused
columns,usethisstatement:
Forexample:
Thisstatementwilldropallunusedcolumnsthatareassociatedwiththetable
ORDER_RETURNS.
CERTIFICATIONOBJECTIVE2.07
CreateandUseExternalTables
Anexternaltableisaread-onlytablethatisdefinedwithinthedatabasebut
existsoutsideofthedatabase.Inmoretechnicalterms,theexternaltable’s
metadataisstoredinsidethedatabase,andthedataitcontainsisoutsideofthe
database.
Externaltableshaveanumberofrestrictionsonthem.Youcanquerythem
withtheSELECTstatement,butyoucannotuseanyotherDMLstatementson
them.Youcan’tcreateanINDEXonthem,andtheywon’tacceptconstraints.
Benefits
Sowhywouldyoucreateanexternaltable?Theirprimarybenefitistocreatean
easy-to-usebridgebetweenSQLtablesandnon-databasedatasources.Ifyou’ve
everusedtheOracletoolSQL*Loader,orDataPump,thenyou’llbepleasedto
discoverthattheexternaltablefeaturewasdesignedtoincorporatethe
functionalityfoundinthosetoolsintoaSQLcontext.
Agreatexampleiswhenyouhavesomenon-SQLdatasourcethatregularly
producesinformationneededinthedatabase,suchasaflatfiletransfer,aweb
sitereference,aspreadsheetapplication,alegacy3GLapplication,orsomething
comparable.Ifthatdatasourceiscapableofprovidingsomesortofformatted
flatfile,thenitcanbestructuredinsuchawaythatitcanbecopieddirectlyinto
afilethattheSQLexternaltablewillinstantlyrecognizeandbeabletoquery.In
otherwords,itwillcreateasortofone-waydatatransferintotheSQLdatabase,
butusingSQLSELECTstatementsinsteadofutilitiessuchasSQL*Loader.
CreatingExternalTables
Tocreateanexternaltable,youcandeclareitscolumnsandtheirdatatypes.You
canalsopopulatetheexternaltablewithasubqueryatthetimeyoucreateit.
Butthat’saboutallyoucandowithexternaltables.Theyarerestrictedina
numberofways:
YoucannotcreateacolumnwithaLOBdatatype—noCLOB,
BLOB,NCLOB,etc.
Youcannotaddaconstrainttoanexternaltable.
YoucannotchangethecolumnofanexternaltabletoUNUSED.If
youtry,SQLwillprocessthestatementbutwillactuallydropthe
column.
Essentially,allyoudowithanexternaltableisdeclareitsstructureanddefine
theparametersbywhichtheSQLdatabasecommunicateswiththeexternaltable.
Inordertoestablishthatcommunication,youmustfirstunderstandtwosubjects:
DIRECTORYobjects
TheOracleutilitiesSQL*LoaderandOracleDataPump
We’lllookatthosenext,andthenwe’llcreateanexternaltable.
DIRECTORYObjects
Tocreateanexternaltable,we’llneedtoidentifythelocationintheoperating
systemwheretheexternalfilecontainingthetablewillreside.Forthis,weneed
tolookattheCREATEDIRECTORYstatement.
TheCREATEDIRECTORYstatementcreatesanobjectinthedatabasethat
representsthenameofadirectoryontheserver’sfilesystem.Here’san
example:
CREATEORREPLACEDIRECTORYdirectory_nameAS
directory_reference;
wheredirectory_nameisanameyouspecify,justasyouwouldanyother
databaseobject,anddirectory_referenceisastringliteral,surroundedbysingle
quotationmarks,thatidentifiesalocationwithinyourOracleserver’sfile
system,intowhichyouwishforexternaltablestobestored.Forexample:
CREATEORREPLACEDIRECTORYBANK_FILESAS
'F:\bnk_files\trnsfr';
Theresultofthisstatementisthatwe’vejustcreatedanobjectinthedatabase
namedBANK_FILESthatlookstotheoperatingsystemwheretheOracleserver
residesandassumesthatthedirectoryreferenceinthestringliteralisconsistent
withthesyntaxrequiredforthatparticularoperatingsystem.Inthiscase,we’re
pointingtoaWindowsdrive“F:”anditsrootleveldirectory“bnk_files”,within
whichisthesubdirectory“trnsfr”—thatsubdirectoryisourtarget.
TheDIRECTORYobjectwillnotparsethisreferencebutinsteadwilljust
storeitasis.Ifit’sincorrect,youwon’tfindoutuntillaterwhenyoutrytouse
theDIRECTORYobject.
Also,theDIRECTORYobjectwillnotcreatethesubdirectory;the
assumptionhereisthatthesubdirectoryalreadyexists.Ifitdoesnot,youwon’t
getanerrormessageuntilyouusetheDIRECTORYobjectlater.
ThekeywordsORREPLACEareoptional.
Inourexample,thenameBANK_FILESisanamewespecify.Thisnameis
thenameassignedtotheobject,andthisnameishowwewillreferencethe
DIRECTORYobjectinthefuture.
Onceadirectoryhasbeencreated,theownermustgrantREADand/or
WRITEaccesstoanyuserwhomayuseit:
GRANTREADONDIRECTORYdirectory_nameTOusername;
Thatincludesuserswhomaywishtouseexternaltablesthatarebuiltwiththe
directoryobjects.
OracleUtilities
TheOracledatabaseprovidesanumberofutilitiesthataccompanytheir
databaseproduct.Thoseutilitiesthatareimportanttoexternaltablesinclude
SQL*Loader
OracleDataPumpExport
OracleDataPumpImport
EachisdocumentedintheOracleCorporationreferencemanualtitled
“OracleUtilities”.Together,theutilitiesprovidecapabilitiesthatallowexternal
datasourcestocommunicatewithSQLobjectswithinthedatabase.
Acompletereviewoftheircapabilitiesisbeyondthescopeoftheexamand
thereforethisbook.Butit’simportantfortheexamtorecognizethatalarge
componentofthedefinitionsassociatedwiththedeclarationofanexternaltable
comesfromtheseutilities.
CreatinganExternalTable
Let’swalkthroughanexample.Let’ssaywehaveanexternaltextfilecontaining
thefollowingdataaboutinvoices:
Wewanttocreateanexternaltableforthisdata;let’scallit
INVOICE_DATA.TXT.
First,wegotothefilesystemonwhichtheOracledatabaseresides,locatethe
samedrive,andwecreateasubdirectoryoffoftherootlevel.We’llcallit
“LOAD_INVOICES”.ThenwecreatetheassociatedDIRECTORYobject:
Bythispoint,wewon’tnecessarilyhavetohavecreatedthe
LOAD_INVOICESdirectory,nortohaveputtheINVOICE_DATA.TXTfilein
thatdirectory.Butforthesakeofourexample,nowwedoso,beforecontinuing.
Next,weexecuteaCREATETABLEstatementthatreferencesthedirectory,
alongwiththenecessaryclausestotellOracleSQLtoloadtheexternalfile,and
howtoloadit:
Oncethisstatementexecutes,weendupwithanexternaltableinthedatabase
calledINVOICES_EXTERNAL.
Notelines2through4wherewedeclaredourtableusingthedata
typesCHAR.You’llrecallthesearefixed-lengthdatatypes.Wedidthis
toaccommodatethetransferofrowsinfromthetextfileinlines12
through14.Eachcolumn’sdatatypeissettoCHAR,thefixed-length
alphanumericdatatype,andthecountsforeachdatatypecorrespondto
thecountsofthecolumnsinthetextfile‘INVOICE_DATA.TXT’,which
isidentifiedinline16andisinthedirectorystoredinthedirectoryobject
INVOICE_FILES,namedinline8.
Lines1through5formacompleteCREATETABLEstatementby
themselves,withouttheexternaltableclause.Butstartingonline6are
thekeywordsandclausesusedtodeclaretheexternaltable,andtogether,
lines1through17formthecompleteCREATETABLEstatementforour
example.
Line6includesthekeywordsORGANIZATIONEXTERNAL,
whicharerequired.
Line7iswherewespecifythatweareusingORACLE_LOADER,
akatheSQL*Loaderfeatures.AnalternativeTYPEvalueherewouldbe
ORACLE_DATAPUMP.
Line9beginsthesetofvaluesforACCESSPARAMETERS,which
areenclosedwithintheparenthesesthatopenonline10andcloseonline
15.
ThreeACCESSPARAMETERSareusedhere:RECORDS,SKIP,
andFIELDS.
Line10—RECORDSDELIMITEDBYNEWLINE—meansthat
eachnewlinestartsanewrowofdatafortheINVOICES_EXTERNAL
table.
Line11—SKIP2—tellsORACLE_LOADERthatthefirsttwolines
oftheINVOICE_DATA.TXTfilearetobeskipped—theyjustcontain
headerinformation.
Line12—FIELDS—startsthespecificationsforeachcolumn,where
eachcolumn’slengthiscarefullyspecifiedtomatchthelengthinthe
INVOICES_DATA.TXTfile.
ManymoreACCESSPARAMETERSexistthatarenotinvokedhere.Icould
probablywriteaseparatebookjustonalltheoptionsandfeaturesthatexistwith
thevariousclausesforthetypesORACLE_LOADERand
ORACLE_DATAPUMP.ButIwon’t,andyoushouldn’tneedthatfortheexam.
UsinganExternalTable
Oncewe’vecreatedanexternaltable,wecanSELECTfromitjustlikeanyother
table.Forexample:
Manyexternaltableswillstartwithsourcedatathatisroughandunformatted.
However,thefirststepisjusttogetitinthedatabase.Oncethatisaccomplished,
youcanusethevariousconversionfunctionsandotherfeaturesofSQLtoclean
upandreformatthedata:
Notetheoutput—thenumbersarereformatted,thedatevaluesareconverted,
theaccountnumbershavebeentrimmedup,andeverythinglooksterrific.
Externaltablescanbequeriedlikeanytableorviewinthedatabase.
RememberthatyoucannotuseINSERT,UPDATE,orDELETEstatements
onexternaltables.
CERTIFICATIONSUMMARY
Themaindatabaseobjectsthataresubjectsoftheexamincludetables,views,
sequences,synonyms,indexes,constraints,users,androles.Atablestoresdata.
Aviewissomethingthatlooksandactslikeatablebutservesasafilterontoone
ormoretables.Asequenceisacounter,andit’softenusedtogenerateunique
numbersforstoringidentifierswithnewrowsthatareaddedtoatable.A
synonymisanaliasforanotherobject.Anindexisanobjectthatprovides
lookupsupporttoatableinordertospeedupqueriesonthetable.Aconstraintis
aruleonatablethatcontrolswhatsortofdatacanbestoredinthetable.Auser
isanobjectthatdefinesauseraccount.Arolerepresentsasetofoneormore
privilegesthataregrantedtoauserinorderforthatusertohaveaccessrightsto
otherobjects.
Alldatabaseobjectsareeitherschemaornonschemaobjects.Schemaobjects
areownedbyauserandexistwithinauseraccount.Nonschemaobjectsexistto
supportthedatabaseatlarge.Ofthemaindatabaseobjectsyouarelookingatfor
theexam,theschemaobjectsaretable,view,sequence,privatesynonym,index,
andconstraint.Thenonschemaobjectsareuser,role,andpublicsynonym.
YouusetheCREATETABLEstatementtocreateatable,namethetable,
namethecolumns,assigndatatypestothecolumns,andoptionallycreate
variousconstraintstothetableaswell.
Objectsthatexistinthesamenamespacemusthaveuniquenames.Objects
thatexistindifferentnamespacesmayhaveduplicatenames.Indexeshavetheir
ownnamespacewithinaschema;sodoconstraints.Beyondthat,aschemahas
onenamespaceforthecollectivesetoftables,views,sequences,andprivate
synonyms.Outsideoftheschema,userandroleobjectsshareanamespacefor
theentiredatabase;publicsynonymshavetheirownnamespacefortheentire
database.
Columnsmustbeassignedadatatypewhentheyarecreated.Datatypes
includecharacter,numeric,anddatedatatypes.Characterdatatypesinclude
CHARandVARCHAR2;numericdatatypesincludeNUMBERandFLOAT;
datedatatypesincludeDATE,TIMESTAMP,TIMESTAMPWITHTIME
ZONE,TIMESTAMPWITHLOCALTIMEZONE,INTERVALYEARTO
MONTH,andINTERVALDAYTOSECOND.Therearealsolargeobject,or
LOB,datatypes,suchasBLOB,CLOB,andNCLOB.
ConstraintscanbecreatedwithintheCREATETABLEstatementor
afterward,intheALTERTABLEstatement.Theycanbecreatedinline,
meaningaspartofacolumn’sdefinition,oroutofline,meaningafterwardasa
separatelineitemwithintheCREATETABLEorALTERTABLEstatement.An
exceptionisNOTNULL,whichcannotbecreatedoutofline.
ThefivetypesofconstraintsareNOTNULL,UNIQUE,PRIMARYKEY,
FOREIGNKEY,andCHECK.
TheTRUNCATETABLEstatementcanbeusedinthosespecial
circumstanceswhereyoumaywanttoremovealltherowsofatablewithout
firinganyDMLtriggersorselectivelyremovingdatafromanyassociated
INDEXobjects,aswouldhappenwithaDELETEstatement.Insuchasituation,
TRUNCATETABLEisanattractivealternativetodroppingandre-creatinga
table,sinceitleavesthetableanditsrelationshipsintact,aswellasanyindexes.
TRUNCATETABLEcanremovestatementsmuchmorequicklywithless
processingoverheadthanDELETE.BecauseTRUNCATETABLEfiresno
DMLtriggers,itisconsideredDDL;therefore,itsuseperformsanimplicit
commit,anditsresultscannotberolledback.
IfTRUNCATETABLEisappliedtoatableforwhichthereexistsan
associatedparenttablewithaforeignkeyusingtheONCASCADEDELETE
clause,thenTRUNCATETABLEwillresultinanerrorifthereareinfactrows
inthatparenttablethatmightotherwisebedeletedasaresultofONCASCADE
DELETE.Forthissituation,youmustuseTRUNCATETABLE...CASCADE
toconfirmyourdesiretoremovethoseparentrows.
Columnscanbedroppedfromatable.Columnsthatarepartofareferential
constraint—inotherwords,aFOREIGNKEYconstraint—maybedroppedwith
theCASCADECONSTRAINTSkeywordsaddedsothattheconstraintsare
droppedaswell.ColumnsmaybesettoUNUSEDtorenderthemvirtually
dropped,butsparingtheprocessingoverheadrequiredtodropacolumn.An
UNUSEDcolumnisnolongeravailable,anditcanbedroppedlater.
Externaltablesexistoutsideofthedatabase.Theprocessthatsupportsthem
hasitsrootsandsyntaxintheSQL*Loadertool,buttheresultisatablethatcan
bedescribedjustlikeanyother.Externaltablescanbequeriedbutcannot
receivedatainputviaINSERT,UPDATE,orDELETE.
✓TWO-MINUTEDRILL
CategorizetheMainDatabaseObjects
Tablesstoredata.
Viewsserveasasortof“window”ontotables.
Indexesprovidelookupsupporttospeedqueriesonatable,likean
indextoabook.
Sequencesaresimplecounterobjects.
Synonymsarealternativenamesforexistingobjects.
Constraintsarerulesontables.
Usersareobjectsthatownothernonuserobjects.
Rolesaresetsofrights,orprivileges,thatcanbegrantedtoauser
togivethatuseraccesstootherobjects.
Objectsareeitherschemaornonschemaobjects.
Tables,views,indexes,sequences,andprivatesynonymsare
schemaobjects.
Usersandroles,alongwithpublicsynonyms,arenonschema
objects.
CreateaSimpleTable
TheCREATETABLEstatementisusedtocreateatable.
Youassignanametoatablebyusingtherulesofnamingdatabase
objects.
Youalsoassignnamestothetable’scolumnsusingthesamerules.
Alltableshaveatleastonecolumn.
ReviewtheTableStructure
TheDESCcommandcanbeusedtodisplayatable’sstructure.
Thestructureincludesthetablename,tablecolumns,datatypes,
andoptionalconstraints.
ListtheDataTypesThatAreAvailableforColumns
Eachcolumnmustbeassignedadatatype.
Datatypesincludenumeric,character,anddatetypes,suchas
VARCHAR2,NUMBER,andDATE.
Datatypesalsoincludelargeobjecttypes,includingBLOB.
ExplainHowConstraintsAreCreatedattheTimeofTable
Creation
ThetypesofconstraintsareNOTNULL,UNIQUE,PRIMARY
KEY,FOREIGNKEY,andCHECK.
AcolumnwithaNOTNULLconstraintmustbeassignedavalue
foreachrowthatisaddedtothetable.
AUNIQUEconstraintrequiresthatifdataisaddedtoacolumnfor
agivenrow,thatdatamustbeuniqueforanyexistingvaluealreadyin
thecolumn.
APRIMARYKEYconstraintisthecombinationofNOTNULL
andUNIQUE.
APRIMARYKEYmaybeassignedtoonecolumnora
combinationofcolumns.
APRIMARYKEYassignedtoacombinationofcolumnsiscalleda
compositekey.
AsingletablemayhaveonlyonePRIMARYKEY.
AFOREIGNKEYcorrelatesoneormorecolumnsinonetablewith
asetofsimilarcolumnsinasecondtable.
AFOREIGNKEYrequiresthatthesecondtablealreadyhaveeither
aPRIMARYKEYconstraintoraUNIQUEconstraintassignedtothe
correlatedcolumnsbeforetheFOREIGNKEYcanbecreated.
Oncecreated,theFOREIGNKEYensuresthatanyvaluesaddedto
thetablewillmatchexistingvaluesinthePRIMARYKEYcolumnsof
thesecondtable.
ConstraintscanbecreatedwiththeCREATETABLEstatementor
withintheALTERTABLEstatement.
Constraintscanbedefinedaspartofthecolumndefinitions(inline)
orafter(outofline).OneexceptionisthatNOTNULLcanbecreatedin
linebutnotoutofline.
DropColumnsandSetColumnUNUSED
TheDROPclauseofALTERTABLEcanbeusedtoremovea
columnfromatable.
OnceacolumnisremovedwithDROP,thedataislost.
Droppingacolumncanconsumesignificantprocessingtimeifthe
tableinvolvedcontainsalotofdata.
Ifyoudropacolumnwithaconstraint,theconstraintisalso
dropped.Thesameistrueforanyindexobjectsonthecolumn;theyare
alsodropped.
SETUNUSEDrendersacolumnpermanentlyunavailable;itcannot
berecovered.
TheSETUNUSEDclausecanbenefitalargetableinheavy
productionthatcannotaffordtheoverheadprocessingpowerofaDROP.
AfteratablehascolumnsthataresettoUNUSED,theycanbe
droppedwiththeDROPUNUSEDCOLUMNSclauseofALTER
TABLE.
CreateandUseExternalTables
Anexternaltableisaread-onlytablewithinthedatabasethatstores
dataoutsideofthedatabase.
Thecommunicationbetweentheexternaltable’sdatastoragefile
anddatabaseobjectsisbasedonthelogicofSQL*LoaderorOracle
DataPump.
YouuseadatabaseobjectknownastheDIRECTORYobjectaspart
ofthedefinitionofanexternaltable.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
CategorizetheMainDatabaseObjects
1.Atableiswhichofthefollowing?(Chooseallthatapply.)
A.Aschemaobject
B.Anonschemaobject
C.Arole
D.Alloftheabove
2.Whichofthefollowingareschemaobjects?(Chooseallthatapply.)
A.SEQUENCE
B.PASSWORD
C.INDEX
D.ROLE
3.ACONSTRAINTisassignedtowhichofthefollowing?(Chooseall
thatapply.)
A.TABLE
B.SYNONYM
C.SEQUENCE
D.INDEX
CreateaSimpleTable
4.WhichofthefollowingarevalidCREATETABLEstatements?
(Choosethree.)
5.Whichofthefollowingoptionscanbeusedwiththereservedword
CREATEtoformthebeginningofacompleteSQLstatement?(Choose
three.)
A.TABLE
B.VIEW
C.CONSTRAINT
D.SEQUENCE
6.YouareloggedintouserFINANCE.Itiscurrentlytheonlyschemain
theentiredatabase.Thefollowingexistinthedatabase:
–AVIEWnamedVENDORS
–ACONSTRAINTnamedVENDORS
–AnINDEXnamedCUSTOMER#ADDRESS
YouattempttoexecutethefollowingSQLstatement:
Whichoneofthefollowingistrue?
A.ThequestionisflawedbecauseyoucannothaveanINDEX
namedCUSTOMER#ADDRESS.
B.ThequestionisflawedbecauseyoucannothaveaVIEWanda
CONSTRAINTwithidenticalnamesinthesameschema.
C.TheSQLstatementwillfailtoexecuteandresultinanerror
messagebecauseyoucannotcreateaTABLEnamewiththe#
character.
D.TheSQLstatementwillfailtoexecuteandresultinanerror
messagebecauseyoucannotcreateaTABLEthathasthesamename
asanINDEXinthesameschema.
E.TheSQLstatementwillexecute,andtheTABLEwillbecreated.
7.Youhaveasingledatabase,withonlyoneschema.Thefollowingfour
objectsexistinthedatabase:
–ATABLEnamedPRODUCT_CATALOG
–ATABLEnamedADS
–AUSERnamedPRODUCT_CATALOG
–AVIEWnamedCONFERENCE_SCHEDULE
Howmanyofthefourobjectsareownedbytheschema?
A.0
B.2
C.3
D.4
8.WhichofthefollowingistrueaboutROLES?
A.Rolesareschemaobjectsbutonlywhencreatedfromwithina
useraccount.
B.RolesareinthesamenamespaceasCONSTRAINTS.
C.RolesareinthesamenamespaceasTABLES.
D.RolesareinthesamenamespaceasUSERS.
ReviewtheTableStructure
9.TheDESCcommandcanbeusedtodowhichofthefollowing?
A.Showatable’scolumnsandthedatatypesofthosecolumns
B.Showabriefparagraphdescribingwhatthetabledoes
C.Showatable’snameandwhocreatedit
D.Showthedatathatiscontainedwithinatable
ListtheDataTypesThatAreAvailableforColumns
10.YouattempttoexecutethefollowingSQLstatement:
Whichoneofthefollowingistrue?
A.Theexecutionfailsbecausethereisnoprecisionindicatedfor
NUMBER.
B.Theexecutionfailsbecausethereisnoprecisionindicatedfor
VARCHAR2.
C.Theexecutionfailsbecausethereisnoprecisionindicatedfor
CHAR.
D.Theexecutionsucceeds,andthetableiscreated.
11.ThefollowingSQLstatementscreateatablewithacolumnnamedA,then
addarowtothattable,thenquerythetable:
WhatisthedisplayedoutputoftheSELECTstatement?
A.3.1415
B.3.142
C.3.141
D.Noneoftheabove
ExplainHowConstraintsAreCreatedattheTimeofTable
Creation
12.WhichofthefollowingSQLstatementscreatesatablethatwillreject
attemptstoINSERTarowwithNULLvaluesenteredintothe
POSITION_IDcolumn?
13.ReviewthefollowingSQLstatement:
AssumethereisnotablealreadycalledSHIPPING_ORDERinthe
database.Whatwillbetheresultofanattempttoexecutethepreceding
SQLstatement?
A.ThestatementwillfailbecausethedatatypeforORDER_YEAR
isaCHAR,andCHARdatatypesaren’tallowedinaPRIMARY
KEYconstraint.
B.Thestatementwillfailbecausethereisnoprecisionforthe
ORDER_IDcolumn’sdatatype.
C.Thetablewillbecreated,buttheprimarykeyconstraintwillnot
becreatedbecausethenamedoesnotincludethe_PKsuffix.
D.Thestatementwillsucceed:thetablewillbecreated,andthe
primarykeywillalsobecreated.
14.ReviewthefollowingSQLstatement:
AssumethereisnotablealreadycalledPERSONNELinthedatabase.
WhatwillbetheresultofanattempttoexecutetheprecedingSQL
statement?
A.Thestatementwillfailbecauseyoucannotcreatetwoprimary
keyconstraintsonthetable.
B.Thestatementwillsuccessfullycreatethetableandthefirst
primarykeybutnotthesecond.
C.Thestatementwillsuccessfullycreateasingletableandone
compositeprimarykeyconsistingoftwocolumns.
D.Thestatementwillsuccessfullycreatethetableandtwoprimary
keys.
DropColumnsandSetColumnUNUSED
15.ThedifferencebetweendroppingacolumnfromatablewithDROPand
settingacolumntobeUNUSEDis:
A.AnUNUSEDcolumncanberecovered.
B.TheUNUSEDcolumnanditsdataareretainedwithinthetable’s
storageallocationandcountsagainstthetotallimitonthenumberof
columnsthetableisallowedtohave.
C.AcolumnthatisdroppedwithDROPnolongerappearswithin
thetable’sdescriptionasshownwiththeDESCorDESCRIBE
statement,whereasacolumnthatissettoUNUSEDstillappearsin
thetable’sstructureasshownintheoutputoftheDESCstatement.
D.Nothing.
CreateandUseExternalTables
16.ThepurposeoftheCREATEDIRECTORYstatementistocreateanamed
objectinthedatabase:
A.Thatlistsnamesofuseraccountsthathaveexternalprivileges
B.Thatcontainslookupreferencematerialforqueries
C.ThatidentifiestherootdirectoryoftheOracleserverinstallation
D.Thatpointstoadirectoryyouchoosesomewherewithinthe
Oracleserver’sfilesystem
SELFTESTANSWERS
CategorizetheMainDatabaseObjects
1. A.Alldatabaseobjectsareeitherschemaornonschemaobjects,and
atablefallsunderthecategoryofschemaobjects.
B,C,andDareincorrect.Atable,whichisaschemaobject,isnota
nonschemaobject.Aroleisanotherformofadatabaseobject.
2. AandC.Asequenceandanindexarebothschemaobjects.They
areownedbyaschema.
BandDareincorrect.Apasswordisnotadatabaseobject.Arole
consistsofoneormoreprivilegesthatareassignedtoauserobject,and
boththeuserandroleobjectsarenonschemaobjects.
3. A.ACONSTRAINTisarulethatrestrictswhatsortofdatacanbe
addedtoatable.
B,C,andDareincorrect.Youcannotattachaconstrainttoasynonym,
sequence,orindexobject.
CreateaSimpleTable
4. B,C,andD.Underscoresareacceptablecharactersinanydatabase
tablename,providedthatifthenameisunquoted,thefirstcharacterisnot
anunderscore.Quotationmarks,whenused,enableanycharactertobe
usedthroughoutthename,includingspaces,althoughallfuturereferences
tothenamewillbecase-sensitiveandrequirequotationmarks.Finally,
mixedcasecanbeusedtocreateatablename,althoughwhencreated,the
tablenamewillbestoredandtreatedasuppercase.Allfuturereferencesto
thenamemaycontinuetobeinanycase—SQLwillperformthenecessary
caseconversionsothatthetablename,onapracticallevel,istreatedas
thoughitiscase-insensitive,eventhoughitisstoredinternallyin
uppercase.
Aisincorrect.Thefirstcharacterinanydatabaseobjectnamemustbea
letter;itcannotbeanumberorspecialcharacter—unlessthenameis
enclosedindoublequotationmarks,whichthiswasnot.
5. A,B,andD.ThedatabaseobjectsTABLE,VIEW,andSEQUENCE
caneachbecreateddirectlywithaCREATEreservedwordtoforma
completeSQLstatement.
Cisincorrect.ACONSTRAINTisnotcreateddirectlywithaCREATE
CONSTRAINTstatementbutinsteadiscreatedindirectlyasaclausewithin
theCREATETABLEandALTERTABLEstatements.
6. E.Thetablenamemayincludethe#character,aslongasitisn’tthe
firstcharacterinthetablename.AnINDEXinthesameschemaisallowed
tohavethesamenamesincetheINDEXisinsideitsownnamespacewithin
theschema,separatefromthenamespaceinwhichtheTABLEwillbe
created.
A,B,C,andDareincorrect.Thequestionisnotflawed—thehashmark
(#)isanacceptablecharacterinanobjectnameanywherefromthesecond
characterpositionthroughtothefinalcharacter.Youareallowedtohavea
VIEWandaCONSTRAINTwiththesamenameswithinasingleschema,
sinceCONSTRAINTSarecontainedwithintheirownuniquenamespacein
eachschema.
7. C.TABLEandVIEWobjectsareschemaobjects,andsinceyou
haveonlyoneschemainthedatabase,thenbothhavetobeownedbythe
onlyschemainthedatabase.ButtheUSERobjectisanonschemaobject.
Infact,inthisone-schemadatabaseitmustbetheschemathatownsthe
otherobjects.Itdoesnotownitself,anditexistsatthedatabaselevel.
A,B,andDareincorrect.
8. D.BothROLESandUSERSexistatthedatabaselevelandshare
thesamenamespace.
A,B,andCareincorrect.Itdoesn’tmatterthataROLEiscreatedfrom
withinaschema’suseraccount;it’sstillanonschemaobjectandexistsin
thesamenamespace.CONSTRAINTSandTABLESbothhavetheir
namespaceswithinaschema.
ReviewtheTableStructure
9. A.DESC,orDESCRIBE,presentsadisplayshowingatable’s
columnsandthedatatypesofthosecolumns.
B,C,andDareincorrect.TheDESCcommanddoesn’tshowdata,the
creator,oratextdescriptionofthetable.Allofthatinformationisavailable
throughothermeans,nottheDESCcommand.
ListtheDataTypesThatAreAvailableforColumns
10. B.TheVARCHAR2datatyperequiresprecision,forexample,
VARCHAR2(30).
A,C,andDareincorrect.NUMBERandCHARcanbedeclared
withoutprecision.ButVARCHAR2cannot,andthestatementwillfail.
11. B.TheNUMBERdatatypehasaprecisionof5andascaleof3.Thescale
indicatesthatthreedigits—butnomorethanthreedigits—totherightof
thedecimalpointareallowed.Thenumberisroundedoff,and5isalways
roundedup.
A,C,andDareincorrect.
ExplainHowConstraintsAreCreatedattheTimeofTable
Creation
12. B.Theprimarykeyconstraintperformstwomainjobs,oneofwhichisto
ensurethatthecolumnuponwhichitisappliedisneverallowedtobe
NULL.Theotherjobistoensurethatanyvalueaddedtothatcolumnis
UNIQUE.
A,C,andDareincorrect.TheUNIQUEconstraintallowsforNULL
values.ThereisnosuchthingasaREQUIREDconstraint.ThereisaNOT
NULLconstraintthatessentiallydoeswhataREQUIREDconstraintmight
do,ifoneexisted.However,thisparticularformofconstraintcreationis
theout-of-lineform,andtheNOTNULLconstraintcannotbecreatedwith
theout-of-lineform,butratherthein-lineform.
13. D.Thesyntaxofthestatementisfine.Boththetableandtheprimarykey
constraintwillbesuccessfullycreated.
A,B,andCareincorrect.Itisperfectlyacceptabletocreateaprimary
keyinanyform—single-columnorcomposite—withtheCHARdatatype.
NUMBERisalsofinewithorwithoutprecisionand/orscale.The_PK
suffixisnotrequired.
14. A.Thestatementisattemptingtocreatetwodifferentprimarykey
constraints,butatablemayhaveonlyoneprimarykeyandnomore.The
statementwillfailwithanerror.
B,C,andDareincorrect.Thesyntaxisnotattemptingacomposite
primarykeybutrathertwoseparateprimarykeyconstraints,andthatisnot
allowedonanytable.Theentirestatementwillfailtoexecute.
DropColumnsandSetColumnUNUSED
15. B.TheUNUSEDcolumnisstillstoredaspartofthetable.There’sno
storagebenefittothetable—nospaceisreclaimedfromanunusedcolumn.
A,C,andDareincorrect.NeitheracolumndroppedwithDROPnoran
UNUSEDcolumncanbeseeninthetable’sstructure.Acolumn,onceset
toUNUSED,canneverberecovered.Itcanonlybedropped.
3
ManipulatingData
T
CERTIFICATIONOBJECTIVES
3.01TruncateData
3.02InsertRowsintoaTable
3.03UpdateRowsinaTable
3.04DeleteRowsfromaTable
3.05ControlTransactions
✓Two-MinuteDrill
Q&ASelfTest
hischapterbeginstolookatthatpartofSQLknownasDataManipulation
Language.We’llgetsomeperspectivebylookingatDMLwithregardto
whereitfitsintothelargercontextofSQL.ThenwewillreviewDML
statementsandtheirusageandlookatsomespecificexamples.Finallywewill
reviewsomesupplementalstatementsthatareusedtocontroltransactions
involvingDML.
CERTIFICATIONOBJECTIVE3.01
TruncateData
Wheneveryouneedtoremoveoneormorerowsfromatable,theDELETE
statementisgenerallyyourbestchoice.ButDELETEmaynotbeidealinevery
situation.Forexample,let’ssayyourtableisequippedwithindexestospeedup
queryingandwithtriggerstoprotectthelogicalintegrityofthedatainthetable.
Thoseareallgreat,butifyourtablealsohasalargenumberofrows,thena
DELETEstatementwillinvokerow-by-rowprocessingtoreviewandupdate
eachindexandfireallappropriatetriggersonarow-by-rowbasis.There’s
nothingwrongwiththat,ofcourse;infact,there’severythingrightaboutit.This
iswhatawell-designeddatabasemightneedtodo,dependingonitsbusiness
requirements.
Butincertaincircumstanceswhereyousimplyneedtoremovealltherowsin
thetable,youmayfindthatallthatdetailedprocessingisunnecessary;youmay
needtosimplyremoveallthedata.
Insuchascenario,youmightconsiderthealternativeofdroppingthetable
andthencreatingitagain.Butifyouweretodothat,youwouldalsohavetore-
createthetable’sindexesandtriggers.Dependingonthetable’srelationships
withothertables,theextraworkrequiredtomakethisallhappencouldgrow
considerably.Inanattempttobypasssomeunnecessaryprocessingofa
DELETEstatement,youmaybeinadvertentlycreatingagoodamountof
otherwiseunnecessaryrework.YetDELETEmayitselfimpactperformanceona
largeproductiondatabase.
ThisiswhereTRUNCATETABLEcomesin.TheTRUNCATETABLE
statementdoesthefollowing:
Removesalltherowsinagiventable
Removesalldataintheassociatedindexes
FiresnoDMLtriggers
ByavoidingtheDROPTABLE/CREATETABLEapproach,using
TRUNCATETABLEdoesthefollowing:
Leavesthetableandindexstructuresintact
Leavesalldependenciesintact,suchaschildtables
TRUNCATETABLEalsodoesthefollowing:
DoesnotleverageundospacelikeDELETEwoulddo
Performsanimplicitcommit
RequirestheDROP_ANY_TABLEprivilege
Becauseoftheimplicitcommit,TRUNCATETABLEdoesthefollowing:
Cannotberolledback
DoesnotworkwithFLASHBACK_TABLE
IsconsideredDDL
ThefactthatTRUNCATETABLEisDDLiswhyTRUNCATETABLEdoes
notfireanyDMLtriggers,suchasONDELETE,whichdoesnotapply.
Thefollowingisanexampleofastatementthatwilltruncatethetable
VENDORS:
TRUNCATETABLEVENDORS;
ThekeywordTRUNCATEisfollowedbytherequiredwordTABLE,which
isfollowedbythenameofthetable.(ThekeywordTABLEisrequiredbecause
TRUNCATEmayalsobeusedtotruncateanotherobjectcalledacluster,which
isnotontheexam,sowearenotconcernedwithithere.)Thisuseof
TRUNCATETABLEwillremoveallthedatafromtheVENDORStable,aswell
asitsindexes,andautomaticallyperformacommittothedatabase.
RecursivelyTruncateChildTables
Oracle12coffersanewfeaturewithTRUNCATETABLE,whichistheoption
toCASCADEthetruncationtodependentchildtables:
TRUNCATETABLEVENDORSCASCADE;
Earlierwelookedathowaparent-childtablerelationshipcanbecreatedwith
aforeignkeyconstraintwiththeoptionalONDELETEclause,whichtellsthe
databasetotakespecificactiononachildrowifandwhenaparentrowis
removedfromtheparenttable.TheTRUNCATETABLEstatement’s
CASCADEworksinasimilarfashion.
Let’slookagainattheexamplesofthetablesPORTSandSHIPS(line
numbersadded):
NotetheONDELETECASCADEclauseonline14.Nowlet’saddsome
rowstothetables:
We’vecreatedaportforAtlanta,andashipisassignedtoAtlanta.Butthen
someonepointsoutthatAtlanta,whileabeautifulcity,islandlocked,soperhaps
weshouldn’ttrytoportashipthere.ClearlyweneedtoremoveAtlantafromthe
PORTStable.
WecouldsimplyDELETEtherow:
TheDELETEstatementwillremovealltherowsfromPORTS,andrightnow
thereisonlytheonerowfortheAtlantaport.Butitwillalsodeleteanyrowsfor
SHIPSassignedtotheAtlantaport,thankstotheONDELETECASCADE
clauseincludedintheSHIPStable’sforeignkeyconstraint(seeline14inthe
previouscodelisting).
If,insteadofDELETE,weneededtouseTRUNCATETABLE,thenwe
couldtrythis,butitwillnotwork:
WiththepresenceofrowsinPORTSforwhichtherearecorresponding
HOME_PORT_IDvaluesinSHIPSandbecauseSHIPSistiedtoPORTSusing
theONDELETECASCADEclause,thissetsuptheriskthatrowsinSHIPS
mayhaveHOME_PORT_IDvaluesthatcorrespondtoPORT_IDvaluesin
PORTS.Sureenough,thatisthecase,resultinginanerrormessagewiththe
TRUNCATETABLEstatementearlier:“ORA-02266:unique/primarykeysin
tablereferencedbyenabledbyforeignkeys.”TogetTRUNCATETABLEto
workinthissituation,weneedtheCASCADEclause.
WithoutCASCADE,theOracledatabasewillnotcompletetheTRUNCATE
TABLEstatementsincetheONDELETECASCADEclauseinaseparatechild
tablewouldforcetheremovalofadditionalrowsofdatabeyondjustthePORTS
table.TheTRUNCATETABLE…CASCADEstatementtellstheOracle
databasetogoforwardwiththeremovalofthoserowsanyway.
NotethatweneedednosuchadditionalclausewithDELETE.Thepresence
ofONDELETECASCADEcausestheadditionalrowstoberemovedwithno
additionaldirectionfromtheDELETEstatement.ButtheTRUNCATETABLE
statementhastheadditionalrequirementfortheCASCADEclause.Remember,
thisappliesonlytosituationswhereachildtablehastheONDELETE
CASCADEclauseofitsforeignkeyconstraint.
CERTIFICATIONOBJECTIVE3.02
InsertRowsintoaTable
TheSQLstatementtoaddrowstoatableistheINSERTstatement.TheINSERT
statementisoftenusedtoaddonerowatatime,butitmayalsobeusedtoadd
multiplerowsatoncebydrawingthemfromelsewhereinthedatabaseand
addingthemtothetargettablewithasingleINSERTstatement.INSERTmay
useexpressions.
INSERTaddsrowsintoaTABLEobject,butitcanalsobeusedwithcertain
VIEWobjects.However,aswewillsee,aVIEWissimplyafilterontooneor
moretables,soultimatelyINSERTisstilladdingrowstoaTABLEobject.
DefaultColumnList
Let’slookatanexampleofanINSERTstatement.We’regoingtoaddarowto
theCRUISEStable.First,let’sdescribetheCRUISEStablesothatwecansee
thecolumns—we’llneedtoknowthenamesanddatatypesofthosecolumnsso
wecanbuildourINSERTstatement(seeFigure3-1).
FIGURE3-1 TheCRUISEStable
Here’sanexampleofanINSERTstatementyoucoulduseonthistable:
AswithallSQLstatements,theINSERTstatementcanbeonasingleline,or
itcanspanmultiplelines.Thechoicedoesn’tmatterasfarasthesyntaxis
concerned.Weseparatedthecomponentsoftheprecedingstatementinorderto
discussitmoreeasilyhere.Thestatementendswithasemicolon,whichisatthe
endofline8inthisexample.
Let’sanalyzethesyntaxforthisexampleofINSERT:
Line1ThereservedwordsINSERTandINTO,followedbythe
nameofthetargettable.
Lines2–4Withinasetofparentheses,alistofthetable’scolumns.
Theorderinwhichthecolumnsappeardoesnotneedtomatchtheorder
ofcolumnsinthetable’sstructureasshownwiththeDESCcommand,
nordoesitneedtoincludeallofthetable’scolumns,aslongaswe
provideforallofthe“required”columns,inotherwords,thosewitha
NOTNULLconstraintorsomethingcomparable(likethePRIMARY
KEYconstraint).AnycolumnassignedaDEFAULTvaluemaybe
omittedfromthelist.
Line5ThereservedwordVALUES.
Lines6–8Withinasetofparentheses,aseriesofvaluestobeadded
toeachofthecolumnslistedin—inthisexample—lines2–4.Valuesare
expressionsandarelistedinthesameorderaseachvalue’s
correspondingcolumnlistedinlines2–4.Forexample,thefirstvaluein
thisliststartinginline6willbecomethevalueforthefirstcolumn
identifiedonline2,thesecondvalueidentifiedinline6willbeinserted
intothesecondcolumnidentifiedinline2,andsoon.
WhentheINSERTstatementissubmittedforexecution,thefollowingsteps
willbeperformedbeforethestatementreturnsanyresults:
Theexistenceandvalidityofthetableinline1willbeconfirmed.
Theexistenceandvalidityofthecolumnsinlines2–4willbe
confirmed.
Theexpressionsinlines6–8willbeevaluated.
Thedatatypesoftheexpressionsinlines6–8willbecompared
againstthedatatypesoftheassociatedcolumnsandevaluatedfor
compatibility.
Thevaluesoftheexpressionsinlines6–8willbeappliedtoany
constraintsthatmightexistinthetable.
Ifallrequirementsfordataentrytothetargettablearesatisfiedandthe
INSERTstatementisdeterminedtobevalid,thenthestatementwillexecute,and
therowwillbeinsertedintothetable.
Inthisexample,thecolumnsinourINSERTstatement(lines2–4)justhappen
toaccountforeverycolumninthetable’sstructureandinthedefaultsequence
ofhowthecolumnsexistinthetable.Inthissortofsituation,thecolumnlistat
thebeginningoftheINSERTstatementisnotrequired.Inotherwords,wecould
haveomittedlines2–4inthisexample;thefollowingisavalidalternativetothe
INSERTstatementwejustreviewed:
Thisexamplewillproducethesameresultbecausetheexpressionsinlines3–5
justhappentocoincidewiththecolumnsintheCRUISEStable,innumber
(thereareseven)andindatatype,aswesawinFigure3-1.Ifthatstructure
changes,thepreviousstatementmayfail.Forexample,ifanewcolumnisadded
toCRUISES,thepreviousexamplewillfail,whereasthepriorINSERT
example,whichnamesthecolumns,willprobablycontinuefunctioning
correctly.
INSERTmustrespectalldatatypesandconstraintsinthetargettable.
Nowyouaresurelyaskingyourselfwhichisbetter:(a)toidentifythecolumn
listbynameor(b)toleveragethedefaultapproach,omitthelistofcolumn
names,andsimplyaccountforallofthetable’scolumnsinthelistofvalues?
Theanswerisitdependsonthesituation.Generallyspeaking,inmyexperience,
Itendtoprefer(a),whereyounameeachcolumnspecificallyanddonotdepend
onthedefault.Thereareseveraladvantagestothisapproach.Oneadvantageis
thatyourcodewillstillexecutesuccessfullyifthecolumnsinthetableare
alteredinvariousways.Forexample,ifthetableisdroppedandre-createdin
somesortoffutureupgradeormaintenanceeffort,thecolumnscouldendupina
differentsequence.ThatcouldtriggerasyntaxerrorwiththedefaultINSERT,or
itcouldresultinsomethingworse—nosyntaxerrorbutacolumnmismatch
wherethedatatypeshappentolineupandtheINSERTstatementworks
technicallybutisn’tputtingthedatainthecolumnsyouoriginallyintended.
Forexample,considertheSQLstatementsshowninFigure3-2.Herewesee
atablecalledTEST_SCORESandanINSERTstatementforit.Notethatthe
INSERTusesthedefaultcolumnlist.There’snothingwrongwiththat—
technically.ButnowlookatFigure3-3.NoticethattheTEST_SCORES
columnsareinadifferentorder.YetthesameINSERTstatement—withthe
syntaxthatdoesnotlistcolumnsbyname—successfullyexecutes.Why?
BecauseSQLseesonlythedatatypesofthelistofvaluesintheINSERT
statement.Inthiscase,bothvaluesbeinginsertedarenumericliterals,and
numericliteralsareacceptableineithercolumn.So,whatistheintenthere?Is
100thevalueforTEST_SCORE_IDand85thevalueforSCORE?Orisitthe
otherwayaround?Thepointisthatyoucannottellinthisparticularvariationof
INSERTstatementsyntax.
FIGURE3-2 TheTEST_SCOREStable
FIGURE3-3 TheTEST_SCOREStablewithadifferentstructure
Byalwaysenumeratingthelistofcolumnnames,youcanavoidany
confusion.However,thereisoneissuetokeepinmind:if,inthefuture,thetable
intowhichyouareinsertingvaluesmightbemodifiedinsuchawaythatnew
columnsareaddedtoit,thenyou’llneedtoremembertorevisitINSERT
statementslikethisandeditthemifnecessary.Ifyou’veenumeratedacolumn
listandthetableislateralteredwiththeadditionofnewcolumns,thenbarring
anyconstraintsortriggersthatmightyieldastatementfailure,youroldINSERT
statementwillcontinuetofunctionnormally;itjustwon’tprovidedataforthe
newcolumns.ButinalltheprofessionalsituationsI’veencountered,thesetypes
ofissuesarelessproblematicandeasiertoresolvethantheproblemofdatatype
matchesthatsupportillogicaldataentry.Themoralofthisstoryistoalways
identifyyourcolumnnamesinanINSERTstatement.
EnumeratedColumnList
TheINSERTsyntaxwejustreviewedassignsvaluestoeachcolumninthetable.
Itaccomplishesthatfeatbyfirstlisting,byname,eachcolumninthetable,in
thesameorderinwhichthecolumnsappearinthetable’sstructure.Butyouare
notrequiredtolistthecolumnsinorder.Here’sanexample:
ThisisavalidINSERTstatement.Noticehowinlines2–3welistthe
columnsinadifferentorderfromthetablestructure.Thisisfine,solongasthe
listofexpressionstobeinserted(lines5and6)areintheorderasthecolumnlist
(lines2and3).Theyareasfollows:
AnotherchangewiththisINSERTisthatwedonotincludeeverycolumnin
thetable.WeignorethecolumnCRUISE_TYPE_ID.That’salsofine,provided
thatallrequiredcolumnsareincluded,andinthisparticulartable,wehavetwo
columnsthatareNOTNULL,andbothareincludedinthisINSERTstatement.
DataTypeConversion
WhentheINSERTstatementisevaluatedforsyntacticalcorrectness,thedata
typesofthevalueslistedinlines5–6willbecomparedtothedatatypesofthe
columnsidentifiedinlines2–3.Thedatatypesmustbecompatible.Butthe
operativewordhereiscompatible,notidentical.Forexample,thisworks:
Noticethatthe101valueinline2isinquotationmarks,identifyingthatvalue
asastringliteral.Normallythatisusedfortext,andinthiscasethetextisbeing
assignedtothecolumnCAPTAIN_ID,whichacceptsonlynumericdata.Butno
errormessageoccurs,andthisINSERTwillexecute.ThereasonisthatOracle
SQLissmartenoughtofigureoutthatthetextcontainedwithintheliteralvalue
inthissituationhappenstobenumericdata.Thestatementwillexecute
successfully.
ThisfeatureisknowninOracledocumentationasimplicitdatatype
conversion.OracleCorporationformallyadvisesthatsoftwaredevelopersavoid
dependingonimplicitdatatypeconversioninapplicationdevelopmentandrely
insteadonexplicitdatatypeconversion,whichwe’lllookatwhenwereview
SQLconversionfunctionssuchasTO_CHAR,TO_NUMBER,andTO_DATE.
Theruleofthumbisthatwhereveritmakessense,OracleSQLwillperform
animplicitdatatypeconversionifatallpossible.Naturallyitcannotconvert
somethinglike'Montana'toaDATEdatatype.Butifyoutrytoenteranumeric
valuesuchas2011intoadatatypesuchasVARCHAR2,animplicitdatatype
conversionwillconvertthevalueof2011to'2011'andthestatementwill
succeed.
INSERTandConstraints
Ifwehappentoincludedatathatviolatesaconstraint,thenwemightgetarun-
timeerror.Thispointbearsreiteration:violationofaconstraintisarun-time
error.Inotherwords,itisnotasyntaxerror.Forexample,let’ssaywewritethe
followingCREATETABLEstatement:
ThistableincludesaCHECKconstraintthatwilllimitanyvaluesfor
CRUISE_NAMEtooneofthelistedstrings:'Hawaii','Bahamas','Bermuda',
'Mexico',or'DayatSea'.Anythingelsewillberejected.
Next,let’speekaheadalittlebitandcreateaSEQUENCEobject,likethis:
ThisCREATESEQUENCEstatementcreatesanobjectthatwilldispense
individualvalues,andwe’lluseittogenerateprimarykeyvaluesforour
INSERTstatements.
Next,let’susethatSEQUENCEobjectandissuethefollowingINSERT
statement:
ThisINSERTstatementaddsasinglerowtotheCRUISEStable.Thenewrow
consistsoftwovalues.Inline4,thefirstvaluecallsonthenewlycreated
SEQUENCEobjectandasksforthenextavailablevaluefromthesequence,
indicatedwiththereservedwordNEXTVAL.Giventhatoursequenceisnew
anditwascreatedwithallthedefaultsettingsandhasneverbeenusedbefore,
thenthenextavailablevaluewillbe1.Thesecondvaluewe’reinsertinghereis
theliteralstring'Hawaii',whichissyntacticallycorrect,anditalsosatisfiesthe
constraintobjectattachedtotheCRUISE_NAMEcolumnintheCREATE
TABLEstatement.
However,hadweviolatedtheconstraint,theINSERTcouldbesyntactically
correctbutlogicallyincorrect.Forexample,considerthisvariationonthesame
INSERTstatement:
Inthisexample,thestring'HawaiiandBack'violatestheCHECKconstraint
wecreatedfortheCRUISEStable.Therefore,eventhoughthisversionofthe
INSERTstatementissyntacticallycorrect,itwillfailonexecution,andthe
CHECKconstraintwillrejecttheattempttoenterthisrow.SeeFigure3-4fora
sampleoftheexecutionerrorresultingfromthisINSERTstatement—thisis
shownintheSQLDevelopertoolinsteadoftheSQL*Plustoolthatyouhave
seenuptonow.
FIGURE3-4 ExecutionerrorfortheINSERTstatement
NotetheORA-02290run-timeerrormessage.TheCHECKconstraintis
identified,andyoucanseeinthisdisplaythatI’mloggedintothe
EFCODD_TESTuseraccount.
It’salsoworthnotingthateventhoughtheINSERTstatementfailed,the
sequencegeneratoradvancedbyone.Anyattempttoinvokeasequence
generatorwilladvancethenumbercount,eveniftheDMLstatementfails.
We’refarfromdonewithINSERT,andwewilladdressmoreadvanced
conceptsofINSERTinlaterchapters,whenwelookatsubqueries(Chapter9)
andlargedatasets(Chapter13).Butfirst,let’slookattherestofthemajorDML
statements.
CERTIFICATIONOBJECTIVE3.03
UpdateRowsinaTable
TheUPDATEstatementisaDMLstatementthatisusedtomodifyexistingdata
inthedatabase.Itoperatesononetableatatime.Itisusedtomodifyoneor
morecolumnsofdataandcanbeusedtochangealltherowsinatable,oritcan
beusedtochangedatainonlyselectedrows.
AswithINSERT,theUPDATEstatementcanalsoworkwithcertainVIEW
objectstoupdatedataintheTABLEobjectsuponwhichtheVIEWobjectsmay
beconstructed.We’lllookatthismorelaterwhenwediscussVIEWobjects.
Let’slookatanexampleofUPDATE:
ThisUPDATEwilllookforanyandallexistingrowsintheCRUISEStable
wherethevalueforCRUISE_IDequals1.Forallofthoserows,itwillchange
thevalueforCRUISE_NAMEto'Bahamas'andchangethevaluefor
START_DATEto'01-DEC-11'.
WhenwesaytheUPDATEstatementwill“change”thosevalues,this
exampleofUPDATEdoesn’tcareifthecolumninquestionisalreadypopulated
withdataoriftheexistingvalueisNULL.Eitherway,UPDATEwilloverwrite
whateverelsemayormaynotalreadybethereandplacethenewvalueinthe
column.
Let’slookalittlemorecloselyatthesyntaxofthisUPDATEstatement:
Line1ThereservedwordUPDATE,followedbythenameofthe
targettable
Lines2–3OneoccurrenceofthereservedwordSET,followedbya
seriesofoneormoreexpressionsconsistingofthesefourelements:
Acolumnname
Theassignmentoperator(=)
Anexpressionresultinginavaluecompatiblewiththecolumn’s
datatype
Eitheracomma,ifadditionalexpressionsaretofollow,or
nothing,ifthelistofexpressionsiscompleted
Line4AnoptionalWHEREclause,definingaconditiontoidentify
rowsinthetable
Nowthatwe’vereviewedoursampleUPDATEindetail,let’sobserveafew
importantissuesabouttheUPDATEstatementingeneral:
TheseriesofcolumnsenumeratedintheSETclausedoesnotneed
torefertothetable’scolumnsinanyparticularorder.
TheSETclausedoesnotneedtoreferenceallrequiredcolumns—in
otherwords,NOTNULLcolumns.Remember,UPDATEisnotaddinga
rowbutmodifyingexistingdata.AssumingtheUPDATEstatement’s
WHEREclausespecifiesanyexistingoneormorerows,thoserowsare
alreadyinthetable,sopresumablythedatawithineachrowalready
honorsallrequiredconstraints.
AnycolumnnamesomittedfromtheUPDATEstatement’sSET
clausewillnotbechanged.
AnyattemptbyUPDATEtoimplementachangethatviolatesa
constraintwillberejectedandfailtoexecute.
TheWHEREclausespecifiesthecriteriafordeterminingwhich
rowsinthetablewillbeupdated.Ifnosuchrowsarefound,the
UPDATEstatementupdatesnorows,anditexecutessuccessfullywith
noerrors.
TheWHEREclauseisnotrequiredinUPDATE.Ifitisomitted,the
UPDATEwillperformoneachrowinthetable.
Expressions
TheUPDATEstatementcanuseexpressionstoassignvaluestoanygiven
column.Expressionsmayincludeliteralvalues,validcolumnreferences,
mathematicalexpressions,andSQLfunctions.Let’slookatanexampletogetan
ideaofwhatcanbedone.Here’sanUPDATEstatementthatusesexpressionsin
theSETclause:
TheprecedingstatementisanUPDATEstatementintendedtochangedatain
atablecalledCOMPENSATION.TheUPDATEstatementwillchangedatain
anyandallrowswithavalueof83intheEMPLOYEE_NUMBERcolumn.For
anyrowthatmeetsthisWHEREcriteria,UPDATEwillchangethevaluesintwo
columns:
TheSALARYcolumnischangedtoequalitselftimes1.03.Thishas
theeffectofincreasingitsownvalueby3percentor—ifNULL—leaving
thecolumnNULL.
TheLAST_CHANGED_DATEcolumnissettothevalueof
SYSDATE.SYSDATEisabuilt-inSQLfunctionthatcontainsthe
currentdateandtimeaccordingtotheoperatingsystemwhereverthe
databaseisinstalled.
ThisexampledemonstrateshowexpressionscanbeusedwithinanUPDATE
statement.
Constraints
IftheUPDATEstatementviolatesanyconstraintonatable,theentireUPDATE
statementwillberejected,andnoneofthemodificationswillbeacceptedfor
anyoftherows.Inotherwords,iftheUPDATEstatementattemptstochange
anydatainanycolumnofanyrowinatableandanyonechangeresultsinany
oneconstraintviolation,thentheentireUPDATEstatementisrejected.
Forexample,reviewtheseSQLstatements:
Inthiscode,wecreateatablePROJECTSthatincludesacoupleofconstraints;
oneinparticularistheCHECKconstraintthatlimitsanyvalueintheCOST
columntonumbersthatarelessthanamillion.
NowseeFigure3-5.NoticehowweissueanUPDATEstatementinwhichwe
increasethecostofeachprojectby20percent.Thiswillcausetherowidentified
byPROJECT_ID2tobumpupoverourlimitationontheCOSTcolumn.The
resultisthattheentireUPDATEstatementisrejected.
FIGURE3-5 UPDATEstatement:oneconstraintviolationrejectstheentire
statement
Don’tgettheUPDATEstatement’sSETclausemixedupwiththe
“set”operatorsofUNION,INTERSECT,andMINUS.Thosearetwo
completelyseparateissues,andbothareaddressedontheexam.You’ll
studythesetoperatorsinChapter11.
TheWHEREClause
TheUPDATEstatement’sWHEREclauseisarguablyitsmostpowerfuland
importantfeature.WHEREdetermineswhichoftheexistingrowsinthetable
willbemodifiedbytheSETclause.TheWHEREclauseisnotuniquetothe
UPDATEstatement;WHEREisalsousedforsimilarpurposeswithDELETE
andSELECT.
Awordaboutterminology:UPDATEcanbeusedonlytomodifyexistingrows
inatable.Onapracticallevel,endusersmayspeakintermsof“adding”data
toatablewhenalltheyreallymeanisthattheywanttosetavaluetoacolumn
withinanexistingrow.Inotherwords,whenyouarespeakingwith
nontechnicalusersandtheyspeakof“adding”datatoatable,beawarethat
thisdoesn’tnecessarilymeanyou’llbeusingtheINSERTstatement;an
UPDATEmayactuallybeinorder.Similarly,youcanuseUPDATEto
“remove”valuesfromthetablebysettingagivenrow’scolumntoNULL.But
youaren’tnecessarilyremovingarowinthatsituation—justmodifyingthe
contentsofit.Toremovearow,youneedtheDELETEstatement.Youneedto
keepalerttothedifferencesbetweennaturallanguageandSQLsyntaxonthe
jobandontheexam.
CERTIFICATIONOBJECTIVE3.04
DeleteRowsfromaTable
TheDELETEstatementisusedtoremoverowsfromtablesinthedatabase.
RowsareidentifiedbytheWHEREclauseofDELETE.IfWHEREisomitted,
DELETEremovesalltherowsfromthetable.
WhenDELETEidentifiesarowwiththeWHEREclause,itremovesthe
entirerowfromthetable,notjustanindividualdataelementfromwithinarow.
Ifyourgoalistoremoveasinglevaluefromwithinanexistingrow,while
retainingtherowinthetable,thenyoudon’tuseDELETE;youuseUPDATEto
identifytherowandsetthedesiredvaluetoNULL.
TheDELETEclauseissimple.Here’sanexample:
ThissampledeletesanyandallrowsinthePROJECT_LISTINGtablewherea
columncalledCONSTRUCTION_IDcontainsavalueof12.Allrowsthat
containa12intheCONSTRUCTION_IDcolumnwillbedeletedfromthetable.
Let’slookatthissamplestatement:
Line1TherequiredreservedwordDELETE,followedbythe
optionalreservedwordFROM,followedbytherequirednameofthe
targettable
Line2AnoptionalWHEREclause
AsIjustsaid,thereservedwordFROMisoptional.Inotherwords,this
variationoftheprecedingDELETEstatementisalsovalid:
ThisDELETEstatementperformsthesamefunctionwithoutthereservedword
FROM.
TheWHEREclauseforDELETEperformsthesamefunctionastheWHERE
clauseintheUPDATEstatementandintheSELECTstatement,inthesensethat
itspecifiesrowsforprocessingbytheparticularDMLstatementwithwhichyou
areworking.Butbeware:inthecaseoftheDELETEstatement,ifyouomitthe
WHEREclause,you’lldeleteeveryrowinthetable.
CERTIFICATIONOBJECTIVE3.05
ControlTransactions
Sofarinthischapter,we’velookedattheSQLstatementsINSERT,UPDATE,
andDELETE.Thosethreestatements,alongwithSELECT,formasetofSQL
statementsknownasDataManipulationLanguage.
ThereareothertypesofSQLstatements,butonetypeinparticularisof
specialimportancetoDML.Asmentionedearlierinthechapter,thattypeis
knownasTransactionControlLanguage.Thesestatementsareimportanttoany
SQLsessioninwhichyouuseDMLstatements,asTCLstatementsprovidethe
functionalitytosaveorundothechangesmadewithDMLstatements.
We’lllookatthreeTCLstatementsinthissection:COMMIT,ROLLBACK,
andSAVEPOINT:
COMMITYoucouldthinkofCOMMITasSAVE.Saveschangesto
thedatabasesincethesessionbeganorsincethemostrecentcommit
eventinthesession,whicheverismorerecent.
ROLLBACKUndoeschangestothedatabaseperformedwithina
session,backtothelast“commit”pointinthesession.
SAVEPOINTTemporarilysetsanoptionalpoint,ormarker,ina
sessiontoempowerfuture“commit”or“rollback”actionsbyproviding
oneormoreoptionalpointsatwhichyoumay—ormaynot—undo
changes.
NotethatTCLperformschangesmadetothedatabasewithinasession.A
sessionbeginswhenasingleuserlogsinandcontinuesastheuserengagesina
seriesoftransactions,untiltheuserdisconnectsfromthedatabasebyeither
loggingoutorbreakingtheconnectioninsomefashion.Asingleusermay
engageinmultiplesessions.Buttheoppositeisnottrue:onlyoneusercan
engageinagivensession.ThisdiscussionaboutTCLisconcernedwith
sessions,includingthetransactionsthatoccurwithinagivensessionandhow
theimpactofthosetransactionsmayormaynotimpactothersessions.
Withthatinmind,let’slookateachstatementinmoredetail.
COMMIT
TheSQLstatementCOMMITisusedtosavechangesmadewithinasessionto
anytablesthathavebeenmodifiedbytheDMLstatementsINSERT,UPDATE,
andDELETE.COMMITmakeschangestothedatabasepermanent,andonce
committed,thosechangescannolongerbeundonewithaROLLBACK
statement.Thatisn’ttosaythatthedatacannotbechangedbackwithadditional
DMLstatements;ofcourseitcan.ButbeforeaCOMMITisexecuted,changes
tothedatabasecanbeundonewithaROLLBACKstatement.Afterthe
COMMIT,however,thatoptionnolongerexists.
AseriesofSQLstatementsisconsideredatransactionbySQLandistreated
asoneunit.Thechangesyoumakewithinatransactionarenotmadepermanent
untiltheyarecommitted.Acommiteventcompletesatransaction.
Therearetwokindsofcommitevents:
Anexplicitcommit,whichoccurswhentheCOMMITstatementis
executed
Animplicitcommit,whichoccursautomaticallywhencertain
databaseeventsoccur
Untilacommiteventofeithertypeoccurs,nochangesthatmayhavebeen
performedtotablesinthedatabasearemadepermanent,andallchangeshave
thepotentialforbeingundone.
ExplicitcommitsoccurwhentheCOMMITstatementisexecuted.Implicit
commitsoccurwithouttheCOMMITstatement,butinsteadoccurwhencertain
typesofdatabaseeventsoccur.Let’sdiscussbothsituations.
ExplicitCommit
AnexplicitcommitoccurswhenevertheCOMMITstatementisexecuted.The
syntaxofCOMMITissimple:
COMMIT;
TheCOMMITstatementhasafewparametersthatarenotrequiredforthe
exam.Oneworthnoting,however,istheoptionalkeywordWORK,asfollows:
COMMITWORK;
TheWORKkeywordisincludedforcompliancewithANSIstandardSQL,butit
isnotrequiredinOracleSQL.Itprovidesnoadditionalfunctionalitybeyondthe
COMMITstatementitself.
TounderstandhowCOMMITworks,considerthefollowingseriesofSQL
statements:
Inthisseriesofstatements,thechangetothetablemadebytheINSERT
statementismadepermanentbytheCOMMITstatement.Withoutit,the
INSERTchangescouldbeundonewithaROLLBACKstatement.
ImplicitCommit
Animplicitcommitoccurswhencertaineventstakeplaceinthedatabase.Those
eventsinclude
Immediatelybeforeandimmediatelyafteranattempttoexecuteany
DDLstatement,suchasCREATE,ALTER,DROP,GRANT,or
REVOKE.Note:EveniftheDDLstatementfailswithanexecutionerror
(asopposedtoasyntaxerror),the“before”implicitcommitisexecuted
andtakeseffect.
AnormalexitfrommostofOracle’sutilitiesandtools,suchas
SQL*PlusorSQLDeveloper.(OneexceptionisOracle’sprecompilers,
whichdonotperformanimplicitcommituponexitbutinsteadperforma
rollback.)
Whentheseeventstakeplace,animplicitcommitisautomaticallyexecuted,
meaningthatalluncommittedchangesbecomepermanentinthesamewayas
theywouldifyouhadexecutedtheCOMMITstatement.
Here’sanexample:
Inthisexample,thechangeperformedwiththeUPDATEstatementhas
becomepermanent.Why?BecauseALTERTABLEisaDDLstatementand
carrieswithitanimplicitcommit.AsfarastheSHIPStableisconcerned,the
followingwouldhaveanequivalentimpact:
Inbothexamples,theUPDATEstatementiscommitted.Thefirstexample
demonstratesanimplicitcommit.Thesecondexampledisplayedpreviously
showsanexplicitcommit.FromtheperspectiveoftheSHIPStable,theultimate
effectisthesame—anALTERTABLEcommandandaCOMMITcommand
bothresultinacommiteventonthechangesperformedbytheUPDATE
statement,aswellasanypreviouslyperformedchangesthatmayhavenotyet
beencommittedsincethemostrecentofeitherasessionstartoranother
COMMITevent.
COMMITandMultipleSessions
Uptonow,we’velookedatCOMMITfromtheperspectiveofasinglesession.
Nowlet’sexpandourperspectiveanddiscussCOMMITanditsbehaviorwith
regardtomultiplesessionsloggedinsimultaneouslyandaccessingthesameset
oftables.Inshort,asingleuser,loggedintoasinglesession,canperform
changestoadatabaseusingINSERT,UPDATE,DELETE,oranycombination
ofthethree,butwhiletheresultingchangesarevisibleinthesessionwithin
whichthechangeswereperformed,theyarenotvisibletoanyotherlogin
sessionuntilaCOMMITisperformed.Thisincludesadditionalloginsessions
bythesameuserwhoperformedthechanges.Asingleusercanloginmultiple
timesandopenmultipleloginsessions,butuncommittedchangestodataare
visibleonlywithintheonesessionthatperformedthechanges,untilacommitis
performed—eitherexplicitlyorimplicitly.
Let’ssaythatoneuseraccountownsaschemathatincludesseveraltables,
thatallusershavebeengrantedprivilegestosee(SELECT)datafromthese
tables,andthatonlytheowninguseraccountretainstheprivilegeofmodifying
anydatainthosetables.IfthatowninguserexecutesaseriesofDMLstatements
withinasinglesession,anyresultingchangeswillbevisiblewithinthatsession
butwillnotbevisiblefromwithinanyothersessions—thatis,notuntila
commiteventoccursintheoriginalsessionwherethechangesweremade.Until
then,othersessionswillnotseethechanges.Theowningusermayperforma
largeseriesofINSERT,UPDATE,andDELETEstatementsandevenprint
reportsandscreenshotdisplaysshowingtheresultsofthemodifications,
performingSELECTstatementstodoit.However,unlessanduntilacommit
eventoccurswithinthesessionwherethechangeswereperformed,noother
session,regardlessofwhateverprivilegesmightbeinvolved,willbecapableof
seeingthechangeddata.Onlyaftersomesortofcommiteventoccurs—either
explicitorimplicit—dothechangesbecome“permanent,”asOraclelikestosay,
andthereforevisibletoallsessions.
Let’slookatavariationofthisscenario.LookatFigure3-7.Inthisscenario,
USER_1ownsatableSHIPSandhasgrantedUPDATEprivilegestoUSER_2.
ThismeansthatUSER_2,whodoesnotowntheSHIPStable,hastherightto
issueUPDATEstatementsandchangethatdata.So,USER_2issuesan
UPDATEstatementonSHIPSbutdoesnotcommitthechanges.Theresultis
thatifUSER_3hasSELECTprivilegesandtriestoquerytheSHIPStable
ownedbyUSER_1,thechangesmadebyUSER_2arenotvisibletoanyone
otherthanUSER_2.USER_3,forexample,cannotseethechangeddata.Inthis
example,thevalueforCAPTAIN_IDis0,andUSER_2issuesachangetothat
valueandupdatesitto7.ButUSER_3doesnotyetseethechange,sinceit
hasn’tbeencommittedtothedatabase.Forthatmatter,nouserseesthechange
—otherthanUSER_2.Noteventhetableowner,USER_1,willseeUSER_2’s
changeunlessanduntilUSER_2causesacommiteventtooccur.
FIGURE3-7 Uncommittedchange
Inthisway,changesmadepriortoanycommiteventareinasortofstaging
area,wheretheusercanworkinwhatisalmosta“draft”mode.However,any
commitevent—explicitorimplicit—willmakechangespermanentandexpose
thenewdatatoallsessions.
ROLLBACK
TheROLLBACKstatementiscomparabletothe“undo”functioncommonto
manysoftwareapplications.ROLLBACKundoeschangestothedatabasethat
havebeenperformedwithinagivensession.Itdoesnotremoveanychangesthat
havealreadybeencommitted.Theonlychangesthatarerolledbackarethose
changesissuedwithinthesessionperformingtherollback.
Here’sanexample:
Inthisexample,oneINSERTstatementandoneDELETEstatementareissued.
Theresults:weaddonerowtothePORTStableanddeletealltherowsinthe
SHIPStable.
ButthenweissueaROLLBACKstatement,andbothchangesareeliminated.
ItisasifthosetwoDMLstatementsneverhappened.ThePORTSandSHIPS
tablesarerestoredtotheiroriginalconditionatthetimeofthelastCOMMIT
event.SincenoneoftheDMLstatementswascommitted,noothersessionsaw
thechanges.Thechangeswereobserved,albeittemporarily,onlybythesession
thatissuedthestatements.
ThechangesperformedbyuncommittedDMLstatementsarevisiblewithin
thesessionuntilthosechangesarerolledback.Forexample,seeFigure3-9.
FIGURE3-9 SamplesessionwithROLLBACK
Thefigureshowsthefollowingseriesofsteps:
AnexplicitCOMMITstatement
ASELECTtodemonstratethedatawithintheSHIPStable
AnUPDATEtochangedataintheSHIPStable
ThesameSELECTstatementtodemonstratethechangeddata
AROLLBACKtoremovetheeffectsoftheUPDATEstatement
ThesameSELECTstatementyetagain,showingthattheSHIPS
table’sconditionhasbeenrestored
Atnotimeduringthisprocessdidanyothersessionseetheeffectsofthe
UPDATEstatement.Thechangeswerevisibleonlytothesessionissuingthe
statements.
Ifaprogramabnormallyterminates,thedatabasewillissueanimplicit
rollback.Uncommittedchangesatthetimeofanabnormalterminationof,for
example,SQL*PlusorSQLDeveloperwillnotbecommittedtothedatabase.
SAVEPOINT
SofarwehavelookedattheTCLstatementsROLLBACKandCOMMIT.Let’s
lookatathird:SAVEPOINT.TheSAVEPOINTstatementestablishes
demarcationpointswithinatransactiontoempoweranyfollowingCOMMITor
ROLLBACKstatementstosubdividethepointsatwhichdatamaylaterbe
optionallysavedorundone.
WithoutSAVEPOINT,theCOMMITandROLLBACKstatementscan
operateonlyonasortofall-or-nothingbasis.Onceaseriesofstatementshave
beenexecuted,theentireseries,asonelargegroup,canbeeithersavedor
undone.ButifperiodicSAVEPOINTshavebeenissuedalongtheway,a
subsequentCOMMITorROLLBACKcanbeusedtosaveorrestoredatato
thosesavedpointsintimemarkedbyoneormoreSAVEPOINTstatements,thus
providingafinerlevelofdetailatwhichthetransactioncanbecontrolled.
HereisanexampleofSAVEPOINT:
Inthisexample,westartwithanexplicitCOMMITonline1andthenissuean
UPDATEstatement.Thenonline3,weissueaSAVEPOINTstatementand
nameitSP_1.That’sfollowedbyasecondUPDATEstatement.Giventhatwe
electedtoissuetheSAVEPOINT,wehaveanoptiononline5thatwehaven’t
seenyet,andthatisto“undo”thepreviousUPDATEstatement(butonlythat
secondUPDATE,notthefirst).Weaccomplishthisbyrollingbacktothe
SAVEPOINT.ThenweCOMMITourchanges.
TheresultisthatthevalueintheSHIP_ID12rowforHOME_PORT_IDis
21.
Here’sanotherexample;seewhetheryoucandeterminewhattheresulting
valueforHOME_PORT_IDwillbehere:
InthisseriesofSQLstatements,whatistheresultingvalueoftheSHIPS
table’sHOME_PORT_IDcolumnwheretheSHIP_IDvalueisequalto12?The
answer:22.ThatisthevaluecommittedtothedatabaseaftertheCOMMIT
statementonline8isexecuted.
Inthisexample,wecreatedtwoSAVEPOINTs—onewechosetoname
MARK_01,andanotherwechosetonameMARK_02.Wecouldhavechosen
anynameforthesesavepointsthatwewanted,accordingtotherulesofnaming
databaseobjects.Bynamingthem,wereservetherighttoselectivelyrollbackto
oneortheothernamedSAVEPOINT.Inthiscase,wechosetoissuea
ROLLBACKtotheSAVEPOINTnamedMARK_02.Thisstatementeffectively
restorestheconditionoftheentiredatabasetothepointwheretheSAVEPOINT
wasexecuted,which,inthisexample,ispriortotheUPDATEstatementonline
6.Inotherwords,it’sasiftheline6UPDATEstatementhadneverbeen
executed.
TherulesforusingSAVEPOINTincludethefollowing:
AllSAVEPOINTstatementsmustincludeaname.Thenamemust
bespecifiedusingthesamerulesandlimitationsfornamingdatabase
objects.Behindthescenes,theSAVEPOINTnameyoucreateis
associatedwithasystemchangenumber(SCN).Thisiswhatthe
SAVEPOINTismarking.
YoushouldnotduplicateSAVEPOINTnameswithinasingle
transaction—andrememberthatatransactionisaseriesofoneormore
SQLstatementsendingwithacommitevent.Ifyouduplicateaname,
youwillnotreceiveasyntaxorexecutionerror.Instead,thenew
SAVEPOINTwillsimplyoverridetheearlierSAVEPOINT,effectively
erasingit.
Onceacommiteventoccurs(eitheranexplicitorimplicitcommit
event),allexistingsavepointsareerasedfrommemory.Anyreferencesto
thembyfutureTCLstatementswillproduceanerrorcode.
Regardingthatlastpoint,here’sanexampleofwhatwe’retalkingabout:
Intheprecedingexample,theROLLBACKstatementonline5iswrongfor
tworeasons.First,it’slogicallyirrelevantsincethereisnothingtorollback—the
COMMITonline4permanentlysavedeverything,andnoadditionalSQL
statementshavebeenexecutedbythetimetheROLLBACKisexecutedonline
5.Second,theROLLBACKmakesareferencetoaSAVEPOINTthatdoesnot
exist,soitwillproduceanerror.Withoutthenamedsavepointreference,the
ROLLBACKwouldexecutejustfineandsimplyhavenoimpactonthe
database.ButwiththereferencetoanamedSAVEPOINTthatnolongerexists
bythetimetheROLLBACKisexecuted,theresultofline5isanerrorcode.
SAVEPOINTisparticularlyusefulwhenmanagingalargeseriesof
transactionsinwhichincrementalvalidationmustberequired,whereineach
individualvalidationrequiresacomplexseriesofDMLstatementsthatmight
failbutcanbeprogrammaticallycorrectedandvalidatedbeforemovingontothe
nextincrement.Agreatexampleofthisoccursinthefinancialworld.When
reconcilingasetoffinancialbooksforagivenorganization,youmightfindit
necessarytovalidateanaccountwithinalargerchartofaccounts.Duringeach
individualaccountvalidationprocess,theremaybeaneedtorollbacksome
statementsbeforemakingsomechangesandattemptingvalidationagain.Then,
onceagivenaccountisvalidated,youmightwanttodeclarethataccount
“temporarilyauthorized”andthenmoveontoattemptingtovalidatethenext
account.Furthermore,youmaywanttodeferacompleteCOMMITuntilall
accountshavebeenvalidated.SAVEPOINTisperfectforthis;aseachindividual
accountisvalidated,aSAVEPOINTcanbeestablishedsothatsubsequent
accountvalidationattemptsthatmightfailcantriggeraROLLBACKwithout
undoingtheearlieraccountsthatwerealreadysuccessfullyvalidated.Then,
whenallaccountsarevalidated—andnotbefore—asingleCOMMITcan
declarethefullsetofvalidatedrowstothedatabasewithapermanentsave.
ROLLBACKRevisited
Nowthatwe’veseenSAVEPOINT,let’stakeanotherlookatthesyntaxfor
ROLLBACKandseehowitcanbeusedtorollbacktoaparticularnamed
SAVEPOINT.
Sofar,we’veseenthisformoftheROLLBACKstatement:
ROLLBACK;
IfthesinglewordROLLBACKisexecutedbyitself,itwillignoreany
SAVEPOINTstatementsthatmayhavebeenexecutedsincethemostrecent
commiteventandundoanychangesmadebytheuserinthesessionsincethe
timeofthelastcommitevent.
However,ifROLLBACKisintendedtoundoanychangessinceanamed
SCNwasestablishedbySAVEPOINT,thenitcannametheSCNspecifically.
Forexample,ifaSAVEPOINTstatementestablishedademarcationwithan
SCNnamedscn_01,likethis:
SAVEPOINTscn_01;
thenasubsequentROLLBACKcanselectivelyundochangestothispoint
likethis:
ROLLBACKTOscn_01;
oralternativelylikethis:
ROLLBACKWORKTOscn_01;
Let’slookatthecomponentsofthisformoftheROLLBACKstatement:
First,thereservedwordROLLBACK
TheoptionalreservedwordWORK
TherequiredreservedwordTO
ThenameofanSCNasnamedbyaSAVEPOINTstatementthatwas
executedafterthemostrecentcommitevent
NotethattheWORKreservedwordisoptional.WORKispartoftheANSI
standardbutisnotrequiredintheOracleimplementation.
IfaROLLBACKstatementisexecutedthatnamesanonexistent
SAVEPOINT,SQLwilldisplayanerrorcodewarningthattherollbackwas
attemptingtorollbacktoaSAVEPOINTthatwasneverestablished.The
ROLLBACKwillfail,andnothingwillchangeregardingthestateofthe
database.Atthatpoint,anyoutstandingchangeswillremaininanuncommitted
state.Atthispoint,uncommittedchangesmaystillbecommittedorrolledback.
CERTIFICATIONSUMMARY
TheTRUNCATETABLEstatementcanbeusedinthosespecialcircumstances
whereyoumaywanttoremovealltherowsofatablewithoutfiringanyDML
triggersorselectivelyremovingdatafromanyassociatedINDEXobjects,as
wouldhappenwithaDELETEstatement.Insuchasituation,TRUNCATE
TABLEisanattractivealternativetodroppingandre-creatingatable,sinceit
leavesthetableanditsrelationshipsintact,aswellasanyindexes.TRUNCATE
TABLEcanremovestatementsmuchmorequicklywithlessprocessing
overheadthanDELETE.BecauseTRUNCATETABLEfiresnoDMLtriggers,it
isconsideredDDL;therefore,itsuseperformsanimplicitcommit,anditsresults
cannotberolledback.
IfTRUNCATETABLEisappliedtoatableforwhichthereexistsan
associatedparenttablewithaforeignkeyusingtheONCASCADEDELETE
clause,thenTRUNCATETABLEwillresultinanerrorifthereareinfactrows
inthatparenttablethatmightotherwisebedeletedasaresultofONCASCADE
DELETE.Forthissituation,youmustuseTRUNCATETABLE...CASCADE
toconfirmyourdesiretoremovethoseparentrows.
TheINSERTstatementaddsrowsofdatatoatable.Initssimplestform,it
addsonerowatatime.ItssyntaxstartswiththereservedwordsINSERTINTO
andthenameofasingledatabasetable,followedbyanoptionalcolumnlist,
followedbythereservedwordVALUES,followedbyalistofvaluestobe
insertedintothetable,enclosedinparentheses.Thelistofvaluesispresentedin
thesamesequentialorderasthecolumnlist,meaningthatfortherowthatthe
INSERTstatementisaddingtothetable,thefirstvalueinthelistwillbeadded
tothefirstcolumninthecolumnlist,thenthesecondvaluewillbeaddedtothe
secondcolumn,andsoon.Thedatatypesofthevaluesshouldbeappropriatefor
thedatatypesofthecolumnstowhichthevaluesarebeinginserted.Any
constraintsthatarenothonoredwillcausetheINSERTstatementtoberejected
atexecutiontime.Forexample,ifacolumnhasaNOTNULLconstraint,then
theINSERTstatementneedstoprovideavalidvalueforthatparticularcolumn,
orelsetheINSERTstatementwillfailandnorowisaddedtothetable.Ifthe
INSERTstatementomitsthecolumnlist,thenthevaluelistisassumedtobein
theorderofthecolumnsaccordingtothetargettable’sstructure,andeach
columnisassumedtobeaccountedforinthevalueslist.
TheUPDATEstatementisusedtomodifyrowsofdatainthetable.It
includestheoptionalWHEREclause,whichisusedtoidentifywhichrowsthe
UPDATEisintendedtomodify.IftheWHEREclauseisomitted,thenthe
UPDATEstatementwillattempttomodifyallrowsinthetargettable.The
UPDATEstatementusesthereservedwordSET,followedbypairsofcolumn
namesandvalues.Eachvaluecanbesubstitutedwithanexpression.Expressions
mayincludeliteralvalues,anyavailabletablecolumn,mathematicalequations,
andSQLfunctions.
TheDELETEstatementremovesrowsfromatable.TheoptionalWHERE
clausecanbeusedtoidentifywhichrowsaretobedeleted.However,ifthe
WHEREclauseisomitted,theneveryrowinthetablewillbedeleted.
TCL,whichisseparatefromDML,isoftenusedwithaseriesofDML
transactionstocontrolwhetherdataprocessedbythoseDMLtransactionswill
becommittedtothedatabase—inotherwords,made“permanent”asOracle
documentation(andothers)likestosay.TheTCLcommandsincludeCOMMIT,
ROLLBACK,andSAVEPOINT.
COMMITmakespermanentanyoutstandingchangestothetablesincethe
lastcommitevent.Commitscanoccurexplicitlyorimplicitly.Explicitcommits
occurwiththesimpleSQLstatementofCOMMIT.Implicitcommitsoccurwhen
othereventstakeplaceinthedatabase,suchasanyDDLstatement.AGRANT,
forexample,willautomaticallycommitallchangestothedatabasesincethelast
COMMIT.
ROLLBACKcanbeusedto“undo”aseriesofstatements.ROLLBACKused
byitselfundoesanychangesmadewithinasessionbytheusertothedatabase
sincethemostrecentcommitevent,implicitorexplicit,tookplace.Butifoneor
moreSAVEPOINTshavebeenissued,thentheROLLBACKmayoptionallyroll
backtoaparticularSAVEPOINT.
SAVEPOINTnamesasystemchangenumberandempowersfuture
executionsoftheROLLBACKstatementtogobacktoearlierversionsofthe
databaseincrementally.
✓TWO-MINUTEDRILL
TruncateData
TRUNCATETABLEremovesallofatable’srowsandallthedata
initsindexes,withoutfiringanytriggers.
ATRUNCATETABLEstatementisaDDLstatement.Thismeans
itsuseresultsinanimplicitcommitstatement,anditsresultscannotbe
rolledback.
IfyouuseTRUNCATETABLEonachildtableofaparentthat
usestheONDELETECASCADEclauseinitsforeignkeyconstraint,
thenyouusetheCASCADEclausewithTRUNCATETABLE,orelse
theexistingorchildrowswithmatchingparentrowswillcausethe
TRUNCATETABLEstatementtofailwithanerror.
InsertRowsintoaTable
TheINSERTstatementaddsoneormorerowstoatable.
TheINSERTsyntaxwereviewedinthischapterconsistsofthe
reservedwordsINSERTINTO,thenameofthetable,theoptional
columnlist,thereservedwordVALUES,andthelistofvaluestobe
entered.
IftheINSERTstatementiswrittensothatthelistofcolumnsinthe
tableisomitted,thenthelistofvaluesmustspecifyonevalueforeach
columninthetable;thosevalueswillbeprocessedinorderaccordingto
thecolumnsinthetable’sstructure.
ThelistofvaluesintheINSERTstatementmayinclude
expressions.Eachexpressionmustevaluatetoadatatypethatis
compatiblewithitstargetcolumninthetable.
Ifanyvalueviolatesanyconstraintappliedtothetargettable,then
anexecutionerrorwillresult.Forexample,eachnewrowaddedtothe
tablemustprovideanappropriatevalueofacompatibledatatypefor
eachNOTNULLcolumn;otherwise,anexecutionerrorisissued,and
theINSERTfails.
UpdateRowsinaTable
ThesingleUPDATEstatementcanmodifyexistingdatainoneor
morerowswithinadatabasetable.
TheUPDATEstatementsyntaxstartswiththereservedword
UPDATEandthenameofthetargettable,thereservedwordSET,and
thenaseriesofassignmentexpressionsinwhichtheleft-sideelement
specifiesatablecolumn,followedbytheassignmentoperator(anequal
sign),followedbyanexpressionthatevaluatestoadatatypeappropriate
forthetargettable’scolumnidentifiedontheleftsideoftheequalsign,
andfinallyanoptionalWHEREclause.
Ifadditionalassignmentexpressionsarerequired,eachadditional
assignmentexpressionisprecededbyacomma.
IftheWHEREclauseisomitted,thenalltherowsinthetableare
changedaccordingtotheseriesofSETvalueslistedintheUPDATE
statement.
DeleteRowsfromaTable
TheDELETEstatementisusedtoremoverowsofdatafroma
table.
ThesyntaxstartswiththereservedwordsDELETEandtheoptional
FROM,thenthenameofthetargettable,thenanoptionalWHERE
clause.
IftheWHEREclauseisomitted,alltherowsinthetableare
deleted.
ControlTransactions
TCLstatementsincludeCOMMIT,ROLLBACK,and
SAVEPOINT.
Therearetwotypesofcommitevents:explicitcommitandimplicit
commit.
AnexplicitcommitoccurswiththeCOMMITstatement.
Animplicitcommitoccursimmediatelybeforeandaftercertain
eventsthattakeplaceinthedatabase,suchastheexecutionofanyvalid
DDLstatement,includingCREATE,ALTER,DROP,GRANT,and
REVOKE.EachDDLstatementexecutionisautomaticallyprecededand
followedbyanimplicitcommit.
TheCOMMITstatementisusedtosavechangesperformedwithin
thesessionandmakethosechanges“permanent.”
IfaDDLstatementfailsduringexecution,theimplicitcommitthat
precededitstillisineffect,ensuringthatthecommitoccurred,whether
theDDLstatementwassuccessfulornot.ThesameisnottrueforDDL
statementsyntaxerrors.
TheROLLBACKstatementisusedtoundochangestothe
database.
TheSAVEPOINTstatementcanbeusedtonameapointwithina
seriesofSQLstatementstowhichyoumayoptionallyrollbackchanges
afteradditionalDMLstatementsareexecuted.
OnceaCOMMITisissued,allexistingSAVEPOINTsareerased.
AnyROLLBACKthatnamesnonexistingSAVEPOINTswillnot
execute.
IfROLLBACKisissuedwithoutnamingaSAVEPOINT,changes
madebytheuserduringthecurrentsessionarerolledbackwithinthat
sessiontothemostrecentcommitevent.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Choosethebestsingleanswerforeach
questionunlessotherwisespecified.
TruncateData
1.ReviewthefollowingSQLstatement:
TRUNCATEpersonnel;
Whichofthefollowingistrueofthepreviousstatement?(Chooseall
thatapply.)
A.Thestatementwillresultinanimplicitcommit.
B.ThestatementwillremovealldatafromanyINDEXobjects
associatedwiththattable.
C.ThestatementwillnotfireanyDMLtriggersonthetable.
D.Thestatementwillfail.
2.TheCASCADEkeyword,whenusedwithTRUNCATE:
A.Isrequiredifthetablehasanydependentchildtables
B.Willensurethatfutureattemptstoinsertrowstothetablewillbe
rejectediftheysatisfytheTRUNCATEtable’sWHEREclause
C.CanbeusedwiththeoptionalDEPENDENCYkeyword
D.Noneoftheabove
3.TRUNCATETABLE:
A.CannotbeusedwithinavalidSQLstatement
B.IsavalidsetofkeywordstobeusedwithinaDDLstatement
C.DoesnotrequiretheDROP_ANY_TABLEprivilege
D.IsavalidstatementthatwilltruncateatablecalledTABLE
InsertRowsintoaTable
4.Reviewthefollowingstatement:
Thetablewillcreatesuccessfully.WhatwillresultfromtheINSERT
statement?
A.TheINSERTwillfailbecausethereisnolistofcolumnsafter
STUDENT_LIST.
B.TheINSERTwillfailbecausetheliteralvalueforPHONEis
numericandPHONEisacharacterdatatype.
C.TheINSERTwillexecute—thetablewillcontainonerowof
data.
D.Noneoftheabove.
5.ConsiderthefollowingsetofSQLstatements:
Thetablewillcreatesuccessfully.Whatwillbetheresultofthetwo
INSERTstatements?
A.Neitherwillexecute.
B.Thefirstwillexecute,butthesecondwillfail.
C.Thefirstwillfail,butthesecondwillexecute.
D.Bothwillexecutesuccessfully.
6.ConsiderthefollowingsetofSQLstatements:
WhatwillbetheresultoftheINSERTstatement?
A.ItwillfailbecausethereisnocolumnlistintheINSERT
statement.
B.ItwillfailbecausethereisnoPRIMARYKEYinthetable.
C.Itwillexecuteandcreateanewrowinthetable.
D.Itwillfailbecausethelastnameandfirstnamevaluesare
reversed.
UpdateRowsinaTable
7.Whichofthefollowingreservedwordsisnotrequiredinordertoform
asyntacticallycorrectUPDATEstatement?
A.UPDATE
B.SET
C.WHERE
D.Noneoftheabove
8.AssumeatableLAMPSthathasnoconstraints.Whichofthe
followingistrueabouttheUPDATEstatementandtheLAMPStable?
(Chooseallthatapply.)
A.UPDATEcanbeusedtoaddrowstoLAMPSbysettingvalues
toallthecolumns.
B.UPDATEcanbeusedtoremovearowfromLAMPSbysetting
alloftherow’scolumnstoavalueofNULL.
C.ForexistingrowsinLAMPS,UPDATEcanaddvaluestoany
columnwithaNULLvalue.
D.ForexistingrowsinLAMPS,UPDATEcanremovevaluesfrom
anycolumnbychangingitsvaluetoNULL.
9.ReviewthefollowingSQLstatements:
Whatcanbesaidofthestatementslistedhere?
A.Onerowwillbeupdated.
B.Tworowswillbeupdated.
C.Atleastoneofthestatementswillnotexecute.
D.Noneoftheabove.
10.ReviewthefollowingSQLstatements:
WhatistheendresultoftheSQLstatementslistedhere?
A.TheBOUNCERStablewillcontainonerow.
B.TheBOUNCERStablewillcontaintworows.
C.TheUPDATEwillfailbecausethereisnoWHEREclause.
D.Noneoftheabove.
DeleteRowsfromaTable
11.WhichofthefollowingreservedwordsisrequiredinacompleteDELETE
statement?(Chooseallthatapply.)
A.FROM
B.WHERE
C.DELETE
D.Noneoftheabove
12.ConsiderthefollowingdatainatablecalledPARTS:
WhichofthefollowingSQLstatementswillremovethewordVALID
fromrow1,resultinginonerowwithastatusofNULLandtworowswith
astatusofPENDING?
13.ReviewthefollowingSQLstatements:
Whichofthefollowingbestdescribestheresultsofattemptingto
executetheDELETEstatement?
A.TheDELETEstatementwillfailbecauseitismissingacolumn
listbetweenthewordDELETEandthenameofthetable
AB_INVOICES.
B.TheDELETEstatementwillexecute,butnorowsinthetable
willberemoved.
C.TheDELETEstatementwillproduceasyntaxerrorbecauseitis
referencingarowthatdoesnotexistinthedatabase.
D.Noneoftheabove.
ControlTransactions
14.Assumeaschemawithonlytwotables:onenamedPRODUCTSandone
namedENGINEERING.ReviewthefollowingSQLstatements:
InthisseriesofSQLstatements,whichlinerepresentsthefirstcommit
event?
A.Line1
B.Line2
C.Line4
D.Line6
15.ReviewtheSQLstatementsthatfollow,andassumethatthereisnotable
calledADDRESSESalreadypresentinthedatabase:
WhatwillbetheresultoftheexecutionoftheSQLstatementsshown
here?
A.TheADDRESSEStablewillhaveonerowwithavalueof1for
ZONE.
B.TheADDRESSEStablewillhaveonerowwithavalueof2for
ZONE.
C.TheADDRESSEStablewillhavenorows.
D.Noneoftheabove.
SELFTESTANSWERS
TruncateData
1. D.Thestatementwillfail.TRUNCATETABLEiswhatisintended
here.TRUNCATEbyitselfisnotavalidstatement.
A,B,andCareincorrect.Theywouldbecorrectifthestatement
includedthekeywordTABLE.Butwithoutthatkeyword,thestatementwill
fail,sotheseoptionsarenotapplicable.
2. D.ThepurposeofCASCADEistoensurethatanydependentchild
tableswithrowsthatrelatetothetruncatedrowswillalsobetruncated.
A,B,andCareincorrect.CASCADEisnotrequired;itisoptional.
TRUNCATEhasnoeffectonsubsequentSQLstatements,including
INSERT.ThereisnoDEPENDENCYkeywordusedwithTRUNCATE.
3. B.Thesekeywords,whencombinedwithavalidtablename,will
formavalidDDLstatement.
A,C,andDareincorrect.Thesearevalidkeywords.TRUNCATE
requirestheDROP_ANY_TABLEprivilege.TABLEisakeywordand
requiredforTRUNCATE,anditrequiresavalidtablenametofollowthe
keywordTABLE.
InsertRowsintoaTable
4. C.Thestatementsaresyntacticallyandlogicallycorrect.The
INSERTstatementomitsthecolumnlist.Thisomissionrequiresthelistof
valuestobeprovidedinthesamesequenceinwhichthecolumnsappearin
thetable’sstructure,asindicatedintheCREATETABLEstatement.
A,B,andDareincorrect.ThevalueprovidedbyINSERTforthe
PHONEcolumnisanexpressionthatiscompatible;theVARCHAR2data
typeisacharacterdatatype,anditacceptsbothnumericandtextdata.In
fact,valueslikephonenumbersandZIPcodesarebesttreatedascharacter
data;otherwise,leadingzeroswillbetruncated,andinthecaseofaZIP
code,thatcanbeadisasterforalotofaddressesintheNortheasternUnited
States.
5. D.Thesyntaxisfine,andbothINSERTstatementswillexecute.
A,B,andCareincorrect.
6. C.Itwillcreateanewrowinthetable.Thefactthatthecolumn
valuesareprobablyreversedmayrepresentalogicalerrornowandcreate
problemsdowntheroad,butthere’snothingaboutthestatementthatwill
preventitfromexecutingsuccessfully.
A,B,andDareincorrect.ThelackofacolumnlistintheINSERT
merelyrequirestheretobealistofvaluesmatchingthenumberanddata
typesofthecolumnsinthetable’sstructure,andthisINSERTstatement’s
listofvaluessatisfiesthatrequirement,albeitinanapparentlyillogicalway,
butnevertheless,therequirementsforSQLaremet.Thelackofa
PRIMARYKEYonthetableprobablyrepresentspoordesign,butisnota
problemwithregardtothesuccessfulexecutionoftheSQLstatementshere.
UpdateRowsinaTable
7. C.AnUPDATEstatementdoesnotneedtohaveaWHEREclause.
IfaWHEREclauseisomitted,theneveryrowinthetargettableissubject
tobechangedbytheUPDATEstatement,dependingonwhetherany
constraintsexistonthetableandwhethertheypermitorrejectthedata
changestheUPDATEstatementisattemptingtomake.
A,B,andDareincorrect.ThereservedwordUPDATEisrequiredfora
validUPDATEstatement.ThesameistrueforthereservedwordSET.
8. CandD.Addingavaluetoacolumninanexistingrowisthe
purposeoftheUPDATEstatement.SettingavaluetoNULLisas
acceptableassettingavaluetosomeotherspecificvalue.
AandBareincorrect.INSERTaddsnewrowstoatable,andDELETE
removesthem.UPDATEdoesn’tremoverowsfromatable.TheUPDATE
statementcanmodifyonlyexistingrows.InthequestionoftheLAMPS
table,ifyouchoosetouseSETtoseteachcolumn’svaluetoNULL,then
you’llstillhavearowinthetable;itwillsimplyconsistofNULLvalues.
Butyou’llstillhavearow.AndyoucannotcreateanewrowbyusingSET
tosetvaluestoeachcolumn;allyoucandoismodifyexistingrows.And,
ofcourse,ifLAMPSwerecreatedwithanyNOTNULLconstraints,any
UPDATEstatementwouldhavetorespectthoseconstraints.Butthe
questionassertedtheLAMPShasnoconstraints.
9. C.TheUPDATEstatementcontainsanextraoccurrenceofthe
reservedwordSET.OnlythefirstSETbelongs;thesecondshouldbe
removed.Isthisatrickyquestion?Yes,itis.Soaremanyofthequestions
onthecertificationexam.Makesureyourknowledgeofsyntaxisstrong.
Andreadcarefully.
A,B,andDareincorrect.
10. A.TheINSERTstatemententersasinglerow,andtheUPDATEstatement
modifiesthatsinglerow,leavingonemodifiedrowinthetable.
B,C,andDareincorrect.Thereisonlyonerowinthetable—the
UPDATEdoesnotaddanewrowbutratherchangestheexistingrow.
UPDATEdoesnotrequireaWHEREclause;withoutit,theUPDATE
statementappliesitschangestoalltherowsinthetable,andthistable
containsonerow.
DeleteRowsfromaTable
11. C.TheonlyrequiredreservedwordisDELETE.
A,B,andDareincorrect.FROMisoptional.WHEREisalsooptional.
12. Discorrect.DELETEremovesentirerowsfromthedatabase.Removing
asinglevaluefromasinglecolumnrequirestheuseoftheUPDATE
statement.
A,B,andCareincorrect.AandBarevalidDELETEstatements,either
ofwhichwillremovethefirstrowfromthetable,insteadofjustremoving
thevalueforthe“status”column.OptionCisaninvalidstatementthatwill
triggerasyntaxerror—theSETreservedwordhasnoplaceintheDELETE
statement.
13. B.Thesyntaxisfine,andthestatementwillexecuteasintended,whichis
toremoveanyrowsfromthetablewithanINVOICE_IDvalueof2.Itjust
sohappensthattherearen’tanyrowsthatmatchthestatedcriteriaatthe
timetheDELETEstatementisissued.
A,C,andDareincorrect.ThereisnocolumnlistinaDELETE
statementbeforethetablename.AndthefactthattheWHEREclausedoes
notidentifyanyrelevantrowsisnotasyntaxproblem,norisita
compilationproblem—thestatementwillsimplynotdeleteanyrows.
ControlTransactions
14. B.Line2isaDROPstatement,whichfallsunderthetypeofSQL
statementsknownasDataDefinitionLanguage.AllDDLstatementscause
animplicitcommittooccur,eveniftheDDLstatementfailsinexecution.
A,C,andDareincorrect.TheSELECTstatementhasnoimpactona
commiteventatall.Line4isanexplicitCOMMIT,andwereitnotforline
2,thiswouldbethefirstcommiteventinthissetofstatements.Line6
undoestheeffectsofline5andundoestheuser’schangestothedatabase
sincethepreviouscommitevent,whichatthisstageisrepresentedbythe
line4commit.
15. C.TheROLLBACKstatementdoesnotreferencetheSAVEPOINTname,
soinsteaditrollsallthewaybacktothelastCOMMITevent,whichinthis
caseistheimplicitcommitthatoccurredwiththeCREATETABLE
statement.
A,B,andDareincorrect.
4
RestrictingandSortingData
T
CERTIFICATIONOBJECTIVES
4.01SorttheRowsThatAreRetrievedbyaQuery
4.02LimittheRowsThatAreRetrievedbyaQuery
4.03UseAmpersandSubstitutiontoRestrictandSortOutputatRunTime
4.04UsetheSQLRowLimitingClause
✓Two-MinuteDrill
Q&ASelfTest
hischapterlooksatvariouscapabilitiesoftheSELECTstatement:the
WHEREclause,theORDERBYclause,ampersandsubstitution,andthe
SQLrowlimitingclause.TheORDERBYclausesortstheretrievedrows.It’s
veryflexible:itcansortrowsinascendingordescendingorder,oritcansortby
expressionlistsortakeadvantageofotherpowerfulfeatures.TheWHERE
clausespecifiesthecriteriarequiredforarowtobeincludedinaSQLstatement.
Withoutit,allrowsinagiventableareretrieved,butwithit,aSQLstatement
canselectivelytargetparticularrowsforprocessing.Ampersandsubstitution
providesuniqueandpowerfulcapabilitieswhenworkingwithOracleSQL.The
SQLrowlimitingclauseisaflexibleenhancementtotheSELECTstatement.
AmpersandsubstitutionisaSQL*Pluscapabilityontheexam.Weknowitisa
SQL*Plusstatementbecauseitisnotdescribedinthe"OracleDatabaseSQL
LanguageReference,"butisdetailedinsteadinthe“SQL*PlusUser'sGuide
andReference."Ampersandsubstitutionprovidesuniqueandpowerful
capabilitieswhenworkingwithOracle’sSQL,thusitsinclusionontheexam.
Aworkingknowledgeoftheseclausesisnecessarytopasstheexam.Let’s
getstarted.
CERTIFICATIONOBJECTIVE4.01
SorttheRowsThatAreRetrievedbyaQuery
ThissectionlooksatanotherclauseintheSELECTstatement,theORDERBY
clause.ORDERBYisusedtosorttherowsthatareretrievedbyaSELECT
statement.Itsortsbyspecifyingexpressionsforeachrowinthetable.Sorting
canbeperformedineitherascendingordescendingorder.SQLwillsort
accordingtothedatatypeoftheexpressionthatisidentifiedintheORDERBY.
Youcanincludemorethanoneexpression.Thefirstexpressionisgivensorting
priority,thesecondisgivensecond-positionpriority,andsoon.
ORDERBYisalwaysthefinalclauseinaSELECTstatement.Itisusedonly
inSELECT;contrarytotheWHEREclause,whichcanalsobeusedinUPDATE
andDELETE,theORDERBYclauseisuniquetotheSELECTstatementandis
notusedintheotherSQLstatements.
(NotethatinChapter9we’llexaminehowyoumayembedaSELECT
statementasasubquerywithinanINSERT,UPDATE,orDELETEstatement—
sointhatregard,itistheoreticallypossiblethatanORDERBYclausemightbe
includedinaSELECTstatementthatisembeddedwithin,forexample,an
INSERTstatement.Butthatisaseparateissue.)
ORDERBYdoesnotchangedataasitisstoredinthetable.Datainatable
remainsunchangedasaresultoftheORDERBY.ORDERBYispartofthe
SELECTstatement,andtheSELECTstatementisincapableofchangingdatain
thedatabase.Note,however,thatwhenSELECTisembeddedwithinotherSQL
statementslikeINSERTorUPDATE,changestothedatabasecanresult,butnot
becauseofSELECTalone.You’llseehowthatworksinChapter9.
ORDERBYsortstheoutputofaSELECTstatementfordisplaypurposes
only.ItisalwaysthelaststepinaSELECTstatementandperformsitssortafter
allthedatahasbeenretrievedandprocessedbytheSELECTstatement.
ReferencebyName
Let’slookatanexampleofORDERBYinaction.Considerthefollowingdata
listingfromatableADDRESSES:
Wecanselectthisdataandsortitbyspecifyingthecolumnname(ornames)
intheORDERBYclauseoftheSQLstatement,asfollows:
Figure4-1showstheresults.Noticeinthefigurethattherowsaresortedin
alphabeticalorderaccordingtothevalueintheSTATEcolumn.
FIGURE4-1 ResultsofSELECTwithORDERBYSTATE
NotethattherowwithaNULLvalueforSTATEislast.TheNULLvalueis
consideredthe“highest”value.
Aswereviewtheoutput,itbecomesclearthatwemightalsowantto
alphabetizeourinformationbycityforeachstate.Wecandothatbymodifying
ourORDERBYclauseeversoslightly:
InthemodifiedversionofourORDERBY,weaddasecondcolumntothe
ORDERBYclausebywhichwewanttosort.Figure4-2displaystheresultsof
thisSELECTstatement.TherowshavebeensortedfirstbySTATEandthenby
theCITYvalueforeachSTATE.
FIGURE4-2 ResultsofSELECTwithORDERBYSTATE,CITY
NotethatthechoiceofcolumnsweincludeintheORDERBYclausedoes
notinfluencewhichcolumnswechoosetodisplayintheSELECTexpression
list.Itwouldprobablybeeasiertoreadifweputthesamecolumnsusedinthe
ORDERBYinthesamepositionsastheSELECTexpressionlist.Inother
words,thisquerywouldprobablyproduceamorereadableoutput:
TheoutputofthisSELECTwoulddrawattentiontoourintent,whichisto
sortdatabySTATEfirstandthenCITY.Butwhilethismightbeconsidered
preferentialdesignincertaincircumstances,itisbynomeansrequiredwithin
thesyntaxoftheSQLstatement.We’renotevenrequiredtoincludetheORDER
BYcolumnsintheSELECTstatement’sexpressionlistatall.Thisisanother
perfectlyvalidSELECTstatement:
Noticethatwe’resortingbycolumnsthataren’tincludedintheSELECT
statement’sexpressionlist.
WithoutanORDERBYclause,thereisnoguaranteeregardingthesequence
inwhichrowswillbedisplayedinaSELECTstatement’soutput.Therowsmay
beproducedinadifferentorderfromonequerytoanother.Theonlywayto
ensureconsistencytotheoutputistoincludeanORDERBYclause.
ASCandDESC
Therearetworeservedwordsthatspecifythedirectionofsortingonagiven
columnoftheORDERBYclause.ThosereservedwordsareASCandDESC.
ASCisshortfor“ascending”andindicatesthatvalueswillbesorted
inascendingorder.Inotherwords,thelowest,orleast,valuewillbe
listedfirst,followedbyvaluesofhigher,orgreater,value.ASCisthe
defaultchoiceandassuchdoesnotneedtobespecifiedwhendesiredbut
maybespecifiedforclarity.
DESCisshortfor“descending”andindicatesthatvalueswillbe
sortedindescendingorder.Inotherwords,thehighest,orgreatest,value
willbelistedfirst,andvalueswillcontinuetobelistedindecreasing,or
lesser,value.
Asjuststated,thedefaultisASC.Youdon’tneedtospecifyASC.The
ORDERBYexamplesyou’veseensofarhavedefaultedtoASCwithoutour
havingtospecifyit.ButyoucanspecifyASCifyouwish.
Here’savariationontheprecedingSELECTstatementthatusesa
combinationofASCandDESC:
Figure4-3displaystheresultsofthisSELECT.NoticethattheSHIP_ID
valuesarelistedinascendingorder,butthatforeachship,thePROJECT_COST
valuesareshownfromthehighesttothelowestvalues.
FIGURE4-3 PROJECTStablewithORDERBYASCandDESC
ASCandDESCeachoperateontheindividualORDERBYexpressions.
ThereisnowaytoassignASCorDESCtoalltheORDERBYexpressions
collectively;instead,youmustplaceyourchoiceaftereachindividualORDER
BYexpression,rememberingthatASCisthedefaultandthereforedoesnotneed
tobespecified.
Expressions
NotethattheexpressionsyoucanincludeinanORDERBYclausearenot
limitedtocolumnsinatable.Anyexpressionmaybeused.Tobeuseful,the
expressionshouldincludeavalueinthetable;otherwise,thevaluemaynot
change,andtherewon’tbeanymeaningfuleffectontherowsinthetable.
Forexample,here’sadatalistingforthePROJECTStable:
Thisdatalistingshowsaseriesofprojects.Foreachproject,weseethe
SHIP_IDforwhichtheprojectisintended,theproject’stotalcost,andthe
estimatednumberofdaysitwilltaketocompleteeachproject.
LookingatthevaluesforPROJECT_COSTandDAYS,weseeenough
informationtocomputetheaveragecostperdayforeachproject.
Forexample,theper-daycostforthethree-day“LifeboatInspection”willturn
outtobe4000,or12000dividedby3.
Whatifwewanttosorttheserowsaccordingtothecomputedvalueofthe
PROJECT_COST/DAYS?Noproblem.
Thatquerywillachievetheresultwe’reafter.Let’svaryitabittoseemoreof
whatitiswe’recalculatingandsorting.
Figure4-4showstheresultsofthisquery.Notethattherowsareorderedbya
valuethatdoesn’texistinthetablebutratheravaluethatistheresultofan
expressionthatdrawsvaluesfromthetable.
FIGURE4-4 PROJECTSsortedbyPROJECT_COST/DAYS
TheColumnAlias
Asyou’vealreadyseen,aSELECTstatementcanincludeexpressionsinthe
selectlist.Here’sanexample:
NoticetheoutputinFigure4-4andthedefaulttitleofthefifthcolumn.SQLhas
usedtheexpressionasthetitleofthecolumn.
WecouldhaveusedaSQLfeaturecalledthecolumnalias.Hereisthesame
querywithacolumnalias(linenumbersadded):
NoticethePER_DAY_COSTcolumnaliasattheendofline2.Thecolumn
aliasisanameyoumakeupandplacejustafterthecolumnyouwanttoalias,
separatedbytheoptionalkeywordAS.Inthisexample,thecolumnwiththe
columnaliasisthefinalcolumnintheselectlist.Oncethecolumnaliasisused,
youcanreferenceitfromwithintheORDERBYclause,aswedoonline4.
Therulesforusingacolumnaliasincludethefollowing:
EachexpressionintheSELECTlistmayoptionallybefollowedbya
columnalias.
Acolumnaliasisplacedaftertheexpressionintheselectlist,
separatedbytheoptionalkeywordASandarequiredspace.
Ifthecolumnaliasisenclosedindoublequotes,itcaninclude
spacesandotherspecialcharacters.
Ifthecolumnaliasisnotenclosedindoublequotes,itisnamed
accordingtothestandardrulesfornamingdatabaseobjects.
ThecolumnaliasexistswithintheSQLstatementanditsresultsand
doesnotexistoutsideoftheSQLstatement.
Thecolumnaliasmustbeunique;itwillbecomethenewheaderin
theoutputoftheSQLstatement.
ThecolumnaliascanbereferencedwithintheORDERBYclause,
butnowhereelse—suchasWHERE,GROUPBY,orHAVING.
Here’sanexampleofacolumnaliasthatusesthedoublequotationmarks.
Noticetheinclusionofaspaceinthealias.
SeetheoutputofthisqueryinFigure4-5.Noticethecolumnheadingforthe
aliasedcolumn—thealiasbecomesthenewheadingintheSQLoutput.
FIGURE4-5 SELECToutputwithcolumnalias
ThepointofbringingupthealiashereinthisdiscussionaboutORDERBYis
this:youcanusethecolumnaliaswhenreferencinganycolumnwithORDER
BY,andit’sparticularlyusefulwhentryingtouseORDERBYwithan
expressionfromwithintheSELECTstatement’sexpressionlist.
ReferencebyPosition
AnotherwaytheORDERBYclausecanidentifycolumnstobesortedisviathe
“referencebyposition”method.ThisworksonlyiftheintentoftheORDERBY
istosortrowsaccordingtoinformationthatisincludedintheSELECTlist.
Here’sanexample:
NoticethatwechoosetoORDERBY5inthisSQLstatement.Thenumber5in
thiscontextisreferencingthefifthitemintheSELECTstatement’sselectlist,
whichistheexpressionPROJECT_COST/DAYS.
AnyexpressionintheSELECTlistcanbereferencedusingitsnumeric
position.Thefirstexpressionisconsiderednumber1,thesecondisnumber2,
andsoon.
Anyattempttoreferenceapositionthatdoesn’texistwillproduceaSQL
error;forexample,thisisinvalid:
Thisstatementwillnotexecute.TheORDERBYclausemustidentifyanumber
thatcorrespondstoanitemthatisintheSELECTlist.
Combinations
ORDERBYcancombinethevarioustechniquesofreferencebyname,reference
bycolumnalias,andreferencebyposition.Here’sanexample:
Thisexampleisavalidstatement.Itsortsrowsby
ThevalueofSHIP_ID,indescendingorder
ThevalueinthePROJECT_NAMEcolumn,whichhasacolumn
aliasinthisSQLstatementof"TheProject"
ThevalueinthePROJECT_COSTcolumn,whichistheseconditem
intheSELECTlist
Figure4-6showstheoutputofthisquery.
FIGURE4-6 PROJECTSsortedbymultipletechniques
RememberthatorderingaSELECTstatementbypositionisextremely
usefulinmanysituationsthatinvolvecomplexSELECTstatements.
Lateryou’llseesomeinterestingcombinationsofmultipleSELECT
statements(suchasthesectionthatlooksatusingsetoperatorsthat
combinemultipleSELECTstatementsintoone),andinthosesituations,
youcanalwaysreferenceanORDERBYcolumnbyposition.
ORDERBYandNULL
WhenSELECTperformsasortusingORDERBY,ittreatsanyvaluesthatit
mightfindtobeNULLas“greaterthan”anyothervalue.Inotherwords,when
yousortbyanumericdatatypecolumnandthatcolumncontainsNULLvalues,
theNULLvalueswillsortasbeinggreaterthanallNOTNULLvaluesinthelist.
Thesameistrueforcharacterdatatypesanddatedatatypes.
CERTIFICATIONOBJECTIVE4.02
LimittheRowsThatAreRetrievedbyaQuery
WhenbuildingaSELECTstatement,yourfirsttaskistoidentifywhichdatabase
table(ortablesorviews)containsthedatayouneed.Youalsoneedtolookatthe
table’sstructuretochoosethecolumnsthatwillbeincludedintheselectlistof
yourSELECTstatement.Butrarelydoyoustopthere.Mostofthetimeyou’ll
wanttolimittherowsyou’llretrievetoaparticularfew,basedonsomesortof
businessrules.ThattaskisaccomplishedwiththeSELECTstatement’sWHERE
clause.
ThissectionwilllookattheWHEREclauseanditsusage.
TheWHEREClause
TheWHEREclauseisoneofthemoreimportantclausesofthreedifferentSQL
statements:SELECT,UPDATE,andDELETE.
ThepurposeoftheWHEREclauseistoidentifyrowsthatyouwantto
includeinyourSQLstatement.Ifyou’reworkingwithaSELECT,thenyour
WHEREclausechooseswhichrowswillbeincludedinyourSELECToutput.If
it’sanUPDATEyou’reworkingwith,theWHEREclausedefineswhichrows
willbeupdated.Ifit’saDELETE,theWHEREclausedefineswhichrowswill
bedeleted.
WithinanySQLstatement,theWHEREclause,ifincluded,alwaysfollows
theFROMclause.WHEREisoptional;itisneverrequiredinordertoforma
completeSQLstatement,butifincluded,itmustfollowtheFROMclause.
TheWHEREclausestartswiththereservedwordWHERE,whichis
followedbytheWHEREcondition.TheWHEREconditionconsistsofoneor
morecomparisonsofexpressions.TheultimategoaloftheWHEREconditionis
todetermineavalueoftrueorfalseforeachrowinthetables(and/orviews)
identifiedintheFROMclause.IftheWHEREconditionreturnsatruefora
givenrow,thatrowisincludedintheSQLstatement.Ifitreturnsafalsefora
givenrow,thatrowisignoredfortheSQLstatement.
Let’slookatasimpleexample:
Inthisexample,theWHEREclauseonline3comparestwoexpressions:
ThefirstexpressionisthetablecolumnSHIP_ID.
Thesecondexpressionconsistsoftheliteralvalue3.
Thecomparisonoperatorusedtocomparethesetwoexpressionsistheequal
sign.TheWHEREclausewillconsidereachrowinthetables(and/orviews)
identifiedintheFROMclause.ForthisWHEREclause,eachrow’sSHIP_ID
valueisanalyzedtodeterminewhetheritsvalueequals3.Foreachrowthat
containsavalueof3intheSHIP_IDcolumn,theWHEREconditionreturnsa
valueof“true”forthatrow,andthatrowisincludedintheSQLstatement.All
otherrowsareignored.
NotethattheSELECTstatement’sselectlistdoesn’tincludeSHIP_ID.The
WHEREclausedoesnotneedtoincludeanyofthecolumnsthatarebeing
displayed—anycolumninthetableisavailabletotheWHEREclause.Inthis
particularexample,theissueofwhethertoincludearowisbasedondatathat
won’tbeincludedinthefinalresultsoftheSELECTstatement,andthat’sfine.
IfyouleavetheWHEREclauseoutofaSELECTstatement,thenallrowsof
thetable(ortables)areretrieved.
HereisanotherexampleofaWHEREclause:
ThisexampleshowsacompleteWHEREclauseonline3.Inthisexample,
theSELECTstatementwillshowthevaluesforPORT_NAMEandCAPACITY
forallrowswithavalueintheCAPACITYcolumnthatisgreaterthanorequal
to5.
Inthenextsectionwe’llexamineexpressionsinWHEREclauses.
ComparingExpressions
TheWHEREclauseusesaseriesofcomparisons,eachofwhichevaluatesfor
eachrowtoeithertrueorfalse.Eachcomparisoninvolvestwoexpressions
evaluatedbyacomparisonoperator.Theexpressionsarefirstevaluatedandthen
compared.Forexample,inthefollowingcomparison,ontheleftisanexpression
thatconsistssolelyofthecolumnnamedSALARY,andontherightisan
expressionthatmultipliestwonumberstogether:
Inthisexample,ifthevalueinSALARYisgreaterthanorequaltotheresultof
themathequation50899times1.12,theresultistrue.Otherwise,it’sfalse.
Theexamplesyou’veseensofarhaveshowncolumnnamesontheleft,but
that’snotrequired;anyvalidexpressionmaybeplacedoneitherside—orboth
sides—ofthecomparisonoperator.Ideallyoneoftheexpressionsshouldinclude
datafromthetable;otherwise,what’sthepoint?Butintermsofsyntax,thatis
notrequired.Allthatisrequiredisavalidexpressiononbothsidesofthe
comparisonoperator.
Let’slookatanotherexample:
Foragivenrow,ifthevalueinthecolumntitledSTART_DATEislessthanthe
valueinthecolumntitledEND_DATE,theexpressionistrue;otherwise,it’s
false.(NotethatwhenSQLcomparesdates,“lessthan”means“earlierthan.”
Forexample,January1islessthanJanuary2ofthesameyear.We’lltalkmore
aboutthisissueinabit.)
TheWHEREclauseusescomparisonoperatorstocomparetwoexpressions
toeachother.SeeTable4-1forafulllistofthecomparisonoperators.The
operatorsarerelativelyself-explanatory,exceptforIN,LIKE,andIS,allof
whichwe’lldiscussinupcomingsections.
TABLE4-1 ComparisonOperators
ComparingDataTypes
Withinasinglecomparison,bothexpressionsshouldbethesamedatatypefor
thecomparisontowork.Thereareessentiallythreegeneralcategoriesofdata
typestoconsiderwhenperformingcomparisons—numeric,characterstring,and
date.Table4-2liststherulesforcomparingdatatypes.
TABLE4-2 RulesforDataTypeComparisons
YoumayhavenoticedthatIsaiddatatypes“should”bethesamefortwo
expressionsthatarecomparedtoeachother.Isay“should”becausethisisn’tan
absoluterule.Sometimesyoucangetawaywithcomparingexpressionsof
differentdatatypesprovidedthatSQLhasenoughinformationtoperforman
automaticdatatypeconversionandthereforetreatbothsidesofthecomparison
asthoughtheywerethesamedatatype,eventhoughtheyarenot.Whilethiscan
work,it’snotrecommended.Theresultsofsuchautomaticdatatypeconversions
canbeabittrickyandrelativelyunpredictable,soit’sbesttoavoidsuch
situations.WhenwediscussSQLfunctionslater,you’llseesomefunctionsthat
canbeusedtoperformexplicitdatatypeconversions,whichisthebetterchoice
forSQLprofessionals.Inthemeantime,don’tdependonOracleSQL’s
automaticdatatypeconversioncapabilitiesunlessyoulovetolivedangerously
anddon’tmindiftherestofuslaughatyou.
Here’sanexamplethatcomparesstringvalues:
ThissamplewillshowallcolumnsinalltherowsintheEMPLOYEEStable
wherethevaluefortheLAST_NAMEcolumnisthecharacterstring'Smith'.
Notethattextsearchesarecase-sensitivebydefault.Inotherwords,thisisa
differentquery:
ThesearchforemployeeswithavalueintheLAST_NAMEcolumnof
'SMITH'willnotfindthesamerowsthathaveaLAST_NAMEvalueof'Smith'.
Ifyouwanttodoasearchonbothpossibilities,seeChapter6,wherewe’ll
discusshowtohandlesuchsituationsusingSQLfunctions.
Whencomparingdates,Ialwaysliketorememberthisrhyme:“laterdatesare
greaterdates.”That’smytrickforrememberinghowtherulesofdate
comparisonwork.
LIKE
TheLIKEcomparisonoperatorisusefulforperformingwildcardsearcheson
characterdata.Ituseswildcardcharactersthatyoucanembedwithinatext
string.LIKEworkswithcolumnsofdatatypeCHARanddatatype
VARCHAR2.Technicallyitdoesn’treallyworkonDATE,butonapractical
levelitdoes—itperformsanautomaticdatatypeconversionoftheDATEvalues
involvedbeforeperformingthecomparison.
Thetwowildcardsymbolsare
Theunderscore(_),representingasinglecharacter
Thepercentsign(%),representingzeroormorecharacters
Youusetheunderscorewhenyouarereferencingafixedlengthofwildcard
characters.Underscorescanberepeatedasrequired.Forexample,thisqueryis
lookingforvaluesinthePORT_NAMEcolumnthatstartwiththestring'San',
followedbyablankspace,followedbyanyfourcharacters:
Incaseyoucan’ttell,that’sfourunderscoresafter'San'inthepreceding
query.Ifyouweretorunthisqueryagainstrowswiththesevalues:
thequerywillreturnonlythisvalue:
SanJuan
That’sbecauseofthefourunderscoresinthequery(line3),whichspecifically
askforfourunknowncharactersafter'San'.Nomore,noless.
Ifyouwanttoindicateanynumberofunknowncharacters,rangingfromzero
toinfinity,thenusethepercentsign.Thisquery,
willfindallthreerowsinthepreviousexample,likeso:
Thepercentsign,combinedwithLIKE,indicatesthatanynumberofcharacters
aresought.
Underscoresandpercentsignscanbeusedinanycombination,inanyorder,
inanylocationwithinthepattern.Here’sanexample:
ThisqueryislookingforvaluesinPORT_NAMEwithanyonerandom
characterinthefirstposition,followedbythelowercaseletterointhesecond
position,followedbyanywherefromzerotoanalmostinfinitenumberof
charactersafterthelettero.Thefollowingrowsmatchtherequest:
WhenworkingwithLIKE,youputthewildcardcharacter(orcharacters)
withinastringenclosedinsinglequotes.Thestringmustoccurafterthereserved
wordLIKE,notbefore.Inotherwords,thefollowingissyntacticallycorrectbut
doesn’tperformasyoumightthinkitshould:
Thisqueryisaskingwhetherthestringliteral'G_and%'happenstomatchthe
valuecontainedwithinPORT_NAME.Thisprobablyisn’twhatwasintended.
Thepointhereisthatthewildcardcharactersare“activated”onlyifthepattern
containingthemisontherightsideoftheLIKEreservedword.Thisisthequery
thatwasprobablyintended:
ThisquerywouldfindarowcontainingaPORT_NAMEvaluesuchasthis:
GrandCayman
Soremember,placethepatternafterLIKE,notbefore.Oraclewon’t
complainifyouscrewitup.Butyouroutputprobablywon’tbewhatyou’re
intending.
BooleanLogic
TheWHEREclauseincludessupportforBooleanlogic,wherebymultiple
expressionscanbeconnectedwithaseriesofBooleanoperators.Thissection
looksatthoseoperators,whattheyare,howtheyareused,andtheirorderof
precedence.
AND,OR
MostWHEREconditionsinvolvemorethanjustonecomparisonoftwo
expressions.MostWHEREclausescontainseveralsuchcomparisons.Thisis
wheretheBooleanoperatorscomein.Twoormorecomparisonsofexpressions
canbeconnectedbyusingvariouscombinationsoftheBooleanoperatorsAND
andOR.There’salsoathirdoperator—NOT—anditcanbeusedtoinvertan
ANDorORcondition.Booleanoperatorsevaluatemultiplecomparison
expressionsandproduceasingletrueorfalseconclusionfromtheseriesof
comparisons.Here’sanexample:
Let’sbreakthisdownthewayOracleSQLdoes.Considerthefollowingdata
listing:
Foreachrow,theWHEREconditionwilldothefollowing:
DeterminewhethertheSHIP_IDvalueequals3
DeterminewhethertheSTATUSvalueisequaltothestring'Pending'
Theresultsforeachrowareasfollows(Note:theitalicizedcolumnsarenot
outputlistings,butananalysisofBooleanoperatorcalculations):
Nowlet’sapplytheANDoperatortoeachrow:
TherulesofBooleanoperatorevaluationarethesameastheyarein
conventionalmathematics.SeeTable4-3foralistingofallthepossibleresults
ofBooleanoperatorexpressions.
TABLE4-3 BooleanExpressionCombinationsandResults
TherulesforBooleansare
ForAND,bothexpressionsmustbetrueforthecombinationtobe
true.Otherwise,theanswerisfalse.
ForOR,atleastoneexpressionneedstobetrueforthecombination
toevaluatetotrue.Otherwise,theanswerisfalse.
ThebasicsyntaxforaSELECTstatementwithaWHEREclausethat
includesBooleansisasfollows:
Lines4and6representthesamething—acomparisonoftwoexpressions.
AsingleWHEREclausemayincludeasmanyofthesecomparisonsasare
required,indicatedonline4andalsoonline6—providedtheyareeach
separatedbyaBooleanoperator.
NOT
ThereservedwordNOTispartofthesetofBooleanoperators.Itcanbeplaced
infrontofanexpressiontoreverseitsconclusionfromtruetofalse,orvice
versa.
Forexample,let’smodifyaSELECTstatementyousawearlier:
InthisSELECT,we’veaddedthereservedwordNOTonline5toreversethe
findingsofthecomparisonofthestring'Pending'tothevaluesinthecolumn
STATUS.IfyouweretorunthisversionoftheSELECTagainstthesamethree
rowsyouusedearlier,you’dgetaverydifferentresult:norowsreturned.Hereis
why:
WithanANDoperatorstillinusehere,nowourSELECTstatementwillreturn
norowssinceANDrequiresbothsidestobetrueandnorowssatisfythis
criteria.
Let’slookatanotherexample:
Asyoucanseefromthisexample,NOTcanbeusedwithoutanyotherBoolean
operators.Whilewe’reatit,theuseofNOTwejustconsideredhasthesame
effectasthis:
orasthis:
Both<>and!=inthesecontextshavethesameeffectastheuseoftheNOT
operator.
Ifyou’reanexperiencedprogrammerandhaveusedlanguagessuchas
Oracle’sPL/SQL,thissectionmayhaveyouwonderingwheretheBOOLEAN
datatypefitsintoSQL.Itdoesn’t.ThereisnoBOOLEANdatatypeinSQL.
ThereisinPL/SQL,butnotinSQL.Instead,expressionsarecomparedto
eachothertodetermineaBooleanconditionofTRUEorFALSE,andthe
Booleanoperatorscomparethemtodetermineananswer.Theconceptsof
TRUEandFALSEaresignificantthroughoutSQL,asweseewiththe
WHEREcondition.ButtherearenospecificdatatypesthatrepresentBoolean
values.
OperatorPrecedence
Justasthereisasetofrulesregardingtheorderofevaluatingarithmetic
operatorswithinexpressions,sotooarethererulesforevaluatingBoolean
operators.It’simportantthatyouremembertheorderinwhichSQLevaluates
Booleanoperators.
Thebottomline:NOTisevaluatedfirst.Afterthat,ANDisevaluatedbefore
OR.
Forexample,considerthefollowingdatalistingforatablecalled
SHIP_CABINS:
NowconsiderthisSQLstatementagainstthedatalisting:
Howmanyrowsdoyouthinkthisquerywillretrieve?Areyouthinking...
threerows,byanychance?Ifyouare,you’renotalone;mostpeopletendto
thinkthat.But,you’llreallygetfiverows.Why?Becauseoftherulesof
Booleanoperatorprecedence.AnEnglish-speakingpersonmightreadthatquery
asaskingforallrowswithaSTYLEvalueofeither'Suite'or'Stateroom'and
alsowithavalueforWINDOWof'Ocean'.ButSQLseesthisdifferently—it
firstevaluatestheANDexpression.SQLislookingforalltherowswhere
STYLEis'Stateroom'andWINDOWis'Ocean'...OR....anyrowwitha
STYLEvalueof'Suite',regardlessofitsvalueforWINDOW.Inotherwords,
it’sdoingthis:
Remember,onlyonesideinanORmustbeTRUE.Andgiventhiscriterion,
allfiverowswillevaluatetotrue.
YoucanuseparenthesestooverridetherulesofBooleanoperatorprecedence,
likethis:
Thatquerywillretrievethreerows.
AdditionalWHEREClauseFeatures
TheWHEREclauseofferssomeoptionstostreamlinethereadabilityofyour
code.ThissectiondescribesfeaturesthatareimportanttoadvancedWHERE
clauseusage.
IN
Sometimesyou’llfindyourselfcomparingasinglecolumntoaseriesofvarious
values.Here’sanexample:
Thatqueryiscorrect,butinsuchsituations,youhavetheoptionofchoosing
adifferentstyle.YoumaychoosetousethereservedwordINasanalternative.
Here’sanexample:
TherulesthatgoverntheuseoftheINoperatorincludethefollowing:
INcanbeusedwithdates,numbers,ortextexpressions.
Thelistofexpressionsmustbeenclosedinasetofparentheses.
Thelistofexpressionsmustbeofthesamedatatype—orbesimilar
enoughthatOraclecanperformautomaticdatatypeconversiontomake
themallthesame.
Thelistcanincludeanywherefromoneexpressiontoseveral,each
separatedbycommas.
Inaddition,theBooleanoperatorNOTmayprecedetheINoperator,as
follows:
TheuseofNOTwillidentifyrowsastrueiftheydonotcontainavaluefromthe
list.
You’llseelaterthatthereservedwordINisparticularlyimportantinthe
WHEREclausewhenwe’reusingsubqueries,whichwe’lldiscussinChapter9.
BETWEEN
Inadditiontotheformatswe’veseensofar,theWHEREclausesupportsa
featurethatcancompareasingleexpressiontoarangeofvalues.Thistechnique
involvesthereservedwordBETWEEN.Here’sanexample:
Thisistheequivalentofthefollowingstatement:
NoticethatBETWEENisinclusive.Inotherwords,itdoesn’tsimplylookfor
values“between”thetwocomparisonexpressions,butalsoincludesvaluesthat
areequaltothecomparisonexpressions.
Therangecanbespecifiedusinganyvalidexpression.
Therangeshouldbefromlowesttohighest.Ifyouspecifythehighervalue
firstandthelowervaluesecond,yourcodewillbeacceptedsyntacticallybut
willalwaysreturnzerorows.
TheNOTkeywordmayalsobecombinedwithBETWEEN.Thefollowing
arevalidstatements:
Thesetwoexamplesareequivalenttoeachother.
ISNULL,ISNOTNULL
RememberthattheNULLvaluerepresentsanunknownvalue.NULListhe
equivalentof“Idon’tknow.”Anyvaluethat’scomparedto“Idon’tknow”is
goingtoproduceanunknownresult—inotherwords,NULL.Here’san
example:
ThisSQLstatementwillneverretrieveanyrows,neverever,nevereverever.
Don’tbelieveme?Tryit,I’llwait.
Toldyou.Itwillnoteverretrieveanyrows,notevenifthevaluefor
CAPACITYisNULLwithinagivenrow.ThereasonisthatthisisaskingSQL
tocompareCAPACITYtoavalueof“Idon’tknow.”Butwhatifthevalueof
CAPACITYinthedatabasetableisactuallyNULL?Shouldn’tthisworkthen?
Shouldn’tyoubeabletoaskifCAPACITY=NULL?Whyisn’ttheexpression
NULL=NULLtrue?
Well,letmeaskyouthis:I’mthinkingoftwonumbers,andI’mnotgoingto
tellyouwhateitheroneofthemis.Instead,I’mjustgoingtoaskyouthis:are
thesetwonumbersequaltoeachother?Well?Arethey?
Ofcourseyoucan’tpossiblyknow.Ithinkyou’dhavetosaytheansweris“I
don’tknow,”orNULL.AndNULL,intermsofBooleanlogic,isalways
assumedtobeFALSE.So,anytimeyoucreateaWHEREconditionthatendsup
as“anything”=NULL,theanswerwillalwaysbeFALSE,andyou’llnevergeta
row—evenifthe“anything”isNULLitself.
Butwhatdoyoudowhenyoureallyneedtotestthevalueofsomethinglike
CAPACITYtodeterminewhetheritisNULLornot?Thereisananswer,andit’s
theSQLcomparisonconditionISNULLanditscompanionISNOTNULL.
Let’sredoourSELECTstatement:
Nowyou’reaskingforrowsfromthePORTStablewherethevaluefor
CAPACITYisunknowninthedatabase—whichiswhatISNULLasksfor.
That’saverydifferentquerythanaskingifCAPACITYhappenstobeidentical
tosomenumberthatwehaven’tidentifiedyet—whichiswhat=NULLasks.
TheoppositeoftheISNULLcomparisonoperatorisISNOTNULL,like
this:
Inthisquery,you’reaskingforallrowsinwhichtheCAPACITYvalueis
identifiedinthedatabase,inotherwords,whereveritisnotNULL.
Theseconceptsareimportant.Thisisyetanotherexampleofoneofthemany
waysinwhichSQLcodemightappeartobecorrect,mightexecutewithoutany
syntaxorexecutionerrors,andyetcanbetotallywrong.
Besureyougetthisright.Don’tscrewitup.Ifyoudo,theproblemswillbe
subtleandpotentiallydisastrousandmightbecomeapparentonlymonthslater
afterbaddataandincorrectreportshavebeencirculated.So,remember,never
usethis:
=NULL
Thereisneveragoodreasontousethat,ever.Alwaysusethisinstead:
ISNULL
Gotit?
AdditionalConcepts
TherearemorewaystocustomizeaWHEREclausethanwhathasbeen
presentedhere.Upcomingtopicsthatwillbeaddressedinthisbook—andtested
ontheexam—includethefollowing:
Subqueries
Setoperators
TheseandotherissuesareimportanttotheWHEREclauseandimportantto
theexam.Theywillbecoveredontheirowninupcomingchapters.
CERTIFICATIONOBJECTIVE4.03
UseAmpersandSubstitutiontoRestrictandSort
OutputatRunTime
Theinclusionoftheampersandsubstitutionvariableasanexamobjectiveisa
bitunusualinthatitrepresentsaSQL*Plusfeaturetobeaddressed.Allother
examobjectivesfocusonOracle’simplementationoftheSQLlanguage,
includingANSIstandardSQLaswellasOracle’senhancements,suchasthe
DECODEfunction.Buttheampersandsubstitutionvariableisafeatureof
SQL*Plusexclusively.SQL*PlusisatoolforworkingwithOracle’srelational
databasebyusingSQLcommandsinteractivelyorviabatchprocessing,andit
offersseveraluniquecommands,systemvariables,andothercapabilities,allof
whichareuniquetoSQL*Plus.Theampersandsubstitutionvariableisoneof
thoseSQL*Plusfeatures,butitisnotpartoftheSQLlanguage.Youwon’tfinda
descriptionofitintheOracleSQLLanguageReferencemanual,not,atleast,at
thetimeofthiswriting.ButyouwillfinditdescribedinOracle’sSQL*Plus
documentation.
ThepurposeofampersandsubstitutionistoprovideaSQLscriptwitharun-
timeparameterfeaturewhenusedwithinSQL*Plussessions.Thevalueofthe
parametercanbesetviabatchbeforeorinteractivelyduringagivenSQLscript’s
execution.Eitherway,thepointistodecouplethevalueoftheparameterfrom
thescript,empoweringanindividualscripttoexecuteinavarietyofways.
Furthermore,thesubstitutionvariablecanrepresentanyaspectoftheSQL
script.ItcanbeusedtospecifyavalueinaWHEREclause,acolumnina
SELECTstatement,thenameofatable,orvirtuallyanyportionofthecode
withinascript,includingkeywords,SQLcommands,ordataofanykind,such
asinputdataforanINSERTorUPDATEstatement,thecriteriaofaHAVINGor
GROUPBY,oranything.
Tofullyleveragethepoweroftheampersandsubstitutionvariable,youneed
toknowmorethanthevariable.Thereareavarietyofsurroundingcommands
youshouldunderstandtoconfigureandimplementtheampersandsubstitution
variable.Thissectiondescribesthosesupportingfeatures,allofwhichmay
appearontheexam.
Inthissection,we’lllookattheampersandsubstitutionvariableitselfand
howtouseitduringexecution.Nextwe’llpredefineavalueusingtheSQL*Plus
commandsDEFINEandUNDEFINE.Thenwe’lldiscusshowSQL*Plussystem
variableswork,afterwhichwewilllookattwoofimportanceforourdiscussion:
theVERIFYsystemvariableandtheDEFINEsystemvariable(nottobe
confusedwiththeDEFINEcommand).Finally,we’lldiscusstwoadditional
SQL*Pluscommandsthatyoucanusewithsubstitutionvariables:ACCEPTand
PROMPT.
&
Let’slookatanexampleoftheampersandsubstitutionvariablebyusingthe
SHIP_CABINStable.Let’ssaythetablecontainsthefollowingrowsofdata:
HereisascriptthatwillquerySHIP_CABINSanduseanampersand
substitutionvariableontheendofthethirdlinetoenableustosettheWHERE
criteriaatexecutiontime:
Oncewehavecreatedthisscript,wecanexecuteitandspecifythevaluefor
ROOM_NUMBER.RefertoFigure4-7toseewhathappenswhenweexecute
thisscriptwithinaSQL*Plusclient.
FIGURE4-7 Usinganampersandvariabletospecifyroomnumberatrun
time
Duringexecution,thepresenceoftheampersandsubstitutionvariabletriggers
an“Entervalueforrno:”requestfromthesystem.Inresponse,wetype104and
pressENTER.Thesystemthendisplaystheoldline3,aswellasthenewline3
showinghowthevaluefor“rno”hasbeenreplacedwith104.Finally,the
statementisexecutedasthough104hadbeenintheplaceof“rno”allalong,and
weseetheresult:areturnofrowswhereROOM_NUMBER=104.
Theampersandsubstitutionvariableconsistsofthefollowing:
Thesubstitutionvariableprefix(anampersand)
Thesubstitutionvariablename,consistingofanysubsequent
contiguoussetofalphanumericcharactersuntilthenextblankspace
Thevariablenameyouspecifywillberepeatedatruntimeinthecontextofa
question,asyoucanseeintheexample.IusedthenameRNO,butyoucould
haveusedsomethingmoredescriptive,perhapsRoom_Numberorsomething.
Inourexample,weusedthesubstitutionvariabletoprovideavaluefora
numericcolumnatruntime.Butwhatabouttextvalues?Thesubstitution
variablecanbespecifiedwithinquotesintheSQLstatement.Here’sanexample:
Let’sseewhathappenswhenweexecutethiswithinaSQL*Plusclient;see
Figure4-8.
FIGURE4-8 Usinganampersandvariablewithquotes
Asyoucanseeintheexample,thesubstitutionvariableusedfromwithin
quotesworksjustthesame.Alternatively,youcanomitthequotesintheSQL
andchooseinsteadtoprovidethequotesatruntime(seeFigure4-9).
FIGURE4-9 Usinganampersandvariablewithoutquotes
Notehowwejustusedasinglesubstitutionvariableintheplaceofacolumn
listoftheSELECTstatement.Atruntime,whenprompted,wetypedinthe
namesoftwocolumns,separatedwithacomma.Thesetwonamesare
substitutedatruntime,andthecodeexecutesaccordingly.
Sofarwehaveworkedwiththesubstitutionvariablebyspecifyingitsvalue
atruntime.Butyoucanpredefineitaswell,usingtheSQL*Pluscommand
DEFINE.
DEFINEandUNDEFINECommands
Youcanuseasinglestatementonitsowntodefineasubstitutionvariableusing
theDEFINEstatementsothatwhenSQLcodewithasubstitutionvariableis
executed,thevalueyou’vealreadydefinedwillbeused.Here’sanexample:
DEFINEvWindows=Ocean
Notethatweomitthesubstitutionvariableprefix;thereisnoampersandat
thebeginningofthevWindowssubstitutionvariable.
Tolistallexistingdefinedvariablesforagivensession,useDEFINEona
linebyitself,likethis:
DEFINE
Alsonote:WechosetoexecutetheSQL*PluscommandDEFINEwithouta
semicolonattheend.SQLcommandsrequireasemicolonattheend;SQL*Plus
commandsdonotrequirethem,yettheydoacceptthem.Soyoumaychooseto
includeoromitthem.SQLcommandsrequiresemicolons.ButforSQL*Plus
commands,semicolonsareoptional.
Thescopeofthesubstitutionvariableisthesession.Oncedefined,the
variablewillpersistthroughthesessionoruntilitis“undefined.”
UNDEFINEvWindows
WithoutanUNDEFINE,thevWindowssubstitutionvariablewillpersistfor
thedurationoftheloginsession.WewilluseDEFINEwithaseriesofSQL
statementstoseehowitworks.Butfirstlet’salsolookatSETandSHOW.
TheSETandSHOWCommands
TheampersandsubstitutionvariableisaSQL*Pluscommand,anditsbehavioris
controlledbythesettingsofsomeoftheSQL*Plussystemvariables.SQL*Plus
includesanumberofsystemvariablesthatcanbeconfiguredusingtheSET
command.Thecurrentconfigurationofasystemvariablecanbedisplayedusing
theSHOWcommand.Foranexample,seeFigure4-11.
FIGURE4-11 SHOW
SHOWcanbeusedwithanyoftheSQL*Plussystemvariablestodisplaythe
particularsystemvariable’scurrentstate.Agivensystemvariable’scurrentstate
consistsofwhetheritisONorOFFandoptionallymayincludeconfiguration
detailsuniquetothesystemvariable.
Toseethefullsetofallsystemvariablesandtheirstate,useSHOWALL.
Forthepurposesofworkingwiththesubstitutionvariable,weareprimarily
interestedintwoparticularsubstitutionvariables:VERIFYandDEFINE.Let’s
lookatbothinmoredetail.
TheVERIFYSystemVariable
NotehowSQLhasbeeninformingusofthe“old”and“new”linesofcodefor
eachsubstitutionvariable.ThiscanbeturnedonoroffusingaSETVERIFY
statement.
SETVERIFYOFF
Onceoff,the“old”and“new”lineswillnolongerdisplay.Alternatively,you
canuseanabbreviatedversionofVERIFY.
SETVEROFF
TorestoreVERIFY,turnitbackon.
SETVERIFYON
SettingVERIFYbacktoONwillensurethe“old”and“new”linesappear
whenusingadefinedvariableinyourSQLscript.
ACCEPTandPROMPT
TwoadditionalSQL*Pluscommandsareusefulwhenworkingwithsubstitution
variables.PROMPTisacommandtodisplayaninteractivemessagetoanend
user.ACCEPTwillreceivedatafromausertostoreinapredefinedvariable.
Together,thesetwocommandsarecommonlyusedininteractivescriptswhere
SQL*Plussubstitutionvariablesareinuse.
Foranexample,let’spromptanendusertotypeinanumber,acceptthe
typednumberasthevalueforavariablewe’llnamevRoomNumber,andthen
incorporatethevariableintoaSQLscript.
Next,we’llstoretheSQLscriptinasimpletextfilethatwe’llname
The_Script
.sql.We’llstorethefileinthedefaultfolderofourlocalSQL*Plusclientand
executethefile.SeeFigure4-12fortheresults.
FIGURE4-12 ACCEPTandPROMPT
NotethatPROMPTdoesnotrequirequoteswheninvokedasastand-alone
statementbutdoesrequirethemwhenusedinconjunctionwithACCEPT.
Inourexample,theenduserprovidesaroomnumberof104,andthe
subsequentSQLscriptreturnstheappropriaterow.UsingPROMPTyoucan
createamoremeaningfulquestionoftheenduser.BycombiningPROMPTwith
ACCEPTyoucanacceptananswerfromtheenduserandstorethevalueina
variableyoureferencelaterintheSQLscript.
Animportantnote:Weincludedaperiodattheendofourdefinedvariable,
yettheperioddidnotdisplayinteractively.Hadweaddedaspaceafterthe
definedvariableandbeforetheperiod,theperiodwouldhavedisplayed.Forthat
matter,anyadditionaltextafterthedefinedvariablewilldisplay,provideditis
separatedfromthedefinedvariablewithoneormorespaces.
Youcanuseanysimpletexteditortocreatebatchscriptsforprocessingby
SQL*Plus.IuseNotepadorUltraEdit.Youshouldsavethescriptinafile
endingwiththe*.SQLsuffix,butthisisnotrequired.Forexample,ifyou
createafilecalledRun.sqlandthensaveitonyouroperatingsystem
somewhere,youcaninvokeitfromwithinSQL*Plusbytyping@[folder
location]Run,where@tellsSQL*Plustoexecutethescript,[folderlocation]is
thelocationofthefile,RUNisthefileprefix,andthe.SQLfilesuffixis
assumed.Alternatively,youcanuse@[folderlocation]Run.SQL.Thespecific
folderlocationisimplementationspecific,andyoushouldcheckwithyour
localdatabaseadministratorand/ordocumentationtodetermineitslocation.
TheDEFINESystemVariable
Tousethesubstitutionvariable,theDEFINEsystemvariablemustbesettoON.
ThedefaultsettingforDEFINEisONforagivensession,soyougenerallydon’t
needtospecificallysetit.Buttobesure,youcanensurethatDEFINEisON
beforeyouusethesubstitutionvariablebyexecutingthefollowingSQL*Plus
statementpriortoanyuseofasubstitutionvariable:
SETDEFINEON
Thisisparticularlyimportantifyouarecreatingabatchscriptandyouwon’t
necessarilyknowatthetimethebatchscriptisexecutedwhetherthedefaultON
valueofDEFINEisset.ItmightbeturnedOFF.SettingittoONexplicitlywhen
itisalreadyONwillnottriggeranycomplaintsfromthesystem.So,itis
commonpracticetouseSETDEFINEONatthebeginningofabatchscriptthat
usesit.
TosetDEFINEtoOFF,usethis:
SETDEFINEOFF
NotethatSQL*Plusstatementsdonotrequireasemicolonattheend.You
canusethemifyouwant,buttheyarenotrequired.
Theexamobjectivesspecificallyrefertothesubstitutionvariableasthe
“ampersandsubstitutionvariable,”buttheampersanditselfcanbechangedwith
avariationoftheSETDEFINEcommandthatdoesn’tuseeitherONorOFFbut
insteadresetsthesubstitutionvariableprefixcharacter.Here’sanexample:
SETDEFINE*
ThisSETDEFINE*statementwillchangethesubstitutionvariableprefixto
anasterisk.Let’sseeitinactionwithacombinationofstatements.Forthis
example,we’llsetasystemvariablewehaven’tusedyet,ECHO.SettingECHO
toONisusefulwhenexecutingaseriesofstatementsinbatch;ECHOensures
ourstatementsthemselveswilldisplay,notjusttheiroutput,sowecanseethe
fulleffectofourscript.
Next,we’llsetVERIFYtoOFFsothe“old”and“new”lineswon’tdisplay
wheneverweinvokeasubstitutionvariable.
Next,we’llsetDEFINEtoOFFanduseSHOWtoconfirmthatDEFINEhas
infactbeenturnedoff.Butthenwe’lluseSETDEFINEtochangetheprefix
fromthedefault(oftenanampersand)totheasterisk.ThenwewilluseSHOW
DEFINEagaintoseethatthedefaultprefixhasinfactbeenresetandthatthe
DEFINEsystemvariableisnolongerOFF;changingthedefaultprefixhasthe
by-productofalsoturningtheDEFINEsystemvariablebacktoON.
Next,we’lltrytouseasubstitutionvariablewiththeampersand,butsince
we’vechangedtheprefixtosomethingelse,theampersandwillnolongerbe
recognizedandinsteadwillbetreatedasstandardtext.
Finally,we’llrepeatthesameSQLscript,butusingthenewlyspecified
substitutionvariable’sprefixofanasterisk,andwe’llseethattheSQLstatement
producestheoutputwe’reexpecting.
Notethatthesubstitutionvariableprefixislimitedtoonecharacteronly.
Also,ifDEFINEissettoOFFandyouchangetheprefix,youwillalso
automaticallysetDEFINEtoON.
CERTIFICATIONOBJECTIVE4.04
UsetheSQLRowLimitingClause
YoucanusetheSQLrowlimitingclausetoreturnonlyasubsetofthatdata.The
SQLrowlimitingclauseisnewwithOracle12c.Itcanbeusedafterany
WHEREorORDERBYclausetolimitthenumberorpercentageofrowstobe
returnedbyaquery.Granted,allWHEREcriteriaarealreadyintendedtolimit
returneddatafromalogicalstandpoint—that’stheentirepurposeoftheWHERE
clause.Buttherowlimitingclausetakesamuchbroaderview.Whereasother
aspectsofyourqueryaregenerallyfocusedonbusinesslogic,therowlimiting
clausecanbeusedtochoose,forexample,onlythefirst10rowsofquerieddata,
theseconddozenrows,orthelast50rows.
FETCH
LimitsontherowsreturnedbyaSELECTstatementarespecifiedbytheFETCH
statement.HereisanexampleofasingleSELECTstatementusingtheSQLrow
limitingclause:
ThekeywordFETCHsignifiesthepresenceoftherowlimitingclause.Inthis
example,thequerywillreturnuptoeightrowsandnomore.Forexample,if
onlysixrowsexist,thenallsixwillbereturned.If500rowsexist,only8willbe
returned.
FETCHcanspecifyanumberofrows,aswejustsaw,orapercentage,like
so:
TheFETCHclauseconsistsofthefollowingrequiredkeywordsandoptions:
ThekeywordFETCH(required).
EitherthekeywordFIRSTorthekeywordNEXT(oneisrequired).
Eitherisacceptable,andthereisnofunctionaldifferencebetweenthe
two;theoptionisavailableforgrammaticalreadabilityonly.
Avalidexpressionthatevaluatestoanumber(optional).
IfnonumericvalueispresentbuttherestoftheFETCH
keywordsareinplace,FETCHwilldefaulttoonerow.
AnoptionalkeywordPERCENTiftheimmediatelypreceding
numberistobeinterpretedasapercentageinsteadofanumeric
value.PERCENTwillneverreturnapartialrow,andpercentagesare
roundeduptothenearestnumberofrows.Forexample,ifyou
specifyafetchof1PERCENToffouravailablerows,onerowwill
bereturned.Ifyouspecify26PERCENToffouravailablerows,two
rowswillbereturned.
EitherthekeywordROWorthekeywordROWS(oneisrequired).
JustliketheFIRST/NEXTkeywords,eitherROWorROWSis
acceptable,andthereisnofunctionaldifferencebetweenthetwo;the
optionisavailableforgrammaticalreadabilityonly.
EitherthekeywordONLYorthekeywordsWITHTIES(oneis
required).
ONLYwillreturnthenumberorpercentageofrowsspecified
andnomore.
WITHTIESisbestunderstoodwithanexample,butinshort,
WITHTIESwillreturneverythingreturnedbyONLYbutpossibly
withsomeadditionalrows.Thoseadditionalrowswillbeconsidered
onlyifanORDERBYclauseisincludedintheSELECTandthat
ORDERBYsortsrowsinsuchawaythattherearerowsremaining
thatwerelogicallyconsistentwiththeparticularORDERBYclause
butarbitrarilyomittedtosatisfytherowlimit.Thisrequiressome
explanationandisbestillustratedwithanexample;seethenext
section.
WITHTIES
WITHTIESis“tied”totheORDERBYclause.WithoutORDERBY,WITH
TIESwillbehavethesameasONLY.
Let’sconsideranexampleofWITHTIES.Let’ssayyouhaveeightrowsina
tableORDERS,fiveofwhichhaveavalueintheLINE_ITEMScolumnof2.If
yousorttherowsbyLINE_ITEMSandthenFETCHFIRST50PERCENT
ROWSONLY,you’llgetthefirstfourrowsreturnedbytheORDERBYclause,
asshowninFigure4-14.
FIGURE4-14 SELECTwithFETCH
Thatmakessensebecausethereareeightrowsintotal,so50percent—half—
isfourrows.However,yourORDERBYclausesortedrowsbyLINE_ITEMS,
andthenumberofrowswithaLINE_ITEMvalueof2doesn’tconveniently
breakat50percent,sothereareadditionalrowswithaLINE_ITEMof2that
didn’tmakethecut.
There’snothinginherentlyrightorwrongaboutthatapproach.Ifyour
objectiveistoonlyget50percentoftherowsanditdoesn’tmattertoyour
businessobjectivesthatthelinewasarbitrarilydrawnthroughthesetofrows
whereLINE_ITEM=2,thenyou’refine.
Butwhatifyourobjectiverequiresyoutoincludethoseadditionalrows
whereLINE_ITEM=2?Ifyourobjectiveislessconcernedwithanarbitrary
breakpointandmoreconcernedwithincludingalogicallyconsistentsetofrows,
youcanusetheWITHTIESclause.
So,let’sedittherowlimitingclausetoinsteadbeFETCH50PERCENT
ROWSWITHTIES.Theresult:we’llgetthesame50percentreturnedinthe
immediatelyprecedingexampleplusanyadditionalrowswiththesamevalue
specifiedintheORDERBYcriteria,asshowninFigure4-15.
FIGURE4-15 SELECTwithFETCH…WITHTIES
NotethatwhenwecombineORDERBYandaFETCH…WITHTIES,we
endupwiththefirst50percentplusallrowsthatlogicallyequatetothe
LINE_ITEMvalueatthecutoffpoint.
WesaidthatWITHTIESis“tied”totheORDERBYclause.Whatifwe
omittedtheORDERBYclause?SeeFigure4-16.
FIGURE4-16 SELECTwithFETCH…WITHTIES,noORDERBY
WithoutORDERBY,WITHTIEShasnoeffect.WithoutORDERBY,the
useofWITHTIESproducesthesameresultasifwehadexecutedFETCH…
ONLY.Wedidn’tgetasyntaxerror.Wesimplyreceivedthesameresultsasif
we’dusedFETCH…ONLY.
OFFSET
Bydefault,therowlimitingclausewillstartwiththefirstreturnedrow,butyou
canoptionallyspecifythattheFETCHstartelsewhere,atsomespecificnumber
ofrowsintotherange.Here’sanexample:
Inthisexample,theFETCHwillskipthefirstfiverows,startatthesixthrow,
andreturnthesixthandseventhrows,foratotaloftworowsreturned.
Thefollowingtablelistswhathappenswithvariousspecificationsof
OFFSET:
CERTIFICATIONSUMMARY
TheORDERBYclauseoftheSELECTstatementisthemethodforsortingthe
rowsofoutputreturnedbytheSELECTstatement.TheORDERBYclauseis
optional,butifincludedinaSELECTstatement,itisalwaysthefinalclauseof
theSELECTstatement.
ORDERBYspecifiesoneormoreexpressions.Eachexpressionisusedby
ORDERBYtosorteachrowintheresultset.Outputrowsaresortedfirstbythe
firstexpression,andforanyrowsthatsharethesamevalueforthefirst
expression,thoserowswillbesubsortedforthesecondexpression,andsoon.
ExpressionsforORDERBYfollowthesamerulesasexpressionsinthe
SELECTstatement’sselectlistandtheWHEREclause.Eachexpressionshould
ideallyreferenceacolumninthetable,butthisisn’trequired.
TheASCandDESCreservedwordscanbeusedinanORDERBYclauseto
determinethedirectionofsortingforeachindividualexpression.ASCwillsort
valuesinascendingorder,andDESCwillsortindescendingorder.ASCisthe
defaultanddoesnotneedtobespecified.ThespecificationofASCorDESC
shouldfolloweachexpressionwithaspaceseparatingthem.
ORDERBYsortsvaluesaccordingtodatatypes.Withnumericdatatypes,
lownumbersarelow,andhighnumbersarehigh;withdates,yesterdayislower
thantomorrow,andnextweekishigherthanlastmonth;withcharacters,Zis
lessthana,andthecharacterstring'10'islessthanthecharacterstring'3'.
ORDERBYcanspecifyexpressionsintheSELECTstatement’sselectlistby
referencingthecolumnalias,ifonewascreatedwithintheSELECTlist.
ORDERBYcanalsoidentifyexpressionsintheSELECTlistbythenumber
correspondingtothepositionoftheitemintheSELECTlist;forinstance,
ORDERBY1willsortbythefirstitemintheSELECTlist.
ORDERBYcancombineallofthesefeaturesintooneseriesoforderitems.
Acolumnalias,ifspecifiedintheselectlist,isnotrecognizedinthe
WHERE,GROUPBY,orHAVINGclause.
TheWHEREclauseispartoftheSQLstatementsSELECT,UPDATE,and
DELETE.ItisusedtoidentifytherowsthatwillbeaffectedbytheSQL
statement.FortheSELECTstatement,WHEREdetermineswhichrowsare
retrieved.FortheUPDATEstatement,itdetermineswhichrowswillbeupdated.
FortheDELETEstatement,itdetermineswhichrowswillbedeleted.The
WHEREclauseconcernsitselfwithentirerows,notjustthecolumnsthatarethe
subjectoftheparticularSQLstatementofwhichitisapart.TheWHEREclause
canreferencecolumnsthatarenotintheSELECTlist.
TheWHEREclauseisoptional.IfincludedinaSELECTstatement,itmust
followtheFROMclause.
TheWHEREclausecomparestwoexpressionsanddetermineswhetherthe
resultofthecomparisonistrueorfalse.Atleastoneofthetwoexpressions
shouldincludeacolumnfromwhatevertabletheSQLstatementisintendedto
addresssothattheWHEREclauseisrelevanttotheSQLstatement.The
expressionsarecomparedusingcomparisonoperators.Examplesincludethe
equalsign,thenot-equalsign,andthegreater-thanandless-thansigns.
AseriesofcomparisonscanbeconnectedusingtheBooleanoperatorsAND
andOR.TheNOToperatorcanalsobeincluded.Together,theseexpressionscan
formcomplexWHEREclauses.
TheLIKEoperatorcanactivatethewildcardcharacters.Thetwowildcard
charactersaretheunderscore(_)andthepercentsign(%).
TheINoperatorcancompareasinglevaluetoasetofvalues.Anexpression
usingtheINoperatorwillevaluatetotrueifthatsinglevaluematchesanyofthe
valuesintheexpressionlist.
WhenusingtheWHEREclausetolocaterowsthathaveaNULLvalue,never
usethe=NULLcomparison;instead,alwaysusetheISNULLorISNOTNULL
comparisonoperator.
TheampersandsubstitutionvariableisusedwithinSQL*Plustosupport
interactiveandbatchprocessing.Theampersandisaprefixthatcanbe
configureddifferentlywiththeSETDEFINEstatement.Thesubstitution
variablecanbeturnedonoroffwithSETDEFINEONorSETDEFINEOFF.
YoucanalsouseSETVERIFYtoturnonorofftheautomaticdisplayof
“old”and“new”linesofcodecontainingthespecifiedsubstitutionvariable
value.AnySQLscriptcanleveragethesubstitutionvariabletoreplaceanycode
orvaluewithinanysubsequentscript.
TherowlimitingclauseisnewtoOracle12c.Itspurposeistolimitthe
numberofrowsreturnedbyaSELECTstatement.Therowlimitingclauseis
specifiedwithFETCHandsyntacticallyfollowsORDERBY(ifitisincluded).
TheFETCHclausespecifiesarangeofrowstobereturnedasasubsetofthe
SELECTstatements.Therangecanbedeterminedbynumbersofrowsorasa
percentage.Ifnorangeisspecified,FETCHdefaultstoonerow.TheFETCH
keywordsFIRSTandNEXTbehavethesame,sodoROWandROWS;both
pairsareacceptableandexistforreadability.WITHTIEScanbeusedtoinclude
rowsthathaveidenticalsortedvaluesasspecifiedbyORDERBYandwould
otherwisebearbitrarilyomittedfromthereturnset.AnoptionalOFFSETvalue
canbeincludedtodeterminethestartingpointoftherange.OFFSETisspecified
bynumbersofrows(notapercentage).Ifomitted,OFFSETdefaultstozero,and
ifenteredasanegativenumber,OFFSETwillbetreatedasthoughzero.
✓TWO-MINUTEDRILL
SorttheRowsThatAreRetrievedbyaQuery
ORDERBYisanoptionalclauseusedtosorttherowsretrievedin
aSELECTstatement.
Ifused,ORDERBYisalwaysthelastclauseintheSELECT
statement.
ORDERBYusesexpressionstodirectthesortingorderoftheresult
setoftheSELECTstatement.
Eachexpressionisevaluatedinordersothatthefirstitemin
ORDERBYwilldotheinitialsortofoutputrows,theseconditemlisted
willsortanyrowsthatshareidenticaldataforthefirstORDERBY
element,andsoon.
ORDERBYcansortbycolumnsinthetable,regardlessofwhether
thecolumnsappearintheSELECTstatement’sselectlist.
ORDERBYcanalsosortbyexpressionsofanykind,followingthe
samerulesofexpressionsthatyou’veseenwiththeWHEREclauseand
theselectlist.
Numericdataissortedbydefaultinascendingorder,fromlower
numberstohigher.
Characterdataissortedbydefaultinascendingorder,fromAtoZ.
Datedataissortedbydefaultinascendingorder,frompriordatesto
laterdates.
Allsortsdefaulttoascendingorder,whichcanbespecifiedwiththe
optionalkeywordASC.
Sortordercanbechangedtodescendingorderwiththekeyword
DESC.
ORDERBYcanidentifycolumnsbycolumnaliasorbyposition
withintheSELECTlist.
LimittheRowsThatAreRetrievedbyaQuery
TheWHEREclausecomesaftertheFROMclause.
WHEREidentifieswhichrowsaretobeincludedintheSQL
statement.
WHEREisusedbySELECT,UPDATE,andDELETE.
WHEREisanoptionalclause.
ExpressionsformthebuildingblocksoftheWHEREclause.
Anexpressionmayincludereferencestocolumnnamesaswellas
literalvalues.TheWHEREclausecomparesexpressionstoeachother
usingcomparisonoperatorsanddetermineswhetherthecomparisonsare
trueorfalse.
Booleanoperatorsmayseparateeachcomparisontocreatea
complexseriesofevaluations.Collectively,thefinalresultforeachrow
inthetablewilleitherbetrueorfalse.Iftrue,therowisreturned;if
false,itisignored.
TheBooleanoperatorsareAND,OR,andNOT.
TherulesofBooleanoperatorprecedencerequirethatNOTbe
evaluatedfirst,thenAND,andthenOR.
ParenthesescanoverrideanyBooleanoperatorprecedence.
Whencomparingdatedatatypes,earlierdatevaluesareconsidered
“less”thanlaterdates,soanythinginJanuarywillbe“lessthan”
anythinginDecemberofthesameyear.
Whencomparingcharacterdatatypes,theletteraislessthanthe
letterz,uppercaselettersare“lowerthan”lowercaseletters,andthe
characterrepresentationof3isgreaterthanthecharacterrepresentation
of22,eventhoughtheresultswouldbedifferentiftheywerenumeric
datatypes.
LIKEcanbeusedtoactivatewildcardsearches.
INcanbeusedtocompareasingleexpressiontoasetofoneor
moreexpressions.
BETWEENcanbeusedtoseewhetheraparticularexpression’s
valueiswithinarangeofvalues.BETWEENisinclusive,notexclusive,
sothatBETWEEN2and3includesthenumbers2and3aspartofthe
range.
UseISNULLorISNOTNULLwhentestingacolumntosee
whetheritsvalueisNULL.
UseAmpersandSubstitutiontoRestrictandSortOutputatRun
Time
ThesubstitutionvariableisusedinbatchorinteractiveSQL*Plus
processing.
ItisnotaSQLfeature,butaSQL*Plusfeature.
ThesubstitutionvariablecanspecifyaWHEREclauseparameter,
ORDERBYoption,columnlist,tablename,anyportionoftheSQL
keyword,oranyportionoftextwithinaSQLscript.
ThesubstitutionvariableworkswithSELECT,INSERT,UPDATE,
orotherSQLstatements.
Theampersandcanberedefinedtoanalternativesinglecharacter.
VERIFYisasystemvariable;whensettoON,itensuresthatthe
useofasubstitutionvariablewilltriggerthedisplayofan“old”and
“new”lineoftext.
TheDEFINEsystemvariablespecifiestheprefixforusewitha
substitutionvariable.
ACCEPTcanbeusedtoacceptinteractivelyspecifiedvaluesfora
substitutionvariable.
PROMPTcanbeusedtoissuerichpromptquestionstoauser
duringaninteractiveSQL*Plussession.
UsetheSQLRowLimitingClause
FETCHisanoptionalclausethatfollowsWHEREandORDER
BY.
FETCHcanspecifyarangeintermsofanumberofrowsora
percentageofrows.
ExpressionscanbeusedinFETCHtospecifythenumberofrows
orpercentageofrows.
Ifnorangeisspecified,FETCHdefaultstoonerow.
AnexampleisFETCHFIRST20ROWSONLY;.
ThekeywordFIRSTcanbeexchangedwiththekeywordNEXT;
botharefunctionallyidentical,butoneofthetwokeywordsisrequired.
ThekeywordROWcanbeexchangedwiththekeywordROWS;
botharefunctionallyidentical,butoneofthetwokeywordsisrequired.
TheSQLrowlimitingclauserequireseitherthekeywordONLYor
thekeywordsWITHTIES.ONLYreturnsrowsthatmatchtheFETCH
criteriaonly.WITHTIESreturnsrowsthatmatchtheFETCHcriteria
andalsosatisfytheORDERBYclauseatthesameFETCHlogical
dividingpointintherange.
WithoutORDERBY,WITHTIESbehaveslikeONLY.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
SorttheRowsThatAreRetrievedbyaQuery
1.ReviewthisSELECTstatement:
Assumethatalltableandcolumnreferencesexistwithinthedatabase.
WhatcanbesaidofthisSELECTstatement?
A.TherowswillsortinorderbySHIP_IDandthenbyCAPACITY.
Allrowswillsortindescendingorder.
B.TherowswillsortinorderbySHIP_IDinascendingorderand
thenbyCAPACITYindescendingorder.
C.ThestatementwillfailtoexecutebecausetheORDERBYlist
includesacolumnthatisnotintheselectlist.
D.ThestatementwillfailtoexecutebecausethereisnoWHERE
clause.
2.ReviewthisSELECTstatement:
Assumealltableandcolumnreferencesexistinthedatabase.Whatcan
besaidofthisSELECTstatement?
A.Thestatementwillexecutesuccessfullyandasintended.
B.ThestatementwillexecutebutnotsortbecausetheORDERBY
clauseiswrong.
C.ThestatementwillfailtoexecutebecausetheORDERBY
clauseincludesthewordLIKE.
D.Noneoftheabove.
3.WhichifthefollowingistrueoftheORDERBYclause?(Choose
two.)
A.Itisoptional.
B.ItcanbeusedintheUPDATEstatementaswellasSELECTand
DELETE.
C.Itcansortrowsbasedondatathatisn’tdisplayedaspartofthe
SELECTstatement.
D.IfthelistofORDERBYexpressionsusesthe“byposition”
form,thenallexpressionsintheORDERBYmustusethe“by
position”form.
4.IfyouareusinganORDERBYtosortvaluesindescendingorder,in
whichorderwilltheyappear?
A.Ifthedatatypeisnumeric,thevalue400willappearfirstbefore
thevalue800.
B.Ifthedatatypeischaracter,thevalue'Michael'willappearfirst
beforethevalue'Jackson'.
C.Ifthedatatypeisdate,thevalueforJune25,2010,willappear
beforethevalueforAugust29,2010.
D.Ifthedatatypeischaracter,thevalue'130'willappearfirst
before'75'.
LimittheRowsThatAreRetrievedbyaQuery
5.ReviewthefollowingdatalistingforatableVENDORS:
NowreviewthefollowingSQLstatement:
HowmanyrowswilltheSELECTstatementreturn?
A.2
B.1
C.0
D.Nonebecauseitwillfailduetoasyntaxerror
6.ReviewthefollowingdatalistingforatablecalledSHIP_CABINS:
TheblankvaluesareNULL.NowreviewthefollowingSQLstatement
(linenumbersareaddedforreadability):
HowmanyrowswilltheSQLstatementretrieve?
A.0
B.1
C.2
D.Nonebecauseyoucannotuseparenthesesinline3tosurround
theexpressions
7.ReviewthefollowingdatalistingforatableSHIPS:
IntheSHIPStable,SHIP_NAMEhasadatatypeofVARCHAR2(20).
AllothercolumnsareNUMBER.Nowconsiderthefollowingquery(note
thatlinenumbershavebeenaddedforreadability):
HowmanyrowswilltheSELECTstatementreturn?
A.Nonebecauseofasyntaxerrorresultingfromadatatype
conflictinline4
B.Nonebecauseline5isaskingforSHIPnamesthatcontainan
underscoreafterthestring'Codd',andnonedo
C.2
D.1
8.AssumealltablenameandcolumnnamereferencesintheSQL
statementthatfollowsarevalid.Thatbeingsaid,whatiswrongwiththe
syntaxofthefollowingSQLstatement?
A.IntheWHEREclausethereisasyntaxerrorbeforetheword
CAPACITY.
B.Itneedstohaveeitheranequalsignoranot-equalsign.
C.IntheWHEREclausethereisasyntaxerrorafterthewordIN.
D.Thereisnothingwrongwiththesyntax.
9.ReviewthefollowingdatalistingfortheSHIPStable:
NowreviewthefollowingSQLstatement(linenumbersareaddedfor
readability):
WhichofthefollowingstatementsistrueaboutthisSELECT
statement?
A.Thesyntaxiscorrect.
B.Thesyntaxonlines3and4isincorrect.
C.Lines3and4havecorrectsyntaxbutcouldbereplacedwithOR
LIFEBOATSBETWEEN80AND100.
D.Line5ismissingparentheses.
UseAmpersandSubstitutiontoRestrictandSortOutputatRun
Time
10.Tolistallthecurrentlydefinedvariables,use:
A.SHOWALL
B.SHOWDEFINE
C.DEFINE
D.DEFINEALL
11.Youcanuseasubstitutionvariabletoreplace:
A.Afloating-pointvalueinaWHEREclause
B.ThenameofatableinaSELECTstatement
C.Neither
D.Both
12.Considerthefollowingtext:
Whatwillhappenwhenthisscriptisexecuted?
A.Theenduserwillbepromptedtoenteranumber.
B.ThescriptwillfailbecausevRoomNumberinthefirstlinedoes
nothaveanampersandprefix.
C.TheSELECTstatementwillfailbecausethesubstitution
variableshouldnotbeprefixedbyanampersandsinceitisalready
definedwiththeDEFINEstatement.
D.TheDEFINEstatementinline1shouldbeprecededbythe
keywordSET.
13.TopermanentlydeleteasubstitutionvariablenamedTHE_NAMEsothatit
cannolongerbeused,use:
A.UNDEFINETHE_NAME
B.SETDEFINEOFF
C.REMOVETHE_NAME
D.Youcannotdeleteasubstitutionvariable.
UsetheSQLRowLimitingClause
14.AssumeyouhaveatableITEMSthatincludesacolumnSTATUS.Whichof
thefollowingstatementsissyntacticallycorrect?(Chooseallthatapply.)
A.SELECT*FROMITEMSFETCHNEXT20%ROWSONLY;
B.SELECT*FROMITEMSFETCHNEXT20PERCENTROWS
ONLY;
C.SELECT*FROMITEMSFETCHNEXT20ROWSWITH
TIES;
D.SELECT*FROMITEMSORDERBYSTATUSFETCH
NEXT20ROWSWITHTIES;
15.Considerthefollowingstatement:
AssumeyouhaveatableITEMSwithacolumnLIST_DATE.Whatis
theresultofanattempttoexecutethestatement?
A.ItwillsorttherowsbyLIST_DATEandreturnonlythefirstfour
rows.
B.ItwillsorttherowsbyLIST_DATEandreturnonlythelastfour
rows.
C.Itwillfailwithasyntaxerrorbecauseoftheuseofanegative
numberwithOFFSET.
D.ItwillfailwithasyntaxerrorbecauseoftheuseofFIRSTand
OFFSETtogether.
SELFTESTANSWERS
SorttheRowsThatAreRetrievedbyaQuery
1. B.TheORDERBYclausewilldefaulttoascendingorderfor
SHIP_ID,butCAPACITYisexplicitlydirectedtosortindescendingorder.
A,C,andDareincorrect.TheDESCdirectiveappliesonlytothe
CAPACITYcolumnintheORDERBYclause,notbothitems.Thefactthat
theORDERBYclausereferencescolumnsthatarenotintheselectlistis
irrelevant;it’sfinetodothat.TheWHEREclauseisnotrequired;it’san
optionalclause,asistheORDERBYclause.
2. C.TheLIKEoperatorismeaninglessinORDERBY.
A,B,andDareincorrect.Thestatementwillcertainlynotexecute;itwill
failtoparsebecauseofthesyntaxerroroftheLIKEoperatorinthewrong
place.Giventhatitwon’tevenparsebecauseofsyntaxerrors,itcertainly
won’texecute.
3. AandC.ORDERBYisoptional;itisnotrequired.Itisabletosort
rowsinthetablebasedonanycriteriathataremeaningfultotherow,and
whensorted,anycolumnsmaybedisplayedfromthoserowsintheselect
list,regardlessoftheORDERBYcriteria.
BandDareincorrect.ItisuniquetotheSELECTstatementanddoesnot
appearasanoptionorotherwiseinanyotherSQLstatement.Orderingby
positionisavailabletoeachindividualORDERBYexpressionanddoesnot
dependonorrequirethesameformatfromotherORDERBYexpressions.
4. B.Ifthevaluesarecharacters,thenAislessthanZ,andifwe’re
listingrowsindescendingorder,thenthegreatervalueisshownfirst.That
meansthevalueslaterinthealphabetareshownfirst.Incomparingthe
characterstrings'Michael'and'Jackson',thestring'Michael'isgreaterand
willshowfirstinthelistingbefore'Jackson'.
A,C,andDareincorrect.Ifthevaluesarenumeric,then400islessthan
800.Thatmeansinadescendingorderlisting,wherethehighervalueis
listedfirst,800wouldbelistedbefore400.Withregardtodatedatatypes,
laterdatesaregreater,andAugust29,2010,shouldlistbeforeJune25,
2010.Finally,withregardtonumericvaluestreatedasstrings,youhaveto
thinkabouthowtheywouldappearinthedictionary—thefirstcharacteris
themostimportant,andinthiscase,the7in75indicatesthatcharacter
stringishigherthan130,soinadescendingpattern,the75wouldbelisted
before130.Ifthosevaluesweretreatedasnumericvalues,itmightbea
differentsituation.Butwe’reexplicitlydirectedtotreatthemascharacter
strings.
LimittheRowsThatAreRetrievedbyaQuery
5. B.TheSELECTwillreturnonerow,forVENDOR_ID1wherethe
CATEGORYequals'Supplier'.
A,C,andDareincorrect.Thesecondrowwillbeignoredbecauseeven
thoughthesetofexpressionswithintheINclauseincludesavaluefor
'%Partner'andusesthepercentsignwildcardcharacteratthebeginning,the
wildcardisn’tactivatedbecauseLIKEisn’tpresentintheexpression.
Therefore,thestringistreatedasaliteral.Hadtherebeenavaluein
CATEGORYof'%Partner',therowwouldhavebeenreturned.Thefailure
toincludeLIKEisnotasyntaxerrorperse;it’sjustincorrectdesignofthe
SELECTstatement.Onewaytochangethisqueryintosomethingthatis
morelikelytheintendedformwouldbethis:SELECTVENDOR_ID
FROMVENDORSWHERECATEGORYIN(‘Supplier’,‘Subcontractor’)
ORCATEGORYLIKE‘%Partner’;Thatapproachwouldproducetwo
rowsandperformthequerythatwasprobablyintended.
6. A.Thisquerywillalwaysretrievezerorows,nomatterwhatthey
looklike.Theuseofthe=NULLexpressionwithintheWHEREclause
guaranteesthatfact.NothingwilleverberetrievedbecausenoSQLengine
iscapableofconfirmingthatanyvalueisequalto“Idon’tknow.”
B,C,andDareincorrect.Ifline3hadusedISNULL,asinWHERE
STYLEISNULLORWINDOWISNULL,thentheanswerwouldhave
beenC,ortworows.Also,iftheISNULLwereusedandtheORhadbeen
ANDinstead,thenonerowwouldhavebeenreturned.Regardless,the
parenthesesarecorrecthere;youareallowedtoenclosecomplete
expressionswithinparentheseswithinaWHEREclause.
7. D.ThequeryreturnstherowwithavalueofSHIP_ID=1,andno
more.TheBETWEENrangeisinclusive,sothenumber2052ispartofthe
range.
A,B,andCareincorrect.TheLENGTHvalueisnumeric,andthesetof
expressionsinsideINarestrings.However,OracleSQLwillperforman
automaticdatatypeconversionsincethestringsallcontainnumericdata
withinthemanyway,andtheoperationwillsucceed.It’snotthebestdesign,
butitworks,andyou’llneedtobeawareofthisfortheexam.Also,line5
usestheLIKEoperatortoactivatewildcardcharacterswithinthestring,and
bothoftheavailablewildcardsareused—thesingle-characterunderscore
andthemulticharacterpercentsign.Thesecombinetoindicatethatanyrow
withaSHIP_NAMEthatstartswiththestring'Codd',followedbyatleast
onecharacter,followedbyanywherefromzerotoaninfinitenumberof
additionalcharacters,willbeaccepted.
8. D.Thereisnothingwrongwiththesyntax.
A,B,andCareincorrect.Thepairofnestedparenthesesbeforetheword
CAPACITYisavalidexpressionthatmultipliesthevalueofthe
LIFEBOATScolumnandaddsthenumber57totheendofit.Thenthe
entireresultissubtractedbywhateverthevalueforCAPACITYmightbe.
Theresultofthatexpressionwillthenbecomparedtowhateveris
containedintheseriesofexpressionsaftertheINclause.Therearetwo
expressionsthere:onemultipliestheLIFEBOATSvaluetimes20,andthe
secondaddsthevaluesofthecolumnsnamedLIFEBOATandLENGTH.
Alloftheseexpressionsaresyntacticallyvalid.
9. A.Thesyntaxiscorrect.However,therearesomeissuesinvolving
thelogic,suchastheexpressiononlines3and4,whichdon’treallydo
anything.Anynon-NULLvalueforLIFEBOATSwillbefoundwiththese
expressionsbecauseoftheORoperatoronline4.Itwouldmakemore
senseforthatoperatortobeAND,butregardless,itissyntacticallycorrect.
B,C,andDareincorrect.Lines3and4haveaccuratesyntax,buttheOR
atthebeginningofline4shouldprobablybeanAND.Sinceitisnot,then
BETWEENwouldnotbeanequivalentsubstituteheresinceBETWEEN
cantestonlyforarangeandessentiallyservesasareplacementoftheAND
combination,asinLIFEBOATS>=80ANDLIFEBOATS<=100.Line5
doesn’tneedanyparentheses.Theywouldn’thurtanythingnecessarily;
theyjustaren’trequired.
UseAmpersandSubstitutiontoRestrictandSortOutputatRun
Time
10. Ciscorrect.TheDEFINEcommandonalinebyitselfwilldisplayall
existingvariablesdefinedforthesession.
A,B,andDareincorrect.TheSHOWALLcommandlistsallsystem
variables.SHOWDEFINEwillshowthecurrentstateoftheDEFINE
systemvariable.DEFINEALLisnotavalidcommand.
11. Discorrect.Youcanuseasubstitutionvariabletoreplacejustaboutany
textinaSQLstatement,includingvaluesandSQLkeywords.
A,B,andCareincorrect.Whileyoucanuseasubstitutionvariableto
replaceafloating-pointnumberandalsothenameofatable,youcando
both,sothebestanswerisD.
12. Aiscorrect.Theenduserwillbepromptedtoenteranumberintwo
places.ThefirstpromptwillresultfromthePROMPTstatement.However,
PROMPTisnotassociatedwithACCEPT,soitwillneitherwaitfora
responsenorcaptureanyinput.However,theSQLscripthasavalid
ampersandsubstitutionvariablethatwillprompttheusertoenteravalue
forrnbr,atwhichpointtheenduserwillbeabletoprovideavalue,which
willcausetheSQLscripttosuccessfullyexecute.
B,C,andDareincorrect.TheDEFINEstatement’sreferenceto
vRoomNumberdoesnotrequireanampersand,butnordoesitassigna
valuetothevariablevRoomNumber.TheSELECTstatementwillnotfail
forthereasonprovided:theampersandiscorrectlyplaced.Thefirstline
statementdoesnotrequiretheSETstatementinfrontand,ifitwere
included,wouldresultinanerrorsinceSETDEFINEworkswiththe
keywordsON,OFF,orasinglecharactertobecomethenewsubstitution
variable.
13. Aiscorrect.UNDEFINEwillremoveasubstitutionvariablefrom
memoryforthesession.
B,C,andDareincorrect.SETDEFINEOFFtemporarilyturnsoffthe
abilitytoreferenceallsubstitutionvariables.Butitdoesnotpermanently
removeanyvariables;youcanSETDEFINEONandallexisting
substitutionvariablesareimmediatelyavailableforreferenceonceagain.
ThereisnoREMOVEstatement.Topermanentlydeleteasubstitution
variable,useUNDEFINEfollowedbythenameoftheparticular
substitutionvariableyouwanttodelete.
UsetheSQLRowLimitingClause
14. B,C,andDarecorrect.InthecaseofC,thelackofanORDERBY
rendersWITHTIESineffective,butthesyntaxisacceptablenonetheless.
Thereisnosyntaxerror.
Aisincorrect.ThepercentsigncannotbeusedinFETCH;usethe
keywordPERCENTinstead.
15. Aiscorrect.TheuseofOFFSETwithanegativenumberistreatedthe
sameasoftheOFFSETwerezero.TheSELECTwillFETCHthefirstrow
rowsofthesortedrowset.
B,C,andDareincorrect.Whileitistemptingtothinkthatanegative
offsetwouldstartattheendofthesortedlist,itdoesnot,andinsteadthe
negativeoffsetnumberistreatedasthoughitwereazero.Syntacticallythe
statementiscorrect,anditwillexecute.TheuseofFIRSTis
interchangeablewithNEXT;oneisrequiredandeitherisacceptable,the
choicedoesnotchangethefunctionalityofthestatement.
5
UsingSingle-RowFunctionstoCustomize
Output
T
CERTIFICATIONOBJECTIVES
5.01UseVariousTypesofFunctionsThatAreAvailableinSQL
5.02UseCharacter,Number,Date,andAnalytical(PERCENTILE_CONT,
STDDEV,LAG,LEAD)FunctionsinSELECTStatements
✓Two-MinuteDrill
Q&ASelfTest
hischapterlooksatthetopicofSQLfunctions.Functionsperformunique
tasksthatboostthecapabilitiesofSQL.TherearemanySQLfunctions,and
itisimportantthatyoubefamiliarwithallofthemandunderstandhowtouse
themindividuallyandinvariouscombinationsinsupportofvariousreal-world
scenarios.
Thischapterlooksexclusivelyatsingle-rowfunctions.Mostsingle-row
functionsareknownalsoasscalarfunctions.Scalarfunctionsreturnoneanswer
foreachonerowprocessed.Therearetwoothercategoriesoffunctions.You’ll
studythetopicofaggregatefunctionsandanalyticfunctionsinChapter7,when
youstudytheGROUPBYclauseoftheSELECTstatement.
CERTIFICATIONOBJECTIVE5.01
UseVariousTypesofFunctionsThatAreAvailablein
SQL
Functionshavethefollowingthreecharacteristics:
Theymayacceptincomingvalues,orparameters(notethatafew
functionstakenoparameters).
Theyincorporateparameterdataintosomesortofprocess;inother
words,theyperformsomesortoftaskontheincomingdata,suchasa
calculationorsomeotheractivity.
Theyreturnonesingleanswerasaresult.
Forexample,hereisaSQLstatementthatusesafunctioncalledINITCAP,
whichtakesasingleparameter:
Inthisexample,foreachrowthattheSELECTstatementprocesses,theSQL
built-infunctionINITCAPtakesthecolumnLASTNAMEandtransformsthe
textcontainedwithinsothatthefirstletterisdisplayedasacapitalletter(initial
capital,INITCAP,getit?)andtherestofthetextisinlowercaseletters.The
resultofthefunctionisdisplayedinplaceofthevaluefortheLASTNAME
column.ForeachonerowofdatareturnedbytheSELECTstatement,INITCAP
willreturnonevalue.SeeFigure5-1foranexampleofitsoutput.
FIGURE5-1 OutputofSELECTwithINITCAP
Asyoucansee,afunctionlikeINITCAPisn’tfoolproof—noticehowitdoes
anicetransformationonthefirsttworowsbutdoesn’tnecessarilyproducea
desirableresultinthethirdrow,wherethethirdletterLshouldstillbe
capitalized.ButINITCAPperformsitstask;it’suptousasdeveloperstoknow
wherebesttoapplyit.
WhenafunctionisusedinaSQLstatement,it’softensaidthatit’scalledor
invokedfromthestatement.
Functionscanbecalledfromanyplacethatanexpressioncanbecalled.In
otherwords,youcaninvokeafunctionfrom
ASELECTstatement’sselectlistandWHEREclause
AnINSERTstatement’slistofvalues
AnUPDATEstatement’sSETclauseandWHEREclause
ADELETEstatement’sWHEREclause
...andmore.
ThereareavarietyoffunctionsavailableinSQL.Thetwomajortypesare
built-inanduser-defined.
Built-infunctionsarethosethatarepartoftheSQLlanguage.They
areavailablewitheverystandardimplementationofSQL.
User-definedfunctionsarethosethatarecreatedbyusers.Theyare
writtenwithfeaturesthatgobeyondthecapabilitiesofSQL,using
languagessuchasPL/SQL.Theirconstructionisbeyondthescopeofthe
examandthereforethisbook.Thisbook—andtheexam—willdealonly
withbuilt-infunctions.
Thereareagreatmanybuilt-infunctions,andtheyfallintoseveral
categories.Themostcommoncategoriesarecharacter,number,anddata
functions.We’lldiscussconversionfunctionsinChapter6.
CharacterFunctions
Characterfunctionsareusedtomanipulatetext.Theycanbeusedtoperform
manyjobsonagivenstringsuchasanalyzeitslength(LENGTH),paditwith
extracharacters(RPAD,LPAD),trimoffunwantedcharacters(RTRIM,LTRIM,
TRIM),locateagivenstringwithinalargerstring(INSTR),extractasmaller
stringfromalargerstring(SUBSTR),andreplacetextwithinastring
(REPLACE).It’sevenpossibletosearchforstringsthataren’tnecessarily
spelledthesamebutthatsoundalike(SOUNDEX),andmore.Whentheseare
combined,thepossibilitiesaretheoreticallyendless.
NumberFunctions
Numberfunctionscanperformmathematicalanalysis.SQLcomeswithmany
functionsfordeterminingsine(SIN,ASIN,SINH),cosine(COS,ACOS,
COSH),andtangent(TAN,ATAN,ATAN2,TANH).Youcandetermineabsolute
value(ABS)ordeterminewhetheragivennumberispositiveornegative
(SIGN).
Afunctioncanroundoffvalues(ROUND)andotherwiseabbreviatenumbers
(TRUNC).
Numberfunctionscanbeincorporatedintoexpressions,andasyou’ve
alreadyseen,expressionsprovidesupportforstandardarithmeticoperationsof
addition(+),subtraction(–),multiplication(*),anddivision(/).Theseoperators
arenotfunctionsbutare,well,operators.Thepointhereisthatyoucancombine
theoperatorswithnumberfunctionstoproducepowerfulSQLstatements.
DateFunctions
ThesetofavailableSQLfunctionsincludespowerfulfeaturesforDATE
manipulation.Youcanobtainthecurrentdateandtime(SYSDATE,
SYSTIMESTAMP),“round”offdatestovaryingdegreesofdetail(ROUND),
andotherwiseabbreviatethem(TRUNC).Youcancalculatethedifferences
betweentwoormoredatesinmanyways.
Simplearithmeticoperatorswillhelpdeterminethedifferencesbetweentwo
datesintermsofdays,meaningthatifyousubtractonedatefromanother,the
resultinganswerwillbeanumberrepresentingthedifferenceintermsofdays.
Butwhatifyouwantsomethingelse,like—thedifferenceintermsofmonths?
(TheanswerisMONTHS_BETWEEN.)Therearefunctionsthatwillassistin
managingsuchtasks.Youcanaddorsubtractanentiremonthandaccountfor
spansoftimethatencompassyears(ADD_MONTHSwithapositivenumberto
addoranegativenumbertosubtract—we’llseethislater).
Whatifyouhaveaparticulardateandwanttoknowwhetherthatdatefalls
on,say,aSaturday?Thissortoffeaturecanbeaccomplishedwith“conversion”
functions,whichwediscussinthenextchapter.
OtherFunctions
Therearesomefunctionsthatdon’tquitefitintothecategorieslistedhere.
USERisagreatexample—it’sastandardfunctionthattakesnoparametersand
simplyreturnsthevalueshowingthenameofthecurrentuseraccount.Other
functionssupportadvancedfeatures,suchashierarchicalqueries.We’lllookat
thosefunctionsaswediscussvariousadvancedfeaturesthroughoutthebook.
CERTIFICATIONOBJECTIVE5.02
UseCharacter,Number,Date,andAnalytical
(PERCENTILE_CONT,STDDEV,LAG,LEAD)
FunctionsinSELECTStatements
ThissectionlooksindetailatmanyoftheSQLfunctions.You’lllearnhowthey
work,andyou’llseeexamplesofhowmanyofthemcanbeused.Foreach
functiondiscussedhere,weaddress
Thefunction’slistofparameters
Whethereachparameterisrequiredoroptional
Whattaskthefunctionperforms
Theoutputfromthefunction
Ratherthanpresentanalphabeticallistingofthem,I’lllisttheSQLfunctions
presentedinthissectionlogically,andI’lldescriberelatedfunctionstogether.
ThisisnotanexhaustiveanalysisofallthefunctionsavailableinSQLbutis
neverthelessrathercomprehensive,focusingprimarilyonthefunctionsthatare
mostcommonlyused.Remember,functionsareanexamobjective.It’s
importanttobefamiliarwithhowthemajorfunctionswork.Thissection
describesthemostcommonlyusedfunctionsthatarelikelytobeontheexam.
TheDUALTable
Beforewegetstarted,IneedtomentiontheDUALtable,whichissomething
thatisn’tafunctionissuepersebutishelpfultoourpurposeshere.Itisnota
“SQL”thing,norisitnecessarilya“function”thing,butit’san“Oracle”thing
youshouldknowbeforewecontinue.TheDUALtableispresentineveryOracle
database.Thisspecialtablecontainsjustonecolumn.Thecolumnisnamed
DUMMY,andithasadatatypeofVARCHAR2(1).TheDUALtablecontains
onlyonerow.ThatrowhasavalueinDUMMYof'X'.
ThepurposeofDUALissimple—tohavesomethingtorunaSELECT
statementagainstwhenyoudon’twanttoretrieveanydatainparticularbut
insteadsimplywanttorunaSELECTstatementtogetsomeothertask
accomplished,suchasobtainingtheoutputofafunction.Forexample,you’ll
soonseeinthissectionthatthere’sanOracleSQLfunctioncalledSYSDATE
thatdisplaysthecurrentdateaccordingtotheoperatingsystemoftheserveron
whichtheOracledatabaseisinstalled.IfyouwanttogetthevalueofSYSDATE
withoutwadingthroughabunchoftabledatafromyourapplication,youcan
simplyexecutethefollowingSQLstatement:
SELECTSYSDATEFROMDUAL;
Theresult:you’llgetoneresponseforthecurrentvalueofSYSDATE,since
youknowtheDUALtablehasonlyonerow.
We’llusetheDUALtablefromtimetotimethroughouttherestofthis
chapteraswegothroughexamplesofthevariousSQLfunctions.
CharacterFunctions
Thissectionlooksindetailatthemorecommonlyusedcharacterfunctions.
Characterfunctionsdonotnecessarilydealexclusivelywithcharacterdata—
someofthesefunctionshavenumericparametersandevennumericoutput,like
INSTR.Buttheoverallspiritandintentofthesefunctionsistoperformthesort
ofdataprocessingtypicallyassociatedwithtextmanipulation.
UPPERandLOWER
Syntax:UPPER(s1)
LOWER(s1)
Parameters:s1,arequiredcharacterstring.
Process:Transformss1intouppercaseletters(UPPER)orlowercaseletters
(LOWER).
Output:Characterstring.
Example:UPPERandLOWERcanbeusefulwhenyouaredoingatextsearch
andaren’tsurewhetherthedatainthetableisinuppercase,lowercase,orboth.
YoucanuseUPPERtoforceaconversionofalldatainthetableandthen
comparethatresulttoanuppercaseliteralvalue,thuseliminatinganychanceof
missingmixed-casetextinthetable.
ThepreviousquerywillreturnrowsfromtheEMPLOYEEStablewherethe
LAST_NAMEis'McGillicutty','mcgillicutty',oranyothercombinationof
upper-andlowercaselettersthatequalsthelettersinthestring.
BewarequestionsthataskyouaboutusingUPPERorLOWERwhen
bothsidesofthecomparisonoperatorarevariables.IfyourSELECT
statementendswithsomethinglikeWHERELAST_NAME=
FAMILY_NAMEandyou’reconcernedaboutcasemismatch,thenuse
UPPERorLOWER,butonbothsidesoftheequalsigns:WHERE
LOWER(LAST_NAME)=LOWER(FAMILY_NAME).Usingthe
functionononlyonesidemightactuallyincreaseyourprobabilityofa
casemismatch.Besuretousethefunctiontostandardizethecaseof
bothvaluesbeingcompared.
INITCAP
Syntax:INITCAP(s1)
Parameters:s1,arequiredcharacterstring.
Process:Transformss1intoamixed-casestring,wherethefirstletterofeach
wordiscapitalizedandeachfollowingcharacterisinlowercaseletters.
Output:Characterstring.
Thesinglequoteescapecharacteractivates,orenables,asinglequote
charactertobedisplayedasasinglequote.Withoutit,astringlike
‘O’Hearn’isinterpretedas‘O’followedbytheletters‘Hearn’that
appearoutofcontext.Thisdoesnotwork:SELECT‘O’Hearn’FROM
DUAL.Butthisdoes:SELECT‘O”Hearn’FROMDUAL.
Example:ThefollowingisaSQLstatementthatinvokesINITCAPthreetimes.
Thefirstexamplepassesinthestring'napoleon',whichistranslatedintomixed-
caseletters.Thesecondexampletakesthestring'RedO''Brien'asinput.Notice
thatweneedtoincludethesinglequoteescapecharacterwithinthestringin
orderforasinglequotecharactertoberecognized—sincethesinglequotemark
isalsothestringdelimiter,weneedtotypetwosinglequotesinsuccession,
whichishowyouinstructSQLtotreatasinglequoteasanactualcharacter
withinthestring,andnotthestringdelimiter.Withoutthis,ourstringwould
appeartobe'RedO'followedbytextthatwouldbeseenbySQLasgibberish
andwouldresultinanerrormessage.Finally,thethirdexampledoesthesame
thingwiththestring'McDonald''s',buttheresultsofINITCAParelessthan
desirable.ThefirstdinMcDonald’sisconvertedtolowercase,andthesatthe
endofMcDonald’sisconvertedtouppercasebecauseINITCAPinterpretsthes
asthestartofanewword.
CONCATand||
Syntax:CONCAT(s1,s2)
s1||s2
Parameters:s1,s2.Botharecharacterstrings;botharerequired.
Process:Concatenatess1ands2intoonestring.
Output:Characterstring.
Example:
Here’stheequivalentusingthedoubleverticalbars:
WhileCONCATtakesonlytwoparameters,thedoubleverticalbarsyntax
canberepeatedasoftenasisnecessary.Forexample,thisapproachcreatesone
string:
Notethattheresulthereisasinglestring.Here’sanotherexample:
LPAD,RPAD
Syntax:LPAD(s1,n,s2)
RPAD(s1,n,s2).
Parameters:s1(characterstring—required);n(number—required);s2(character
string—optional;s2defaultstoasingleblankspaceifomitted).
Process:Padtheleftofcharacterstrings1(LPAD)orrightofcharacterstrings1
(RPAD)withcharacterstrings2sothats1isncharacterslong.
Output:Characterstring.
Example:Takeastringliteral'ChapterOne—IAmBorn'andpadittotheright
sothattheresultingstringis40charactersinlength.
ManySQLfunctionsareusefulinandofthemselves,butmanybecomemore
usefulwhencombinedwitheachother.Forexample,here’sacombinationof
RPADandLPADwiththeconcatenationoperators,executedagainstatable
calledBOOK_CONTENTS:
Noticethisexamplealsoincludesthreeusesoftheconcatenationoperator:
OncetoappendasingleblankaftertheCHAPTER_TITLEvalue
OncetoputasingleblankinfrontofthePAGE_NUMBERvalue
OncetocombinetheoutputofRPADandLPAD
Alsonotetheuseofthecolumnalias"TableofContents",andnotethe
ORDERBYtoensurethattherowssortaccordingtoPAGE_NUMBER.
Asyouwillseeinthisbook,whichisfocusedonexampreparation,SQL
featuresanumberofpowerfulformattingcapabilities.Itisworthnoting,
however,thatreportingtoolsoftenareusedtoperformreportformattingina
professionalsettingandcanoffermorefeaturesandeaseofuse.Thesetools
maybelimitedtoparticularoperatingsystemplatforms,whereasSQL’s
formattingcapabilitiesexistwhereverSQLisavailable.
Ifthe“OntheJob”codesampleshowingLPADandRPADcombined
withstringconcatenationisamysterytoyou,thenstopandstudyit.The
exammayincludequestionsaboutseveralfunctionscombinedand
nestedwithineachother,liketheBOOK_CONTENTSsampleshownin
thesample.Wewilladdressnestedfunctionslaterinthischapter.
LTRIMandRTRIM
Syntax:LTRIM(s1,s2)
RTRIM(s1,s2)
Parameters:s1,s2—botharecharacterstrings.s1isrequired,ands2isoptional
—ifomitted,itdefaultstoasingleblankspace.
Process:Removesoccurrencesofthes2charactersfromthes1string,from
eithertheleftsideofs1(LTRIM)ortherightsideofs1(RTRIM)exclusively.
Output:Characterstring.
Notes:Idealforstrippingoutunnecessaryblanks,periods,ellipses,andsoon.
Example:Removedashesfromastring.Notethatwechoosetoincludea
columnalias'Result'torenametheoutputcolumnforthisquery.
TRIM
Syntax:TRIM(trim_infotrim_charFROMtrim_source)
Parameters:
trim_infoisoneofthesekeywords:LEADING,TRAILING,BOTH—ifomitted,
defaultstoBOTH.
trim_charisasinglecharactertobetrimmed—ifomitted,assumedtobea
blank.
trim_sourceisthesourcestring—ifomitted,theTRIMfunctionwillreturna
NULL.
Process:SameasLTRIMandRTRIM,withaslightlydifferentsyntax.
Output:Characterstring.
Example:Trimoffthedashesattheendofthestring'Seventhousand--------'.
Notewechoosetouseacolumnalias'TheOutput'torenametheoutputcolumn.
LENGTH
Syntax:LENGTH(s)
Parameters:sisthesourcestring(required).
Process:Identifiesthelengthofagivenstring.
Output:Numeric.
Example:Determinethelengthofareallylongandfamousword.
INSTR
Syntax:INSTR(s1,s2,pos,n)
Parameters:s1isthesourcestring(required);s2isthesubstring(required);pos
isthestartingpositionins1tostartlookingforoccurrencesofs2(optional,
defaultis1);nistheoccurrenceofs2tolocate(optional,defaultis1).Ifposis
negative,thesearchins1foroccurrencesofs2startsattheendofthestringand
movesbackward.
Process:Locatesastringwithinanotherstring(thusthenameofthefunction:IN
STRing).
Output:Numeric.
Example:Lookforthestring'is'within'Mississippi',startingatthefirst
characterpositionbutlookingforthesecondoccurrenceof'is'.
TheINSTRfunctionistellingusthatthesecondoccurrenceofisstartsatthe
fifthcharacterinMississippi.
SUBSTR
Syntax:SUBSTR(s,pos,len)
Parameters:s=acharacterstring,required;pos=anumber,required;len=a
number,optional.
Process:Extractsasubstringfroms,startingattheposcharacterofsand
continuingforlennumberofcharacters.Iflenisomitted,thenthesubstring
startsasposandrunsthroughtheendofs.Ifposisnegative,thenthefunction
startsattheendofthestringandmovesbackward.
Output:Characterstring.
Example:Startingwithasourcestringof'Name:MARKKENNEDY',extracta
substringoutofit,beginningattheseventhpositionandrunningtotheendof
thestring.
SOUNDEX
Syntax:SOUNDEX(s)
Parameters:s=thesourcestring,required.
Process:TranslatesasourcestringintoitsSOUNDEXcode.
Output:Characterstring.
Notes:SOUNDEXisacodingschemefortranslatingEnglishwordsintosound-
alikepatterns.AsingleSOUNDEXvalueisrelativelyworthless.Buttwo
combinedcanbesurprisinglyhelpful.Thereasonisthatsimilar-soundingwords
tendtogeneratethesameSOUNDEXpattern.
Example:TogenerateaSOUNDEXtranslationforanyword,thefirstletter
remainsunchanged.Thenextseriesoflettersaretranslatedintoanumericcode
accordingtotherulesshowninTable5-1.Translationisperformedforeach
letteruntilthreedigitsaregenerated.Ifanylettersexistbeyondthat,theyare
ignored.Forexample,thelastnameWorthingtonhasaSOUNDEXpatternof
W635:thefirstletter,W,remainsunchanged;thesecondletter,o,isignoredper
thebottomrowoftheTable5-1;thethirdletter,r,translatesinto6accordingto
Table5-1;thefourthletter,t,translatesintoa3;andthefifthletter,h,isignored.
Again,accordingtoTable5-1(whichalsotellsustoignoretheletteri),theletter
ntranslatesinto5,andnowthatwehaveoneletterWandthreenumbers635,we
aredone;theremaininglettersinWorthingtonareignored.Thus,theSOUNDEX
codeisW635.
TABLE5-1 SOUNDEXTranslationTable
So,twowordsthatsoundalike,forexample,WorthingtonandWurthinden,
whilespelleddifferently,willneverthelessgeneratethesameSOUNDEX
pattern.Here’sanexample:
NoticehowthetwodifferentwordsproducethesameSOUNDEXpattern.
Thatmeanswecandoquerieslikethis:
NoticethatSOUNDEXisusedtwiceintheWHEREclause.Usingitonce
wouldprobablybeuseless.Thisquerywillfindcustomerswiththelastnamesof
Worthington,Wurthinden,Worthan,andevenWirthen.
TheconceptandlogicofSOUNDEXwereoriginallydevelopedintheearly
twentiethcenturyforusewiththeEnglishlanguage,withahistoryof
implementationintheU.S.CensusandU.S.NationalArchives.Duringthelate
twentiethcenturyasautomatedsystemsweredeveloped,SOUNDEXbecamea
popularfeaturetoincludeincomputersoftwaresystems,andthuswefinditin
SQL.ItsrulesareformallyadministeredtodaybytheNationalArchivesand
RecordsAdministrationoftheUnitedStatesgovernment.Buttakenote:Itwas
andisdesignedforusewiththeAmericanEnglishlanguage.Itwon’tworkquite
aswellwithwordsoriginatingfromotherlanguages,whosepronunciationrules
andpracticestendtobedifferent.Forexample,thepopularVietnamesename
Nguyenispronounced“Nwen,”buttheSOUNDEXpatternsforthosetwowords
—NguyenandNwen—areratherdifferent.So,SOUNDEXisnotperfectbut
ratherusefulnonetheless.
NumericalFunctions
Thissectiondescribesfunctionsthatdealwithnumericvalues.Somenumeric
functionsareprettysimplesuchasABS,whichtakesasinglenumericvalueand
returnsitsabsolutevalue.There’salsoSQRT,whichtakesasinglenumeric
valueandreturnsitssquareroot.
Notalloftheinputparameterstonumericfunctionsarenecessarilynumeric,
buttheoverallintentofthesefunctionsistoperformnumericanalysisand
performthesortoftaskstypicallyassociatedwithnumericmanipulationand
dataprocessing.
CEIL
Syntax:CEIL(n)
Parameters:nisrequiredandisanynumericdatatype.
Process:CEILreturnsthesmallestintegerthatisgreaterthanorequalton.
FLOOR
Syntax:FLOOR(n)
Parameters:nisrequiredandisanynumericdatatype.
Process:FLOORreturnsthelargestintegerthatislessthanorequalton.
ROUND—Number
Syntax:ROUND(n,i)
Parameters:nisrequired,isanynumber,andcanincludedecimalpoints.iisan
integerandisoptional—ifomitted,itwilldefaultto0.
Process:nisroundeddependingonthevalueofi.Ifiiszero,nisroundedoffto
thenearestwholenumber,inotherwords,zerodecimalpoints.Ifiisapositive
number,nisroundedtoiplacestotherightofthedecimalpoint.Ifiisa
negativenumber,nisroundedtoiplacestotheleftofthedecimalpoint.The
number5isroundedawayfromzero.
Output:Ifiisomitted,ROUNDreturnsavalueinthesamenumericdatatypeas
n.Ifiisspecified,ROUNDreturnsadatatypeofNUMBER.
Example:Roundoff12.355143totwosignificantdigitstotherightofthe
decimal,andalsoroundoff259.99tothenearest“tens,”inotherwords,one
digittotheleftofthedecimal.
TRUNC—Number
Syntax:TRUNC(n,i)
Parameters:nisrequired,isanynumber,andcanincludedecimalpoints.iisan
integerandisoptional—ifomitted,itwilldefaultto0.
Process:TRUNC“rounds”towardzero;inotherwords,ittruncatesthenumbers.
Output:Ifiisomitted,TRUNCreturnsavalueinthesamenumericdatatypeas
n.Ifiisspecified,TRUNCreturnsadatatypeofNUMBER.
Example:UsingthesamenumberswejustusedwiththeROUNDexample,
truncatetheminstead.
REMAINDER
Syntax:REMAINDER(n1,n2)
Parameters:n1andn2arenumbers.Botharerequired.
Process:Identifiesthemultipleofn2thatisnearestton1andreturnsthe
differencebetweenthosetwovalues.
Output:Numeric.
Example:TestREMAINDERusingthreesequentialnumberssuchas9,10,and
11,andcompareeachagainstthenumber3.Sincethefirstnumber(9)isa
multipleof3,thereisnoremainder,sotheanswerwillbe0.Thesecondnumber
(10)representsonemorenumberthanthemultiple,sotheremainderis1.Notice
whathappenswiththethirdnumber(11)—thefunctiondoesn’treturna2asyou
mightexpect.Instead,itreturnsanegative1,becausethenearestintegerthat’s
divisibleby3is12,whichisclosertothe11thanthe9.Inotherwords,
REMAINDERidentifiestheclosestmultipleofn2.Ifthemultipleishigher,
REMAINDERreturnsanegativenumbertoindicatethattheclosestmultipleof
n2ishigherthann1.
MOD
Syntax:MOD(n1,n2)
Parameters:n1andn2arenumbers.Botharerequired.
Process:PerformsthesametaskasREMAINDER,exceptMODusesFLOOR
insteadofROUNDinitsequation.
Output:Numeric.
Example:GettheMODofthesamethreenumberpairswetestedwith
REMAINDER.Notetheresultsinthethirdexample—thismightbewhatyou
would’veexpectedwithREMAINDERanddidn’tget—butyoudogetitwith
MOD.
DateFunctions
ThefollowingsectionlooksatfunctionsthatworkprimarilywithDATEdata
types.
SYSDATE
Parameters:None
Process:Returnsthecurrentdateandtimeaccordingtotheoperatingsystemon
whichtheOracledatabaseserverisinstalled.Inotherwords,ifyourSQL
statementisrunningonanOracleserverinstancefromaremotelocation,then
regardlessofthelocationofyouoryourclient,SYSDATEwillreturnthedate
andtimeoftheoperatingsystemonwhichtheserverresides.Timeinformation
iscontainedwithinSYSDATEbutdoesn’tdisplaybydefault;however,itcanbe
extractedbywayoftheTO_CHARconversionfunction,whichwewillformally
discussinChapter6,butwhichweincludeinsomeoftheexamplesthroughout
thischapter.(Note:Itcanalsobealteredbychangingthe
NLS_DATE_FORMATsessionparameter.)
Output:Date.
Example:Showthecurrentdateaccordingtotheoperatingsystemwherethe
Oracleserverisinstalled.
ROUND—Date
Syntax:ROUND(d,i)
Parameters:disadate(required);iisaformatmodel(optional).
Process:disroundedofftothenearestdatevalue,atalevelofdetailspecified
byi.disrequiredandspecifiesavalueoftheDATEdatatype.iisaformat
modelandspecifiesthelevelofdetailtowhichtheDATEvaluewillberounded
—inotherwords,tothenearestday,nearesthour,nearestyear,andsoon.iis
optional;ifiisomitted,ROUNDwilldefaulttoaformatmodelthatreturnsa
valueofdroundedtothenearestwholeday.Valuesarebiasedtowardrounding
up.Forexample,whenroundingofftime,12noonroundsuptothenextday.
FormatmodelsarecoveredinChapter6whenwediscusstheTO_CHAR
conversionfunction.Butwe’llincludeoneintheexamplethatfollowstogive
youanideaofwhataformatmodelis.
Output:Date.
Example:ThisexampleshowsaSELECTstatementwiththreeexpressionsin
theselectlist.ThefirstisSYSDATE,whichreturnsthecurrentdate.Thesecond
isthesamedate,roundedtothenearestmonth,asspecifiedbythe'MM'format
model.Thethirdisthesamedateroundedtothenearestyear,asspecifiedbythe
'RR'formatmodel.
Iftheoptionalsecondparameterisomitted,theDATEvaluewillberounded
tothenearesthour.
Wehaven’tyetcoveredtheconversionfunctionTO_CHAR,butwearegoing
touseittodemonstratehowROUNDbehaveswhentheoptionalformatmodel
isomitted.Withoutaformatmodel,ROUNDwillroundadatetothenearest
wholedate.Thisroundingisperformedbutisnotnecessarilyobvioussince,by
default,valuesoftheDATEdatatypedon’tdisplaythehour.Thevalueforhour
isstoredwithinaDATEdatatypenonetheless,asarealsothevaluesforminute
andsecond,butyoumustuseaconversionfunctiontodisplaythosevalues.
That’swhereTO_CHARcomesinhandy.
Toseehowthisworks,we’llusetheROUNDfunction,theupcoming
TO_CHARfunction(explainedlaterinthischapter),andatechniqueknownas
nestedfunctions.(Wewillcovernestedfunctionsinmoredetaillaterinthis
chapter.)
Inthefollowingexample,theSELECTstatement’sfirstcolumntakesthe
valueofSYSDATEandusestheTO_CHARconversionfunctiontodisplaythe
valueofSYSDATEwithaformatmodeltodisplaythedateandthetime.
Thesecondcolumndoesthesamethingwithonechange:itusesROUNDto
roundoffthevalueofSYSDATE.NotetheimpactofROUND.
UsingtheTO_CHARconversionfunction(explainedinChapter6),wereveal
thatthecurrentsystemdateandtimeisDecember3,2016,5:35:17a.m.,which
is5:35inthemorning.ButwhenSYSDATEisrounded,wegetDecember3,
2016,12:00:00.
ThisroundingisperformedbyROUNDregardlessofwhetherTO_CHARis
used.ThepointisthatROUNDworkswhethertheresultsarevisibleornot.
ROUNDisbiasedtoroundup.Inthecaseofadatewitha12noontime,
ROUNDwillroundthedateuptothenextcalendarday.
ThefirstcolumnisAugust1and12noon.Thesecondcolumnstartswiththe
samevaluebutusesROUND.Sincethetimeofdayis12noon,theresultrounds
uptothenextwholeday:August2.
Notethatwe’llexploremoreabouthowDATEvaluesandformatmodels
workwhenwediscusstheTO_CHARandTO_DATEconversionfunctions.
TRUNC—Date
Syntax:TRUNC(d,i)
Parameters:disadate(required);iisaformatmodel(optional).
Process:PerformsthesametaskasROUNDfordates,exceptTRUNCalways
roundsdown.
Output:Date.
Example:
NEXT_DAY
Syntax:NEXT_DAY(d,c)
Parameters:disadate,required;cisatextreferencetoadayoftheweek,
required.
Process:Returnsavaliddaterepresentingthefirstoccurrenceofthecday
followingthedaterepresentedind.
Output:Date.
Example:ShowthefirstoccurrenceofaSaturdayfollowingMay31,2019.
LAST_DAY
Syntax:LAST_DAY(d)
Parameters:disadate,required.
Process:Returnsthelastdayofthemonthinwhichdfalls.
Output:Date.
Example:ShowthelastdaysofFebruaryin2020and2021.
ADD_MONTHS
Syntax:ADD_MONTHS(d,n)
Parameters:disadate,required;nisawholenumber,required.
Process:Addsnmonthstodandreturnsavaliddatevaluefortheresult.
Output:Date.
Example:AddonemonthtoJanuary31,2017,andfourmonthstoNovember1,
2017.
ThereisnoSUBTRACT_MONTHSfunction.Instead,useADD_MONTHSto
addanegativenumberofmonths,andyou’llsubtracttheminstead.
MONTHS_BETWEEN
Syntax:MONTHS_BETWEEN(d1,d2)
Parameters:d1andd2aredates,required.
Process:Determinesthenumberofmonthsbetweenthetwodates.Theresult
doesnotroundoffautomatically;iftheresultisapartialmonth,
MONTHS_BETWEENshowsarealnumberresult.Wholemonthsarecounted
accordingtothecalendarmonthsinvolved;ifthetimespans,say,aFebruarythat
has29days,thentheonemonthtimespanforthattimeperiodwillbe29days.
Inotherwords:
Notethattheanswermaybeoppositeofwhatyoumightexpect.Youmight
thinkyoucouldlistthedatesinchronologicalorderandthat
MONTHS_BETWEENwoulddeterminethedifferenceinmonths.Itwill,butas
anegativenumber.Togetapositivenumber,thefirstparameterisexpectedtobe
thegreatervalue;thesecondisexpectedtobethelesser.Eitherapproachworks,
butbesuretoconsiderthesignoftheresult;ifthesecondparameteristhe
greatervalue,theresultisanegativenumber.
Output:Number.
Example:DisplaythenumberofmonthsbetweenJune12,2014,andOctober3,
2013.
NUMTOYMINTERVAL
Syntax:NUMTOYMINTERVAL(n,interval_unit)
Parameters:n=number(required).interval_unit=oneofthefollowingvalues:
'YEAR'or'MONTH'.
Process:Convertsdateinformationinnumericformintoanintervalvalueof
time.
Output:AvalueintheINTERVALYEARTOMONTHdatatype.
Example:Thefollowingexampletakesthenumber27andtransformsitintoa
valuerepresentingatimeintervalof27months,whichequatesto2yearsand3
months,intheINTERVALYEARTOMONTHdatatype.The2-3valueshows
2yearsand3monthsistheamountoftimethatresults.
NUMTODSINTERVAL
Syntax:NUMTODSINTERVAL(n,interval_unit)
Parameters:n=number(required).interval_unit=oneofthefollowing:'DAY',
'HOUR','MINUTE',or'SECOND'.
Process:Convertsdateinformationinnumericformintoanintervalvalueof
time.
Output:AvalueofthedatatypeINTERVALDAYTOSECOND.
Example:Thefollowingexampletranslates36hoursintoitsformal
representationof1dayand12hoursinthedatatypeINTERVALDAYTO
SECOND,whichdisplaysasinglenumberforday,followedbyhours,minutes,
seconds,andfractionalseconds.
DatesandNUMBERConstants
ToperformarithmeticwithDATEvalues,usenumericliterals.Thenumberone
(1)representsoneday.Useliteralexpressionstorepresenthoursorminutes.For
example,sincethereare24hoursinaday,thenonehourcanberepresentedby
1/24.Thereare1,440minutesinaday(60minutestimes24hours),so1minute
canberepresentedby1/1440;12minutescanberepresentedby12/1440,andso
on.
Here’sanexample:
TheTIMESTAMPdatatypeworksthesamewaywiththesameresults;you
couldreplaceSYSDATEinthepreviousexamplewithSYSTIMESTAMPand
seethesameimpacttothevalues.
AnalyticalFunctions
Therearethreecategoriesoffunctionstestedbytheexam:scalar,analytical,and
aggregatefunctions.Scalarfunctionsreturnoneanswerforeveryonerow
processed.Aggregatefunctionsreturnoneanswerforasetofzerotomultiple
rows.
Analyticalfunctionsfallsomewhereinbetweenthese.Theyhavetheability
toreturnmultiplerowsfromwithinagroupofrows.BecauseagivenSELECT
statementprocessesdatarowbyrow,ananalyticfunctioncanoperateacrossa
windowofrows.Thatwindowcanbedefinedbynumbersofrowsorbylogic,
suchasatimerange.AsprocessingmovesfromrowtorowwithintheSELECT
statement’sgroupofrows,thewindowmayslide,dependingonhowtheanalytic
functionspecifiesthewindow.
Analyticfunctionsarethelastsetofoperationsperformedinaquerypriorto
theORDERBYclause,whichisthefinalprocessingstep.Forthisreason,you
cannotincludeanalyticfunctionsanywhereotherthantheSELECTlistorthe
ORDERBYclause.Inotherwords,analyticsareforbiddenintheWHERE,
HAVING,andGROUPBYclauses.
Let’slookatsomekeywordscommonlyusedwithanalyticfunctions.
OVER,PARTITIONBY,andORDERBY
ToseehowOVER,PARTITIONBY,andORDERBYareusedwithanalytics,
let’slookatanexample.First,considerthefollowingsampledataset:
WecanusetheSUMfunctionasanaggregatefunctiontoobtainthesumtotal
ofallSQ_FTvaluesfortheentiredataset,likethis:
Alternatively,wecanuseSUMasananalyticfunctionandcombineitwith
OVERtodisplayarunningtotalforeachrow,likethis(linenumbersadded):
ThecolumnRunningTotaldisplaysexactlywhatisindicated(arunningtotal
ofSQ_FTvalues)thatbuildswithinitsownwindow,whichinthiscasematches
thesetofrowsfortheSELECT.TheSubsetcolumnalsoperformstheSUM
operation,butoveraslidingwindowdefinedasthecurrentrow,theoneprior
row,andtheonefollowingrow.Forexample,theSubsetvalueforline13(Room
Number104)isthecombinationoftheSQ_FTvaluesdisplayedinlines13,14,
and15.Why?BecauseoftheseconduseoftheanalyticfunctionSUMdetailed
onlines3,4,and5.
Let’saddthePARTITIONBYoptiontoperformourSUMoversetsofrows
byvaluesfortheWINDOWcolumn.
TheinclusionofPARTITIONBYchangedthewayRunningTotalandSubset
arecalculated.Forexample,lookatthevaluesonline16.TheRunningTotal
columnrestartswithavalueof533,sincewe’vepartitionedthedataby
WINDOWandthevalueforWINDOWisnowNone(thefirstexampleofthis
valueandthereforethefirstrowinanewpartition).Therefore,therunningtotal
isthecurrentvalueforSQ_FTandnothingmore:533.
Lookatline18.TheRunningTotalvalueis2422,whichissumofthelast
rowforOcean(line15,wherethevaluewas898)andthecurrentvalueinline
18(whichis1524).Together,898plus1524is2422,thecurrentvalueforthe
runningtotalforSQ_FTforthepartitiondefinedbythoserowshavingavalueof
Ocean.
Let’schangetheORDERBYfortheSELECTbutleavetheanalytic
functionsunchanged.
NotethattheSELECTstatementre-sortstherows,butthevaluesforeach
rowremainunchanged.Forexample,online13,RoomNumber102stillshows
aSubsetvalueof2262,justasitdidinthepreviousqueryresults.Asyou’ve
alreadyseen,thevaluefortheSubsetcolumnisdeterminedbythepartitionand
orderofrowsaroundit,butthatorderwasn’tchanged;theanalyticsfunctionon
lines4through7remainsunchanged.Allthatwechangedwasthesortorderof
theSELECTstatement.
LAG,LEAD
TheLAGandLEADfunctionsaresimilartoeachother.Foragivenrowwithin
awindow,LAGshowsacolumn’svalueinthepriorrow,andLEADshowsthe
nextvalue.Forexample,considerthefollowingdataintheSHIP_CABINS
table:
Let’suseLAGandLEADinaSELECTstatementtoreturneachrow
showingthatrow’svalueforSQ_FT,thepriorrow’sSQ_FT(Lag),andthe
subsequentrow’sSQ_FT(Lead):
Inthisexample,theLAG(line2)andLEAD(line3)functionsareboth
specifiedtooperateoverawindowthatissortedbyWINDOWandSQ_FT.The
SELECTstatementusesthesameORDERBYlogic(line5).Noteline9,where
thefirstrowofoutputshowsaNULLfortheLagvalue.Thisisbecausethe
logicinline2specifieslogicresultinginthisrow(line9)asthefirstrowinthe
window(specifiedinline2).Therefore,thereisnopriorrow.
SeeFigure5-2foranillustrationoftheseconcepts.First,PARTITIONBY
separatestherowsintosets,orgroups,asspecified.Inourexample,wespecified
PARTIONBYWINDOW,andoursampledatahastwovaluesforWINDOW,so
weseparateourrowsintotwogroups—oneforaWINDOWvalueof'Ocean'
andanotherforaWINDOWvalueof'None'.Second,foreachgroup,wedefine
awindowforeachtargetrow.Inourexample,thewindowconsistsofthoserows
spanningfromonerowpriortoourtargetrowthroughtoonerowfollowingour
targetrow.Thismeansthataswestepthrougheachrow,ourwindowwillslide.
FIGURE5-2 UsingLAGandLEADanalyticalfunctionswithPARTITION
BYandOVER
Third,aswestepthrougheachrow,wewanttheSQ_FT;theLAG(SQ_FT),
whichisfromthepriorrow;andtheLEAD(SQ_FT),whichisfromthe
followingrow.Finally,wereturntheoutputandseeourresults.
Let’schangetheORDERBYlogicandseewhetherthischangestheLag
value.
TheORDERBYlogicnowsortstheoutputbyROOM_NUMBER.Butnote
theoutputinrow11:it’sthesameROW_NUMBERvalueof104,andit’sthe
sameNULLvalueforLag.ThisdemonstrateshowthewindowforLAGis
definedbyLAGitself,independentoftheORDERBYclause.
Sofarwe’velookedatLAGandLEADfunctionsthatspecificallyreturndata
fromtheonerowimmediatelypriorto(LAG)orfollowing(LEAD)thecurrent
row.Therowdifferenceisspecifiedbytheoffset,whichdefaultsto1aswe’ve
seensofarbutcanbespecifiedassomethingelse.Iftheoffsetspecifiesa
nonexistingrow,theLAGorLEADfunctionwillreturnaNULLvalue.Let’s
changetheoffsetforourLAGfunctionto2andseewhathappens.
Inthissamplelisting,seeline2fortheLAGfunctionandtheoffset
specificationof2,immediatelyaftertheSQ_FTreference.Theresultappearsin
therowsreturned.Notethatbothlines9and10showNULLvaluesforLAG.
Thisisbecausetherearenotrowsattheoffsetforthoserows.Forotherrows—
suchasline13—youseetheSQ_FTof533,andtheLagSQ_FTvalueistaken
fromtherowoffsetbytwoprior,whichinthiscaseistherowshownonline11.
STDDEV
TheSTDDEVfunctionreturnsthesamplestandarddeviationofasetofnumeric
values.Standarddeviationisamathematicalvaluerepresentingthedegreeof
distributionforagivennumericvaluewithinalargerrangeofvalues.The
standarddeviationforagivennumberisthesquarerootofitsvariance.Oracle
hasfunctionsforboth,sothevalueofagivennumber’sSTDDEVisthesquare
rootofitsVARIANCE,anaggregatefunction.UsingSTDDEV,youcananalyze
asetofnumbersanddetermineeachvalue’sdispersionfromthemean.
STDDEVisusefulwhenanalyzingasetofnumbersbylookingforcorrelations
amongthosenumbers—thosenumberswhoseSTDDEVvaluesareloware
closertothemeanthanthosenumberswithrelativelyhighervaluesofSTDDEV.
Themathematicalformulasforcalculatingstandarddeviationandvariance
aresimplebutabitinvolved.Forexample,considerthefollowingsetofvalues:
Thevaluesare1,2,4,and13,foratotaloffourvalues.
Tocalculatethevarianceandstandarddeviationofourexample,dothe
following:
Calculatetheaverage:
First,sumthevalues:1+2+4+13=20
Next,dividethesumbythetotalnumberofvalues:20/4=5.
Thisistheaverage.
Foreachnumber,determinethedifferencebetweenthenumberand
theaverage,thensquaretheresult.
Addupthesquareddifferences.Taketheresultanddividebythe
totalcountofvalueslessone:
16+9+1+64=90
90/(4–1)=90/3=30.Thisisthevariance.
Calculatethesquarerootofthevariance:
SQRT(30)=5.477.Thisisthestandarddeviation.
TheVARIANCEandSTDDEVfunctionswillperformthesecalculationsfor
you.Inthatcontext,thefunctionwillbehaveasanaggregatefunction.For
example,considerthefollowingdataset:
Nowlet’suseAVG,MEDIAN,VARIANCE,andSTDDEVasaggregate
functionsonthefullsetofrows.
ThatisanexampleofusingSTDDEVasanaggregatefunction.Inother
words,thefullsetofrowsasspecifiedbytheSELECTstatementisconsidered,
andasinglestandarddeviationiscomputedandreturned.
However,STDDEVcanalsobeusedasasingle-rowfunctionincombination
withaslidingwindowofrows.Thefollowingcodecalculatesboththe
cumulativeVARIANCEandthecumulativeSTDDEVoverthesamewindow:
Inouroutput,theVARIANCEandSTDDEVarecalculatedcumulatively,and
youcanseethefinalvaluesmatchtheaggregateresultscomputedinthe
previousexample.
PERCENTILE_CONT
ThePERCENTILE_CONTfunctionuseslinearinterpolationbetweenagiven
row’srowsetceilingandfloortocalculatethepercentilevalueforthatgiven
row.ThePERCENTILE_CONTfunctiontakesasinputapercentageyou
specify,say,.4(for40percent),anditanalyzesagroupofrowsyouspecify;then
itdeterminestheequivalentnumericvalueequaltothatpercentageofthewhole,
byusinglinearextrapolation.
Forexample,let’sdisplayrowsfromSHIP_CABINSthatshowthesquare
footageforeachcabin,butforthecabinswiththesametypeofwindow,
considerthelargestsquarefootage,calculate60percentofthatsquarefootage,
anddisplaythatamount.
HereistheformulausedforcomputingthePERCENTILE_CONT.
First,wecalculatedthepercentagebypartitioningtherowsbyWINDOW.
OursampledatahastwovaluesforWindow:OceanandNone.So,wehavetwo
groups.
Foreverygroup,PERCENTILE_CONTwillconsiderthespecified
percentage(P),whichinourcaseis.60,andthencountthenumberofrows
(RN).ForOceantherearefourrows,showninthepreviousexampleonlines10,
11,12,and15.Usingthatinformation,wecalculateatargetrow(TR)usingthe
followingformula:
TR=(1+(P*(RN−1)))
Usingournumbers,hereisthecalculation:
2.8=(1+(.6*(4–1)))
Ourtargetrownumberis2.8.WehavefourrowsforOcean,soourtargetrow
istheoreticallylocatedbetweenthesecondandthirdrows.Ourobjectiveisto
determinetheSQ_FTvaluethatwouldexistonthistheoreticalrownumber2.8.
Tocalculatethatvalue,weneedtoknowthefollowing:theCEILandFLOORof
ourtargetrownumberandthevaluesatthoserows.
Forourexample,thisinformationisasfollows:
TheCEILfor2.8is3,andthevalueforthethirdrowofOceanis
533.
TheFLOORfor2.8is2,andthevalueatthesecondrowofOceanis
205.
TheformulausedbyPERCENTILE_CONTisasfollows:
(CEIL–TR)*(ValueattheFLOOR)+(TR–FLOOR)*(ValueattheCEIL)
Inotherwords,hereisthecalculation:
(((3–2.8)*205)+((2.8–2)*533))=467.4
TheresultiswhatyouseeineachrowofOceaninouroutput.
TheintentofPERCENTILE_CONTistocomputeforagroupofrowsthe
interpolatedvalueatthespecifiedpercent(inourcase,60percent)ofthewhole
forthatgroup.
ManymorefunctionsexistinSQLthanaredescribedinthisbook.
Spacelimitationspreventmefromshowingdescriptionsandexamplesof
allofthem.Yetanyofthemanyfunctionsmayappearontheexam.Be
suretoreviewtheOracleDatabaseSQLLanguageReferenceManualand
reviewthelengthydescriptionofalltheSQLfunctionsbeforetakingthe
exam.Payparticularattentiontotheinputparametersofeachfunction,
aswellasthedatatypeofeachfunction’sreturnedvalue.
NestingFunctions
Whenafunctionisplacedwithinanexpressioninsuchawaythatitsoutput
becomestheparametervalueforanotherfunctionofthatsameexpression,the
originalfunctionissaidtobenested.Whenonefunctionisnestedwithin
another,thenestedfunctionexecutesfirst.Thenestedfunctionisalsoconsidered
theinnerfunction,asopposedtotheouterfunction,whichreceivestheoutputof
theinnerfunctionasaninputparameter.Whenfunctionsarenestedatmultiple
levels,theinnermostfunctionsexecutefirst.Youcannestmultiplefunctionsand
atmultiplelevels—soyoucannestafunctionwithinafunction,andnestthe
combinationwithinyetanotherfunction.
(Note:Onceyouincludenon-scalarfunctions(i.e.,aggregatefunctions)ina
SELECTstatement,youbegintointroducesomepotentialcomplicationsintothe
process,includingwithregardtonestedfunctions.However,thischapterlooks
exclusivelyatscalarfunctions(single-rowfunctions)sowe’lldeferconcerns
aboutnestedaggregatefunctionsuntilChapter7.
NestedFunctionsandPatterns
Here’sanexamplethatnestsonefunctionwithinanother.Thecombinationof
SUBSTRandINSTRcanbehelpfulinlocatingstringswhosepositionvaries
withinastringbutvariesrelativetoafixeddistancetoanotherstring.Oneoften
usedtechniqueishelpfulwhenworkingwithinformationaboutpostaladdresses,
whenyouarelookingforthetwo-letterabbreviationofoneoftheUnitedStates
thatisoftenfoundafterthecommaplusoneblankspace.SeeFigure5-3foran
example.ThefirstcolumnshowsthecolumnADDRESS2unchanged.Notice,
however,thateachstringcontainsatwo-letterstateabbreviationandthateach
stateisafteracommaplusoneblankspace.Wecanusethatconsistentpatternto
ouradvantage.ThesecondcolumnshowshowwecanusetheINSTRfunction
tofindtheexactlocationofthatcommaineachindividualrowofADDRESS2.
Finally,thethirdcolumnshowshowwecannesttheoutputofeachrow’s
INSTRresultwithinaSUBSTRfunction.Byadding2totheresultsofINSTR
(oneforthecomma,oneforthespace),welocatetheprecisestartofthetwo-
letterstateabbreviationwithineachoccurrenceofADDRESS2andthusareable
toextractthevalueforthethirdcolumn,STATE.
FIGURE5-3 SUBSTRandINSTRcombined
Finally,notethatweordertheoutputbythefindingsofthethirdcolumn.
Prettyinterestingthatwecansortrowsofdatabyasubstringofacolumnwhose
positionchangeswithineachrowofthetable—butit’sentirelypossiblethanks
tothepresenceofaconsistentpatterninthedataandtheuseofnestedfunctions
tolocateandworkwiththoseconsistentpatterns.
CERTIFICATIONSUMMARY
SQLfunctionsperformawidevarietyoftasks,rangingfrommathematical
calculationstotextanalysisanddateconversions.Functionscanbecalledfrom
almostanytypeofSQLstatementandfromavarietyoflocationswithinthose
SQLstatements.SQLfunctionscanbecalledfromtheSELECTstatement’s
selectlistandWHEREclause,fromtheINSERTstatement’svaluelist,fromthe
UPDATEstatement’sSETclauseandWHEREclause,andfromtheDELETE
statement’sWHEREclause.
Afunctiontakesanywherefromzerotomultipleinputparametervalues.
Eachfunctiondoessomesortofprocessingthatincorporatestheinput
parameters,andperhapssomeotherdataaswell.Eachfunctionreturnsexactly
oneresult.
Characterfunctionsperformtasksassociatedwithstringmanipulationand
textanalysis.CharacterfunctionsincludeUPPER,LOWER,INITCAP,
CONCAT,LPAD,RPAD,LENGTH,INSTR,SUBSTR,andothers.Character
functionsacceptinputparametersthatmaybecharacterdataandmayinclude
otherdatatypes,suchasnumericparameters.Andwhileeachcharacterfunction
returnsexactlyonevalue,asdoallfunctions,thecharacterfunctionsdonot
necessarilyreturncharacterdataastheirreturnvalue.Forexample,LENGTH
returnsanumberindicatingthelengthofagivencharacterstring.Buteach
performsataskassociatedwithcharacterstrings.
Numberfunctions,alsoreferredtoasnumericfunctions,performanalysison
numbers.TheyincludeROUND,REMAINDER,MOD,andothers.
Datefunctionsworkwithdateanddatetimeinformation.Datefunctions
includeSYSDATE,ROUND(fordates),TRUNC(fordates),NEXT_DAY,
LAST_DAY,ADD_MONTHS,MONTHS_BETWEEN,
NUMTOYMINTERVAL,NUMTODSINTERVAL,andothers.
Analyticalfunctionscanbeusedtoperformanalysisononeormoresetsof
rowswithinthelargerrowsetofaSELECTstatement.Thosesubsetscan
includeslidingwindowsthatvarywitheachtargetrowandcanbespecifiedby
rownumbersorbyvaluerangeusinglogic.Somefunctionscanbeusedas
aggregatestocalculateasingletotalvalueorasanalyticalfunctionswithin
subsetsofrows—likeSUM,whichcanbeusedasananalyticalfunctionto
calculatearunningtotal.
AnalyticalfunctionsincludeSTDDEV,whichcalculatesstandarddeviation,
andPERCENTILE_CONT,whichcalculatesapercentilevalueusinglinear
interpolationwithinaspecifiedsetorsubsetofrows.Otherfunctionsperform
tasksthatmayormaynotperformprocessingononeormoredatatypes.
Functionsmaybenestedwithineachothersothattheoutputofonefunction
servesastheinputparameterofanother.
✓TWO-MINUTEDRILL
UseVariousTypesofFunctionsThatAreAvailableinSQL
MostSQLfunctionsacceptoneormoreinputparameters.Afew
takenoparameters.
Eachfunctionreturnsonevalue;nomore,noless.
SQLfunctionsperformtasksofvariouskinds.
FunctionscanbeincludedanywhereaSQLexpressioncanbe
included,providedthattherulesofdatatypesarerespected.
FunctionscanbeincludedintheWHEREclauseoftheSELECT,
UPDATE,andDELETEstatements.
FunctionscanbeincludedintheSELECTexpressionlist,INSERT
valuelist,andUPDATESETclause.
UseCharacter,Number,Date,andAnalytical
(PERCENTILE_CONT,STDDEV,LAG,LEAD)Functionsin
SELECTStatements
Characterfunctionsincludetextcleanupandconversionfunctions.
UPPER,LOWER,andINITCAPcanmanagethecaseofastring.
LPADandRPADcanpadastringwithspecifiedcharacters.
INSTR,SUBSTR,CONCAT,andLENGTHcanbeusedtodivide
upandputtogetherdifferentstrings.
Numericfunctionsperformanalysisandcalculations.
TRUNCalwaysroundstowardzero.
REMAINDERandMODarevariationsondivisionandleftover
values.
PARTITIONBYspecifiessetsofrowswithintheSELECT
statementrowset.
OVERcanbeusedtospecifyaslidingwindowofrows.
TheLAGandLEADfunctionsdrawdatafrompriorand
subsequentrows.
TheanalyticalfunctionSTDDEVcalculatesstandarddeviations
cumulatively.
OtherfunctionsincludeLEASTandGREATEST.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
UseVariousTypesofFunctionsThatAreAvailableinSQL
1.Whichofthefollowingistrueoffunctions?
A.Theyneverreturnavalue.
B.Theyoftenreturnavalue.
C.Theyalwaysreturnavalue.
D.Thereisnoconsistentanswertowhethertheyreturnavalueor
not.
2.Whichofthefollowingistrueofcharacterfunctions?
A.Theyalwaysacceptcharactersasparametersandnothingelse.
B.Theyalwaysreturnacharactervalue.
C.Theyaregenerallyusedtoprocesstextdata.
D.TheygenerallyhavethelettersCHARsomewhereinthe
functionname.
3.Built-inSQLfunctions:(Choosethree.)
A.CanbeinvokedfromaDELETEstatement’sWHEREclause.
B.ArewrittenbySQLdevelopersandalsoknownas“user-
defined”functions.
C.AreavailableforusefromtheUPDATEstatement.
D.AreavailableforusewithinaSELECTstatement’sWHERE
clause,aswellastheSELECTstatement’sexpressionlist.
4.Theoutputofafunctionmaybeused:(Choosethree.)
A.Asaninputparametervaluetoanouterfunction.
B.AsacolumnofoutputinaSELECTstatement.
C.AsaninputvaluewithintheVALUESlistofanINSERT
statement.
D.AsanalternativetothekeywordSETinanUPDATEstatement.
UseCharacter,Number,Date,andAnalytical
(PERCENTILE_CONT,STDDEV,LAG,LEAD)Functionsin
SELECTStatements
5.Considerthefollowing:
SELECTMOD(5,3),REMAINDER(5,3)FROMDUAL;
Whichofthefollowingwillbetheresult?
A.1,2
B.−1,2
C.2,1
D.2,−1
6.ConsiderthefollowingSQLstatement:
SELECTSOUNDEX('Donald')FROMDUAL;
WhichofthefollowingismostlikelytobetheoutputofthisSELECT
statement?(Choosethebestanswer.)
A.D543
B.DON3
C.Donalt
D.Donalk
7.YouaretaskedtocreateaSELECTstatementtosubtractfivemonths
fromthehireddateofeachemployeeintheEMPLOYEEStable.Which
functionwillyouuse?
A.LAST_DAY
B.SUBTRACT_MONTHS
C.LAG
D.Noneoftheabove
8.ReviewthisSQLstatement:
SELECTSUBSTR('2009',1,2)||LTRIM('1124','1')FROMDUAL;
WhatwillbetheresultoftheSQLstatement?
A.2024
B.221
C.20124
D.Asyntaxerror
9.ReviewthisSQLstatement:
SELECTTRUNC(ROUND(ABS(-1.7),2))FROMDUAL;
WhatwillbetheresultoftheSQLstatement?
A.1
B.2
C.−1
D.−2
10.ReviewthisSQLstatement:
SELECTLASTNAMEFROMCUSTOMERSWHERELASTNAME=
SOUNDEX('Franklin');
Whatisapossibleresultforthequery?
A.Franklyn
B.Phrankline
C.Ellison
D.Noneoftheabove
11.ReviewthisSQLstatement:
SELECTMONTHS_BETWEEN(LAST_DAY('15-JAN-12')+1,'01-APR-
12')FROMDUAL;
Whatwillresultfromthisquery?
A.>2(somenumbergreaterthan2)
B.2
C.–2
D.<−2(somenumberlessthannegative2)
12.ThePERCENTILE_CONTfunction:
A.ReturnsthesameresultasAVG
B.ReturnsthesameresultasVARIANCE
C.CanbeusedwithROWStospecifyaslidingwindow
D.CanbeusedwithPARTITIONBYtospecifygroupsofdata
13.TheORDERBYinanOVERclause:
A.MustmatchtheORDERBYintheSELECTstatement
B.ReplacestheORDERBYintheSELECTstatement
C.OperatesindependentlyoftheORDERBYintheSELECT
statement
D.Noneoftheabove
14.TheLEADfunctionreturnsdatafrom:
A.ArowpriortothecurrentrowasspecifiedbytheLEAD
function’sORDERBYclause
B.ArowfollowingthecurrentrowasspecifiedbytheSELECT
statement’sORDERBYclause
C.TheLAGfunction’swindow’sspecifiedcolumn
D.TherowspecifiedbytheLEADfunction’soffset
15.Analyticfunctionsareprocessed:
A.AsthefirstsetofoperationspriortotheSELECTcolumnlist
processing
B.AsthefirstsetofoperationsbeforeprocessingtheWHERE
clause
C.AsthelastsetofoperationsbeforeprocessingtheWHERE
clause
D.AsthelastsetofoperationsbeforeprocessingtheORDERBY
clause
SELFTESTANSWERS
UseVariousTypesofFunctionsThatAreAvailableinSQL
1. C.Theyalwaysreturnasinglevalue.
A,B,andDareincorrect.Functionsmayormaynotreturnavalue,each
functionisdifferent,anditisnotpossibletomakeasinglestatementthat
canneverreturnavalue.
2. C.Theyaregenerallyusedtoprocesstextdata.
A,B,andDareincorrect.Theydonotallacceptcharactersasinput
parameters.Some,suchasSUBSTR,takenumericinputparameters.They
donotalwaysreturnacharactervalue—LENGTHdoesnot.Andtheydo
notallhaveCHARintheirfunctionname.
3. A,C,andD.Thefunctionsthatarereviewedinthischapterare
knownasbuilt-infunctionsandareavailabletobeusedanywhereinSQL
whereanexpressioncanbeused.ThatincludesaSELECTstatement’s
expressionlist,anUPDATEstatement’sSETclauses,anINSERT
statement’slistofinputvalues,andtheWHEREclauseofanySQL
statement—SELECT,UPDATE,andDELETE.
Bisincorrect.Built-infunctionsanduser-definedfunctionsareseparate
categories.Bothcanbeinvokedfromthesameplaces—suchasaSELECT
statement’sWHEREclause—butuser-definedfunctionsarewrittenin
languagessuchasPL/SQL.Thischapterlookedonlyatbuilt-infunctions.
4. A,B,andC.Anestedfunctionpassesitsoutputtotheouter
functionasaninputparametertothatouterfunction.Afunctioncanbeused
asacolumninaSELECTstatement,suchasSELECTSYSDATEFROM
DUAL.AfunctioncanbeuseasinputforanINSERTstatement.
Disincorrect.AfunctioncannotreplaceakeywordwithinaSQL
statement.Havingsaidthat,itisnotuncommontowriteaquerythat
producesoutputthatisitselfSQLcodeandthenexecutethosedynamically
generatedSQLstatements.Theoriginalqueryusesstringconcatenationand
otherfeaturestogenerateoutputthatisitselfaseriesofSQLstatements.
ButprocessrequiresacombinationofSQLandSQL*Plusfeaturesused
togethertoproduceoutputthatisSQLcodefreeofoutputheadings,titles,
andotherextraneouscontentsothattheoutputiscomposedofpurelySQL
statements.Theprocesscan“spool”outputtoafilethatisexecutableand
executethatfilewithaSQL*Plusstatementtoautomaticallyexecutethose
statements.ButthatapproachincludesfeaturesofSQL*Plusanditis
outsidethescopeofthisbook.
UseCharacter,Number,Date,andAnalytical
(PERCENTILE_CONT,STDDEV,LAG,LEAD)Functionsin
SELECTStatements
5. D.MODdividesthefirstnumberbythesecondandreturnsthe
remainderrelativetothefirstnumber.REMAINDERdoesthesamething
butreturnstheremainderrelativetothesecondnumber. A,B,andCare
incorrect.Aisincorrectforbothfunctions.Bwouldbecorrectifthe
functionswerereversed.CiscorrectforMODbutisincorrectfor
REMAINDER.
6. A.TheoutputofSOUNDEXisafour-charactercodestartingwith
thesameletteroftheinputvalue,followedbyathree-digitcodebasedon
theSOUNDEXlogic.
B,C,andDareincorrect.DON3cannotbecorrectbecausethesecond,
third,andfourthcharactersshouldbedigits.CandDareincorrect—they
arebothsound-alikepossibilitiesthatmighthavethesameSOUNDEX
code,buttheythemselveswillnotbetheoutputofSOUNDEX.
7. D.Noneoftheabove.ThefunctionyouwantisADD_MONTHSso
thatyoucanaddnegativefivemonthstothecurrentdate.
A,B,andCareincorrect.TheLAST_DAYfunctionreturnsthelastday
ofagivenmonth.ThereisnoSUBTRACT_MONTHSfunction.LAGisan
analyticfunctionthatshowsacolumn’svalueinthepriorrow.
8. A.TheSUBSTRfunctionwillextractdatafromthestring('2009')
startingatthefirstposition(1)andlastingfor2characters(2),resultingin
ananswerof'20'.TheLTRIMfunctionwilltrimoffalloccurrencesofthe1
fromtheleftsideof'1124',resultingin24.Thetworesultsareconcatenated
togetherforafinalresultof2024.
B,C,andDareincorrect.Thereisnosyntaxerrorpresentinthecode.
Eventhoughthevaluesevaluatedbybothfunctionsincludedatathat
consistsofnumerals,bothareenclosedinsinglequotesandthereforeare
treatedascharacterdata.Eveniftheywerenotenclosedinsinglequotes,
SQLwouldperformanautomaticdatatypeconversionanyway.
9. A.Theresultwillbe1.TheABSfunctiondeterminesabsolute
value.Astheinnermostfunction,itwillbeevaluatedfirst,resultinginan
answerof1.7.TheROUNDfunctionwillprocessthevalueof1.7and
roundittothenearesttwodigitstotherightofthedecimalpoint,andthe
resultwillstillbe1.7.Finally,TRUNCwilltruncatethevaluedowntoa
one.
B,C,andDareincorrect.Werethe“,2”omittedasthesecondargument
intheROUNDfunction,optionBwouldbecorrect,whichistosaythe
SQLstatementwouldreturnavalueof2.IfboththeABSandROUND
functionswereeditedoutandonlyTRUNCremained,thestatementwould
return−1,makingCthecorrectanswer.WereonlytheABSfunction
removedfromthestatement,thestatementwouldreturn−2,meaningthatD
wouldbethecorrectanswer.
10. D.Noneoftheaboveiscorrect.
A,B,andCareincorrect.SOUNDEXshouldbeappliedtoboththe
sourceandcomparisontext,butinthisSELECTstatementitisusedon
onlyonesideofthecomparisonoperator.Specifically,theSOUNDEX
codeforthetextstring'Franklin'istheliteralvalue'F652'.Istheliteral
'F652'equaltothevalueforLASTNAMEintheCUSTOMERStable?
Probablynot,unlesssomeonewithanamelikeFreddyF652happenstobe
acustomer.ThepurposeofSOUNDEXistoconvertthevaluesthemselves
(inthiscaseLASTNAMEvalues)usingSOUNDEXandthencompare
thoseconvertedvaluestoagivenSOUNDEXcodetofindsound-alikes.So
ifyouarelookingforlastnamesthatareequaltoorsoundlikeFranklin,
youwouldwanttoconvertthelastnamesandthencomparethose
convertedlastnamestotheSOUNDEXcode,likethis:
WHERESOUNDEX(LASTNAME)=‘F652’
orlikethis:
WHERESOUNDEX(LASTNAME)=SOUNDEX(‘Franklin’)
TouseSOUNDEXeffectively,textonbothsidesofthecomparison
operatorneedtobeSOUNDEXvalues.
11. C.Theanswerwillbe–2.First,theLAST_DAYfunctionwilltransform
thevalueof'15-JAN-12'to'31-JAN-12',andthentheresultofthatwillbe
addedto1,sothatthefirstofFebruarywillresult:'01-FEB-12'.The
differencebetweenthatdateand'01-APR-12'willbeanegative2.
A,B,andDareincorrect.Ifthe“+1”wereremoved,thentheanswer
wouldbelessthan−2.Ifthedateswerereversed,theanswerwouldbe
greaterthanpositive2.Thereisnoscenariowhereanobviousandminor
editwouldresultinavalueofpositive2.
12. D.PERCENTILE_CONTcanbeusedwithPARTITIONBYtospecify
groupsofdatawithinasingleSELECTstatement.
A,B,andCareincorrect.PERCENTILE_CONTisnotthesameas
AVG.Itusesamorecomplexsetoflogictointerpolateananswer.Itdoes
notreturnthesameresultasVARIANCE.PERCENTILE_CONT,unlike
someotheranalyticalfunctions,doesnotsupportslidingwindows.
13. C.TheORDERBYinanOVERclauseoperatesindependentlyofthe
ORDERBYintheSELECTstatement.
A,B,andDareincorrect.TheORDERBYintheOVERclausedoesnot
havetomatchtheORDERBYintheSELECT,nordoesitreplacethe
ORDERBYintheSELECT.Thetwoexistindependentlysothatyoucan
logicallysortasubsetinsupportofthecalculationswithinanalytics,
particularlytherow-by-rowcalculations.
14. D.TheLEADfunctionreturnsdatafromtherowspecifiedbytheLEAD
function’soffset.Theoffsetdefaultsto1butmaybespecifiedwithinthe
LEADfunction.
A,B,andCareincorrect.LEADreturnsdatafromarowfollowingthe
currentrow,asdeterminedbytheoffsetandsortedbytheLEADfunction’s
ORDERBYclause.ThewindowforLEADisspecifiedbyLEAD,not
otheranalyticfunctions,whichspecifytheirownwindows.
15. D.Analyticfunctionsarethelastsetofoperationsperformedbeforethe
ORDERBY.Forthisreason,theymustbespecifiedintheSELECTlistor
ORDERBYonly,nottheWHERE,GROUPBY,orHAVINGclauses.
A,B,andCareincorrect.Theseoptionsareexclusivetothecorrect
answer,whichisthattheanalyticfunctionsareperformedatthelastsetof
operationspriortotheORDERBY.
6
UsingConversionFunctionsandConditional
Expressions
T
CERTIFICATIONOBJECTIVES
6.01DescribeVariousTypesofConversionFunctions
6.02UsetheTO_CHAR,TO_NUMBER,andTO_DATEConversionFunctions
6.03ApplyGeneralFunctionsandConditionalExpressionsinaSELECT
Statement
✓Two-MinuteDrill
Q&ASelfTest
hischapterlooksatthetopicsofconversionfunctionsandconditional
expressions.Conversionfunctionsperformdatatypetransformationfromone
generaltypesuchasnumerictoanothersuchastext.Conditionalexpressions
performevaluationsandreturndatausingcriteriayouspecifyinthecontextof
SQLstatements.These(andother)SQLfunctionscanbeusedinvarious
portionsofaSELECTstatement,includingthecolumnlist,theWHEREand
ORDERBYclauses,withinJOINandotherexpressions,andmore.
CERTIFICATIONOBJECTIVE6.01
DescribeVariousTypesofConversionFunctions
Thepurposeofconversionfunctionsistoconvertdatavaluesfromonedatatype
toanother.Conversionfunctionsdon’tchangevalues;theychangethevalue’s
datatype.Forexample,youmighthavefinancialvaluesstoredwithintext
containingdollarsignsandothersymbolsthatamathematicalfunctionmight
rejectwithanerrormessage.Butyoucoulduseaconversionfunctiontoconvert
thefinancialdatawithinthetexttoanumericdatatype,andthenusewhatever
numericfunctionsyouneedontheconvertedvalues.
InChapter2wediscusseddifferentdatatypes.Mostdatatypesfallintoone
ofthreegeneralcategories:numeric(NUMBER),text(VARCHAR2),anddates
and/ortimes(DATE,TIMESTAMP,etc.).InChapter5welookedatseveral
functionsthatperformvariousoperationsondata,butmanyrequirethat
incomingdatabeofaparticulardatatype.Forexample,mathfunctions
generallyoperateonnumericdatatypeinputs.TheADD_MONTHSfunction
usesDATEvaluesasinput.
Conversionfunctionscanbeusedtotransformdatafromonetypetoanother.
Thiscanenabletheconverteddatatobecomeinputtosomeotherfunction
requiringtheconverteddatatype.Forexample,atablewithacolumnNOTE
thatisdeclaredVARCHAR2(30)mightcontainavalueof'1230'.Thathappens
tobeanumber.Youcouldperformadatatypeconversiononthisvaluetofirst
convertitsdatatypefromtexttonumeric.Onceconverted,itcanbeusedas
numericinputtoafunctionthatcanacceptonlyincomingnumericdata.
Alternatively,iftheconversionattemptfails,thatfailuremightindicatethevalue
isnotnumericafterall;perhapsthezeroattheendof'1230'isreallytheletterO.
Yourbusinessrulesmayrequiresuchaconfirmation.Thisishelpfulwhenyou
areworkinginrealtimewithdata,particularlyifyouarecodingSQLtobeused
onarecurringbasiswithinanapplication.
Conversionfunctionscandomorethanchangeavalue’sdatatype.Some
conversionfunctionsalsofeatureformattingcapabilities.Forexample,ifyou
haveaDATEdatatypethatcontainsrawinformationabouthours,minutes,
seconds,andthedateonthecalendar,youcantransformitintoatextstringthat
spellsouttheentiredateindetail,suchas“Thursday,JulytheFourth,Seventeen
Seventy-Six.”(Seethe“OnTheJob”afterthischapter’sTO_DATEsectionfor
theSQLtomakethatwork.)Similarly,conversionfunctionscantransformraw
numericdataintofinancialformatsthatincludedollarsignsandsymbolsfor
otherinternationalcurrency,properplacementforcommasandperiods
accordingtovariousinternationalformats,andmore.
ThenextsectionwilldelveintothespecificsofTO_NUMBER,TO_CHAR,
andTO_DATE,aswellassomeotherconversionfunctions.However,beforewe
gettothat,wewouldberemissifwedidnotalsoaddressthetopicofexplicit
andimplicitconversion—let’saddressthatnow.
ExplicitandImplicitConversion
Theuseofadatatypeconversionfunctionisexplicitconversion.Butthereis
alsoanimplicitconversionfeatureinSQL.Itoccursautomaticallyin
circumstanceswhereSQLwilldetermineonitsownthatadatatypeconversion
isrequiredbutnotspecified.Whenthishappens,SQLwillperformthedatatype
conversionautomatically.Forexample,let’ssayyouwanttoconcatenatea
numericvaluewithatextstring.
NotethatthesecondvalueintheSELECTlistisnumericyetisincludedina
textfunctionforperformingstringconcatenation.SQLwillrecognizetheintent
andwillperformthecharacterconversionfunctionautomatically,executingthe
SQLstatementappropriately.
SQLisgenerouswithsuchautomaticconversions.Thischaracteristicisa
greatconveniencewhenperformingquick,adhocinteractionswiththedatabase.
Here’sanotherexample(linenumbersadded):
Inthisexample,theSUBSTRfunctioninline3returnsastringvalueof3,
whichisautomaticallyconvertedtoanumericdatatypesinceanumericiswhat
isrequiredfortheADD_MONTHSfunctioninlines2and3.
However,whenyourobjectiveistoprogramcodeforreuse,itisconsidered
gooddesigntoavoiddependenceonautomaticdatatypeconversionandcode
yourintentionsexplicitly.Andmorethansimplygooddesignandcommon
practice,itisalsotheformalrecommendationofOracleCorporationtouse
explicitconversionwherepossible.Thepracticeensuresyourintentinyourcode
isclear,documented,andsupportedinthefuturewhenthedatabaseconditions
maychangeforvariousreasons.Forexample,youmightcodeanimplicitdata
typeconversionthatassumesaparticulartable’scolumnwillhappentocontain
numericvalueswithinaVARCHAR2column.Butwhatif,inthefuture,those
valueschangetoalphabeticallyspelledreferencessuchas“two”and“three”
insteadof“2”and“3”?Theerrormessagethatwillresultwillreferencethe
formulainwhichtheautomaticconversionwasattempted.Ifyouweretohave
originallyusedanexplicitdatatypeconversionfunction,thentheerrormessage
wouldindicatethefailureoccurredattheattempttoconvertthedatatype,
makingthetrueproblemclearandresultinginafasterandmorestraightforward
troubleshootingeffort.
Whencomparingtextandnumericvalues,suchasinanIFstatement,thetext
valuewillgenerallybeconvertedtonumeric.Butnotalways:
Notethatthenumberthreeisnotgreaterthanthenumbertwenty.Butthefirst
SELECTcomparesthetwovaluesastextvalues,andinthedictionary,yes,the
textvalue'3'comesbeforethetextvalue'20',wherethefirstcharacterdefines
theprimarysortingcriteria.Whenbothvaluesaretreatedasnumericvalues,
obviously20isalargernumber.Whenthetwovaluesarecomparedsothatonly
oneisnumeric,anautomaticdatatypeconversionisperformedonthetext
value,andsuddenlybothvaluesaretreatedasnumeric.
Thefollowingaresomeadditionalrulesforautomaticdatatypeconversion:
Numericvalueswillgenerallynotconvertautomaticallytodates.
Numericandtextdatawillgenerallynotconvertautomaticallyto
verylargesizedtypes,suchasLOB,CLOB,RAW,andothers.
Verylargetypeswillgenerallynotautomaticallyconverttoeach
other,suchasfromBLOBtoCLOB,forexample.Somewill,butmany
won’t.
Explicitdatatypeconversionisclear,iseasiertoread,andresultsinbetter
performance;implicitconversionisnotasefficient.Forexample,anindex
canspeedtheperformanceofaSELECTstatementbasedonhowtheWHERE
clauseisphrased,butifthatWHEREclauseusessyntaxthatdependsonan
implicitconversion,theindexmightnotbeusedormightevenbeused
incorrectly.Thisdoesn'taffecttheresultingdata,ofcourse,butitmightresult
inperformancedegradation,whichresultsinlongerprocessingtime.
Additionally,Oracle’sdocumentationwarnsthatthebehaviorofimplicit
conversionissubjecttochangeacrosssoftwarereleases.Thebottomlineis
thatcertaintypesofdatatypeconversionsareperformedautomatically.But
don’tdependontheminyourcode.Useexplicitconversion,aswereviewedin
thissection.
CERTIFICATIONOBJECTIVE6.02
UsetheTO_CHAR,TO_NUMBER,andTO_DATE
ConversionFunctions
Conversionfunctionsconvertthedatatypeofanexpressionfromonedatatype
toanother.Someconversionfunctionswillalsotransformtheformatofthedata
atthesametime.
Forexample,thefollowingisanINSERTstatementthatattemptstostoredata
intotwocolumns.TheCALL_IDcolumnisoftheNUMBERdatatype.The
CALL_DATE_TZcolumnisofthedatatypeTIMESTAMPWITHTIME
ZONE.Here’sanattempttoinsertdataintothattable:
Nowlet’strythatsameINSERTstatementwithaconversionfunction.
Inthisexample,theTO_TIMESTAMP_TZconversionfunctionisusedto
sendthesamedataweusedinourpreviousINSERT.Thisparticularconversion
functionusesa“formatmodel”thatdescribestheformatofthedatatothe
database.Theformatmodelusedhereis'DD-MON-RRHH24:MI:SS'.This
helpstoensurethattheinputdataisrecognizedcorrectly.
Thenextsectiondescribesmanyconversionfunctionswithexamplesoftheir
use.
ConversionFunctions
ThemostcommonlyusedconversionfunctionsareTO_NUMBER,TO_CHAR,
andTO_DATE.Let’slookateachofthesethreefunctions.
TO_NUMBER
Syntax:TO_NUMBER(e1,format_model,nls_parms)
Parameters:e1isanexpression(required);format_modelistheoptionalformat
model.SeeTable6-1foracompletelistofelementsthatmakeuptheformat
model.
TABLE6-1 NumberFormatElements
ThereisanoptionalthirdparameterrepresentingNLSsettings.Itallowsyou
toidentifyanyofthethreeNLSparametersdefinedinTable6-2.Ifincluded,the
thirdparameterforTO_NUMBERconsistsofasinglestringthatencompasses
anyoneormoreofthosethreeNLSparameters.Forexample,thefollowingis
oneexampleofthenls_parmsparameterthatprovidesaspecificationoftwoof
theNLSparameters:
TABLE6-2 TheNLSParameters
Notethatsincethevaluesareenclosedinsinglequotesyetincludesingle
quotesthemselves,eachoccurrenceofthesinglequoteswithinthestringmust
beprecededbytheescapecharacter—whichisasinglequote—toclarifythatthe
valueisinfactasinglequoteaspartofthestring,ratherthantheendofthe
overallstringliteralvalue.
ThesevaluescanbeusedtodeclarenonstandardNLSparametervalues
withintheincominge1parameter.
Process:Transforme1fromanexpression,perhapsacharacterstring,into
anumericvalue,usingformat_modeltodeterminewhatformate1maytake
andwheretoextractthenumericvaluesfromamongtheformatting
information.
Output:Numeric.
Example:Intheexamplethatfollows,ourstartingvalueisastring,
'$17,000.23'.Thisisn’tanumericdatatypebutacharacterstringcontaininga
dollarsignandacomma.Theformatmodelhereexplainsthatthedollarsign
isasymbolandmakesitclearwherethesignificantnumericdatacanbe
foundinthesourcecolumn.The9elementinthefollowingexampleisnota
literalnumber9butratheranelementoftheformatmodelthatindicatesthe
presenceofanydigit.Itisrepeatedtoindicatetheupperboundofacceptable
values.Finally,theoutputisdisplayed—arawnumericvalueextractedfrom
thecharacterstring'$17,000.23'.
Hereisasimilarexampleshowingtheuseofthenls_parmsparameter:
Inthisexample,theincomingvalueshowsadecimalpointtomark
“thousands”andthecommatomarkthedecimalpoint.Thenls_parmsvalue
clarifiesthistotheTO_NUMBERfunction,alongwiththeformatmask,andthe
incomingvalueisinterpretedandtranslated,asshowninthedisplayedoutput.
SeeTable6-1foracompletelistoftheelementsthatcanbeincludedina
numericformatmodel.
TO_CHAR
TheTO_CHARfunctionconvertsdatafromvariousdatatypestocharacterdata.
ThereareactuallythreedifferentTO_CHARfunctions.Theyare,inthemost
technicalofterms,threeoverloadedfunctions.Anoverloadedfunctionisone
thatsharesanamewithoneormorefunctions,butwhereeachisdifferentiated
bytheirrespectiveparameterlists.Eachparameterlistspecifiesadifferent
function,eventhoughtheymighthavethesamename.
TherearethreeversionsofTO_CHAR:onewhosefirstparameterisa
characterstring,anotherwhosefirstparameterisadate,andanotherwhosefirst
parameterisnumeric.
ThefollowingsectionsdescribeeachofthethreeTO_CHARfunctions.
TO_CHAR—CHARACTER
Syntax:TO_CHAR(c)
Parameters:ciseitheranNCHAR,anNVARCHAR2,aCLOB,oran
NCLOB.
Process:TransformstheincomingparameterintoaVARCHAR2.
Output:VARCHAR2.
Example:
Therearesituationswhereyou’llworkwithdatatypesthatcannotaccept,for
example,CLOBdatabutcanaccepttheoutputofTO_CHAR,suchasa
VARCHAR2datatype.
TO_CHAR—NUMBER
Syntax:TO_CHAR(n,format_model,nls_parms)
Parameters:nisanumber(required).Theparameterformat_modelis
optional.Aformatmodelconsistsofoneormoreformatelements,whichyou
sawearlierlistedinTable6-1.Thenls_parmsvalueisthesameparameter
yousawearlierwiththeTO_NUMBERfunction.
Process:Transformsnintoacharacterstring,usingtheoptionalformat
modelforguidanceastohowtoformattheoutputwithanyspecialcharacters
thatmaybedesired,suchasdollarsignsorotherfinancialsymbols,special
handlingofnegativenumbers,andsoon.
Output:Character.
Example:Formatthenumber198withadollarsignandpenny
specification.
TO_CHAR—DATE
Syntax:TO_CHAR(d,format_model,nls_parms)
Parameters:disadateoradateinterval(required).Theparameter
format_modelisoptionalandcanbeusedtoformatdatainavarietyofways.
SeeTable6-3fordetailsonformatmodelsfordatedatatypes.Thenls_parms
parameteristhesameasyousawearlierfortheTO_NUMBERfunction.
TABLE6-3 DateFormatElements
Output:Character.
Example:Here’sanexampleoftheuseofadateformatmodel,asdescribedin
Table6-3:
Changingtheformatmaskstomixedcasesendsanimpliedmessagetomix-
casetheoutputaswell.
Addingthethindicatorintroducesanadditionalimprovement.Theinclusion
ofthwillappendwhateverisappropriateafterthedate—for1,you’llget“1st”;
for2,you’llget“2nd”;andsoon.Here’sanexample:
TheformatmodelisthesecrettoextractingthetimevaluesfromSYSDATE.
Here’sanexample:
NoticeinthisexamplewecanuseeitherAMorPMtoindicatewherewe
wantthemorning/afternoonindicatortobelocatedandwhetherwewantitto
includeperiods.WhetherweuseAMorPMmakesnodifference;the
appropriateindicatorwillappearwherevertheformatmodeldirects,asshownin
theprecedingexample.
TheSYSDATEfunctiondisplaysthecurrentdatebydefaultasstoredonthe
serveronwhichthedatabaseisinstalled.Butburiedinsideofitisalsothetime
ofday,inhours,minutes,andseconds.Thefullsetofdatacanbeextractedfrom
SYSDATEwiththeformatmodelparametersoftheTO_CHARfunction,as
showninTable6-3.Butbeware,thereisdangerhere,andit’syetanother
exampleofhowtrickySQLcanbe.TakealookatthisSQLstatement:
Seeanythingwrongwithit?Perhapsnot.Mostdevelopersdon’t;thiscantrip
upeventhemostexperiencedandseasonedofSQLprofessionals.Tryitonany
databaseinstance,anditwillwork,andtheoutputwillprobablyappeartobe
correct.Butlookcloselyatthevaluedisplayedforthatportionoftheformat
modelrepresentedbyMM.ThenlookatTable6-3.MMisnotminutes;itis
months.Ifyouwantminutes,youneedtouseMI,asinHH:MI:SS.Watchthis
one,folks;it’stricky—thesyntaxistechnicallycorrect,theexecutionwillbe
successful,andthetestdatalookscorrectataglance.Butit’sstillwrong.The
sharpeyeofacertifiedOracleDatabaseSQLExpertshouldflagthis.
TheYYandRRformatmasksinterprettwo-digityearrepresentations
differently.Seethefollowingquery:
Notethatadateenteredas50isinterpretedas2050bytheYYYYformat
mask,but1950isenteredasRRRR.SeeTable6-3formoreinformationabout
YYYYandRRRR.
Thehourofmidnightisthestartingmomentofanewday.Thevaluefor
midnightisstoredconsistentlybutrepresenteddifferentlybasedontheformat
modelused.Ina24-hourformat(HH24),midnightisrepresentedas00,butina
12-hourformat(HH12orHH)midnightisrepresentedas12.Forexample,we
canspecifyadateliteralat12midnightasastring,convertittoaDATEdata
typeusingTO_DATE,andthenuseTO_CHARwithaformatmasktoillustrate
thepoint.
Thefirstcolumntakesthedateliteral'07-JUL-16'atmidnight,convertsittoa
DATEdatatypein24-hourformat,andthenconvertsitbackto24-hourformat.
ThesecondcolumnstartswiththesameDATEvaluebutusesTO_CHARto
displaythedatevaluewitha12-hourformat.RememberthatthePMformat
modelspecifiesthedisplayofPMorAM,whicheverisappropriate.
The24-hourformatshowsmidnightas00,andthe12-hourformatshows
midnightas12.Thevaluestoredisnotdifferent.Onlytherepresentationis
different,inaccordancewiththeformatmodelspecified.
TO_DATE
Syntax:TO_DATE(c,format_model,nls_parms)
Parameters:c=acharacterstring(required);format_modelisaformat
modelaccordingtoTable6-3.Thenls_parmsvalueisthesameparameter
yousawearlierwiththeTO_NUMBERfunction.
Process:TransformthevaluecontainedwithincintoavalidDATEdata
typebystructuringformat_modeltodescribehowthecharacterstringis
formed,identifyingthedateinformationaccordingly.
Output:Date.
Example:Convertanonstandarddaterepresentationtothedefaultformat.
Itiscommontonestconversionfunctionsforvariousreasons—forexample,
toleveragetheirformattingcapabilities.Forexample,todeterminethe
weekdayofaparticulardate,youcannestTO_DATEwithinTO_CHAR,like
this:SELECTTO_CHAR(TO_DATE('04-JUL-1776'),'Day')FROMDUAL,
orfortheformattedversion:SELECTTO_CHAR(TO_DATE('04-JUL-1776'),
'fmDay,Month"the"Ddthsp,Year')FROMDUAL.
AdditionalConversionFunctions
WehavejustdiscussedtheTO_NUMBER,TO_CHAR,andTO_DATE
functions,themostwidelyknownoftheconversionfunctions,eachofwhichis
calledoutasanobjectiveontheexam.Thissectionaddressesadditional
conversionfunctionsthathavealsobeenknowntoappearonthecertification
examandareincreasinglyimportantinworkingwithSQLdatatypessuchas
TIMESTAMP,intervals,andothers.
TO_TIMESTAMP
Syntax:TO_TIMESTAMP(c,format_model,nls_parms)
Parameters:cisacharacterdatatype(required);format_modelmustdefine
theformatofccorrespondingtoTIMESTAMPformatmodelelements
(optional).ThedefaultrequirementisthatcmustbeintheTIMESTAMP
format.Thenls_parmsvalueisthesameparameteryousawearlierwiththe
TO_NUMBERfunction.
Process:ConvertscdatatotheTIMESTAMPdatatype,whichdiffersfrom
DATEinthatitincludesfractionalseconds.Theformat_modelparameter
definesthepatternofc’sdateinformationtothefunctionsothevarious
elementsofTIMESTAMPareidentified—informationforyear,month,day,
hours,minutes,seconds,andfractionalseconds.
Output:AvalueintheTIMESTAMPdatatype.
Example:Hereisacharacterrepresentationofadate.Theformatmodelis
includedtodefinethepatternandinformtheTIMESTAMPfunctionwhere
theDDinformationis,wheretheMONinformationis,andsoon.
TO_TIMESTAMP_TZ
Syntax:TO_TIMESTAMP_TZ(c,format_model,nls_parms)
Parameters:cisacharacterstring(required).Theformat_modelvaluemust
definetheformatofccorrespondingtoTIMESTAMPWITHTIMEZONE
formatmodelelements(optional).Thedefaultrequirementisthatcmustbein
theTIMESTAMPformat.Theoptionalnls_parmsvalueisthesameparameter
yousawearlierwiththeTO_NUMBERfunction.
Process:TransformscintoavalueofTIMESTAMPWITHTIMEZONE,where
format_modeldefinestheformatinwhichcstorestheTIMESTAMPWITH
TIMEZONEinformation.Thetimezonewilldefaulttothatdefinedbythe
SESSIONparameter.
Output:AvalueintheTIMESTAMPWITHTIMEZONEdatatype.
Example:Convertthecharacterstring'17-04-201616:45:30'toadatatypeof
TIMESTAMPWITHTIMEZONEbyprovidingaformatmask.
Notethatthereisn’taconversionfunctionthatspecificallyconvertsvalues
intotheTIMESTAMPWITHLOCALTIMEZONEdatatype.Forthat,use
CAST,describedlaterinthischapter.
TO_YMINTERVAL
Syntax:TO_YMINTERVAL('y-m')
Parameters:yandmarenumberscontainedwithinastring(required).
Process:Transformsyandmintotheyearsandmonthsinaformatofthe
datatypeINTERVALYEARTOMONTHS.
Output:AvalueintheINTERVALYEARTOMONTHSdatatype.
Example:Convertthecharacterexpressionshowingfouryearsandsix
monthsintothedatatypeINTERVALYEARTOMONTHS.
TO_DSINTERVAL
Syntax:TO_DSINTERVAL(sql_format,nls_parms)
Parameters:sql_formatisacharacterstringintheformatrequiredforthe
INTERVALDAYTOSECONDdatatype,whichis'DAYSHH24:MI:SS.FF'.
Forexample,'1514:05:10.001'istheINTERVALDAYTOSECOND
representationfor15days,14hours,5minutes,and10.001seconds.The
nls_parmsvalueisthesameparameteryousawearlierwiththe
TO_NUMBERfunction.
Process:Transformstheincomingvaluerepresentedinsql_formattoa
valueoftheINTERVALDAYTOSECONDdatatype.
Output:AvalueintheINTERVALDAYTOSECONDdatatype.
Example:Thefollowingconvertsavaluerepresenting40days,8hours,30
minutes,and0.03225secondsintotheINTERVALDAYTOSECONDdata
type:
NUMTOYMINTERVAL
Syntax:NUMTOYMINTERVAL(n,interval_unit)
Parameters:n=number(required).interval_unit=oneofthefollowing
values:'YEAR'or'MONTH'.
Process:Convertsdateinformationinnumericformintoanintervalvalue
oftime.
Output:AvalueintheINTERVALYEARTOMONTHdatatype.
Example:Thefollowingexampletakesthenumber27andtransformsit
intoavaluerepresentingatimeintervalof27months,whichequatesto2
yearsand3months,intheINTERVALYEARTOMONTHdatatype.The2-
3valueshowsthat2yearsand3monthsistheamountoftimethatresults.
NUMTODSINTERVAL
Syntax:NUMTODSINTERVAL(n,interval_unit)
Parameters:n=number(required).interval_unit=oneofthefollowing:
'DAY','HOUR','MINUTE',or'SECOND'.
Process:Convertsdateinformationinnumericformintoanintervalvalue
oftime.
Output:AvalueofthedatatypeINTERVALDAYTOSECOND.
Example:Thefollowingexampletranslates36hoursintoitsformal
representationof1dayand12hoursinthedatatypeINTERVALDAYTO
SECOND,whichdisplaysasinglenumberforday,followedbyhours,
minutes,seconds,andfractionalseconds.
CAST
Syntax:CAST(eASd)
Parameters:eisanexpression;disadatatype.
Process:Convertsetod.Thisisparticularlyusefulforconvertingtext
representationsofdatetimeinformationintodatetimeformats,particularly
TIMESTAMPWITHLOCALTIMEZONE.
Output:Avalueintheddatatype.
Example:Inthefollowing,weconvertavalueinthedefaulttimestamp
format,presentedasaliteralvalue:
Ifwewanttouseaformatmaskforanyreason,wecannestacallto,for
example,theTO_TIMESTAMPconversionfunction,asfollows:
CERTIFICATIONOBJECTIVE6.03
ApplyGeneralFunctionsandConditional
ExpressionsinaSELECTStatement
Thepowerofconditionalexpressionsiswellknownineverysoftware
programminglanguage,mostofwhichfeatureanIFstatementwithsome
combinationofELSE,THEN,orsomethingcomparable.Conditional
expressionsevaluatedataatthetimeofcodeexecutionandchangethecode’s
logicalapproachtoprocessingbasedoncertainvaluesofdataatruntime.For
example,processingmaydeterminefirstifaparticularemployeeisinacertain
department,andifso,applyabonus;ifnot,processingmayassignapayraise.
SQLdoesnothaveanIFstatement,butitdoesfeatureconditional
expressions.TheCASEstatementevaluatesanexpressionand,basedonits
value,evaluatesoneofaseriesofexpressionsasspecifiedintheCASE
statement.TheDECODEstatementissimilar;itistheoriginalIFTHENELSE
ofOracleSQL.TheNVLfunctionisusefultoreturningrowsofdatathatmight
containNULLvalueswhereyouwanttheNULLtobereplacedwithsomething
morerelevanttoyourimmediatepurposes,perhapsanumericzero,forexample.
NULLIFisusefulforcomparingtwovaluesandreturningaNULLvaluewhen
bothvaluesareidentical.Forexample,thisishelpfulincertainsituationswhere
youaretryingtoflagonlyvariationsordiscrepanciesbetweentwodatasets.
Thissectionwilllookatthesefunctionsandexpressions.
CASE
Syntax:CASEexpression1WHENcondition1THENresult1WHEN
condition2THENresult2...ELSEresultfinalEND
Parameters:expression1canbeacolumninaSELECTstatement’sselect
listoranyothervalidexpression(required).Ifexpression1evaluatestoa
valuethatisequaltocondition1,thenthefunctionreturnsresult1.Additional
WHEN/THENcomparisonpairsmaybeincluded.Thefirstpairisrequired;
additionalpairsareoptional.AnoptionalELSEattheendwillreturnthe
valueofresultfinalifnoWHEN/THENcomparisonpairmatched.
Process:Compareallthepairstodeterminewhichvaluewillbereturned.If
novaluesmatch,resultfinalisreturned.IfnovaluesmatchandnoELSE
clauseisincluded,NULLisreturned.
Example:
ThefunctionstartswiththekeywordCASEandendswiththekeywordEND.
TheCASEexpressionmayincludeacolumnname,likethis:
NotethatinthisexampletheCASEfunctiontakesinanumericvalueand
returnsatextstring.
DECODE
Syntax:DECODE(e,search_expression,d)
Parameters:e,search_expression,anddareallexpressions.Thefirsttwo
arerequired;thethirdisoptional.
Process:eisarequiredexpression;search_expressionisaseriesofpairsof
expressions,se1andse2,eachseparatedbycommas;ifeequalsse1,then
DECODEshouldreturnse2.Otherwise,itshouldreturnd.Ifdisomitted,
DECODEwillreturnNULL.
InDECODE,twoNULLvaluesareconsideredtobeequivalent.NULL
comparedtoNULLwillproduceaTRUEresultandsendthecorresponding
valuebackifrequired.Inotherwords,theuseofNULLwithinDECODEis
interpretedasacomparisonofISNULLasopposedto=NULL.Rememberthat
=NULLwillalwaysreturnafalsesinceNULLisunknown;thinkofitas“I
don’tknow.”So,issomeparticularvalue,say,4,equalto“Idon’tknow”?Who
knows?Nobodyknows,andSQLassumesFALSEineverysuchcase.ButIS
NULLisaskingadifferentquestion:isthevalueinquestionaNULL,or
unknown,value?That’showDECODEusesNULL,inthecontextoftheIS
NULLcomparison.Inthiscase,acomparisonofaNULLvaluewillresultina
truecondition.
Output:Ifthedatatypesofeandthefirstoccurrenceofse1arecharacter,
DECODEwillreturnavalueofdatatypeVARCHAR2.Ifthedatatypesofe
andthefirstoccurrenceofse1arenumeric,DECODEwillreturnavalueof
numericdatatype.
Example:Intheexamplethatfollows,weselectrowsfromADDRESSES
bylookingattheSTATEcolumnvalueasisandthenuseDECODEto
translatethevaluesinSTATEaccordingtothesearch_expressionin
DECODE,whichinthiscaselooksatonlytwostatevaluesbutcouldhave
easilybeenexpandedtotranslate,ordecode,allofthestatevalues.Thefinal
iteminthisDECODEexampleis'Other',whichisassignedtoallvaluesof
STATEthataren’tfoundinoursearch_expressionlist—includingtheNULL
valueforSTATE.
TheDECODEfunctionisoftenreferredtoastheIF-THEN-ELSEofOracle
SQL.
NVL
Syntax:NVL(e1,e2)
Parameters:e1ande2areexpressions,botharerequired,andbothshould
beofthesamedatatype,butautomaticdatatypeconversionapplieshere,so
valuesmaybedifferentaslongastheyarecapableofbeingconvertedtothe
samedatatypeautomatically.
Process:Ife1hasavalueofNULL,thenNVLreturnsthevaluefore2.
Otherwise,itreturnse1.TheintentofNVListouseitinaquerywhere
multiplerowsarebeingreturnedandyouexpectthatperhapssomeofthe
rowsmightbeNULL.There’snothingwrongwiththatinandofitself,but
whatifyouareperformingsomesortofprocessingthatcan’ttakeavalueof
NULL?Forexample,asingleNULLvaluewithinamathematicalcalculation
willautomaticallymaketheanswerNULL.YoucanuseNVLtosubstitute
somethingmeaningfulintheplaceofNULL—suchasazero—tosatisfythe
outerfunction.
Output:Ife1hasacharacterdatatype,theoutputwillbeVARCHAR2.If
e1isnumeric,theoutputwillbenumeric.IftheoutputisNULL,thenit’s
NULL.
Example:NotethatwehavethreeexpressionsintheSELECTlistthat
follows.Thefirstsimplyshowsthatwe’reusingNVLtoreplacetheliteral
valueforNULLwithazero.Thisisuselessbyitself,butitprovesthepointof
whattheNVLfunctiondoes.Thesecondexpressionshowsanequationin
whichweadd14toNULLandsubtract4fromtheresult.Butwhatis14plus
NULL?It’sNULL.SoisNULLminus4.(Remember,NULListheabsence
ofinformation.Whatis14plus“Idon’tknow”?Theansweris“Idon’t
know,”whichisNULL.)
Sointhethirdexpression,weuseNVLtoreplaceNULLwitha0,andweget
ananswerof10.
ThepurposeoftheprecedingexampleistoshowwhatyoucandowithNVL.
Amorelikelyscenariowouldbesomethinglikethis:
ThisSQLcodeaddsthesquarefeetofaship’scabinwiththesquarefeetof
itsbalcony.Butwhatifthereisn’tabalconyandaNULLvalueisreturnedfor
BALCONY_SQ_FT?TheentireresultwouldbeNULL,unlessweusetheNVL
functionaswedointheprecedingexample.
NULLIF
Syntax:NULLIF(e1,e2)
Parameters:e1ande2arebothexpressions(required).Theymustbethe
samedatatype.
Process:Ife1ande2arethesame,NULLIFreturnsNULL.Otherwise,it
returnse1.
Output:Anexpressionmatchingthedatatypesoftheinputparameters.
Example:NULLIFisgoodforcomparingmultiplerowswhereinanolder
andnewerversionofaparticularvalueexistandyouwanttoculloutthose
thatarestillnotupdatedorperhapshavealreadybeenupdated.
Intheprecedingexample,thecolumnUPDATED_TEST_SCORErepresents
asetofvaluesthatincludesolderTEST_SCOREvaluesandthosethathave
beenrevisedforsomereason.TheNULLIFfunctionhelpsfilteroutonlythose
valuesthatrepresentchangestotheolderoriginalvalues,asevidencedinthe
thirdSELECTcolumnwiththecolumnaliasREVISION_ONLY.
CERTIFICATIONSUMMARY
Conversionfunctionstransformvaluesfromonedatatypetoanother.Themost
commonconversionfunctionsaredate,text,andnumericconversionfunctions.
Theuseofaconversionfunctiontoperformdatatypeconversionisconsidered
“explicitconversion,”asopposedto“implicitconversion”whichmayoccur
automaticallywhenyourcodeomitsanyuseofaconversionfunction,yetthe
situationrequiressuchatransformationandSQLlanguageprocessingperforms
theconversionanyway.Goodprogrammingpracticeistouseexplicitdatatype
conversiontoclarifytheintentofyourcodeandincreasetheoddsofcatching
potentialerrorsincontext,whichcanpotentiallyimprovetroubleshooting.
Certainconversionfunctionsdomorethantransformvaluesfromonedata
typetoanother.Someareusedtoapplyformatmodelstoformatvaluesfor
variouspurposes—suchastoquicklygenerateameaningfulreport,ortoextract
detailsnotpresentinthestandarddefaultpresentationofcertaintypesofdata.
Dateconversionfunctionscanbeusedtodeterminethedayoftheweekfora
givendate,ortobetransformedintoatextualpresentationofthedate;numeric
conversionfunctionscanbeformattedwithfinancialformatsinaccordancewith
agivenlocale,withcommas,periods,andotherspecialcharactersas
appropriate.
ThemostcommonlyusedconversionfunctionsareTO_NUMBER,
TO_CHAR,andTO_DATE.
DatetimeconversionfunctionsincludeTO_TIMESTAMP,
TO_DSINTERVAL,andTO_YMINTERVAL.
TheCASEandDECODEfunctionsarelikeIF-THEN-ELSElogicforaSQL
statement.TheycanbeusedasanyotherfunctioninvirtuallyanyDML
statement,subquery,SELECTlist,WHEREclause,oranywhereaSQL
expressioncanbeinvoked.
CASEcomparesasingleexpressiontoaseriesofWHENconditions.Ifthe
expressionevaluatestoavalueequaltoaWHENcondition,theWHEN
condition’scorrespondingTHENresultisreturned.AnoptionalELSEresult
maybeincludedaswell.TheCASEstatementcompleteswiththekeyword
END.ThecompleteCASEstatementisconsideredanexpressionandassuch
maybeincludedanywhereinaSQLstatementthatanexpressionispermitted.
DECODEconsidersasingleexpression.Ifthatexpressionevaluatestoany
oneofaseriesofspecifiedcomparisonexpressions,thatspecifiedexpression’s
evaluatedvalueisreturned.Anoptionalfinalexpressionmaybeincludedasthe
defaultvaluetobereturnedintheeventthatnoneofthecomparisonexpressions
matchestheevaluatedexpression.
TheNVLfunctiontakestwoparametersthatarebothexpressions.Ifthefirst
expressionevaluatestoanon-NULLvalue,itisreturnedasis,butifitevaluates
toNULL,thesecondexpressionisreturned.ThepurposeoftheNVLfunctionis
toreplaceanyNULLvalueswithsomethingyouspecify.Forexample,you
mightqueryatableofnamesandwanttoreplaceanymissingmiddlenames
withtheexpression"NMN"(fornomiddlename).NVLisidealforqueriesin
whichsomevaluesmightreturnaNULLbutyoupreferinsteadtoreturnan
alternativevalue.Onecommonuseisinmathequations.Forexample,withina
mathexpression,youcanuseNVLtosubstituteanyvaluesthatmightbeNULL
withsomethingthatisn’tNULL—likeazero—toenablethemathequationsto
calculatesomethingmeaningful.
NULLIFcomparesasubjectvaluewithacandidatevalueandreturnsNULL
ifbothvaluesareidentical.Thisisusefulinreportsanalyzingdiscrepancies.
✓TWO-MINUTEDRILL
DescribeVariousTypesofConversionFunctions
Mostdatatypesfallintothecategoriesofnumeric,text,anddata
types.
ConversionfunctionsincludeTO_NUMBER,TO_CHAR,and
TO_DATE.
Ifnodatatypeconversionfunctionisexplicitlyspecified,
sometimesSQLwillperformanimplicitdatatypeconversionifit
determinesthatoneisrequired.
Implicitdatatypeconversioncanresultinunpredictableoutcomes.
Therefore,Oracleformallyadvisestheuseofexplicitdatatype
conversionswherepossible.
SQLprovidesexplicitdatatypeconversionfunctionsforeachdata
type.
UsetheTO_CHAR,TO_NUMBER,andTO_DATEConversion
Functions
TO_CHARcanconvertfromcharacter,date,ornumericdataand
intocharacterdata.
TheconversionfunctionTO_TIMESTAMPcanconverttothe
TIMESTAMPdatatype,whichisthesameasDATEbutaddsfractional
seconds.
ThefunctionsTO_DSINTERVALandTO_YMINTERVALconvert
tointervaldatatypesINTERVALDAYTOSECONDandINTERVAL
YEARTOMONTH.
ApplyGeneralFunctionsandConditionalExpressionsina
SELECTStatement
CASEandDECODEacceptoptionaldefaultvaluestoreturnifthe
evaluatedexpressiondoesn’tmatchanyofthespecifiedpossible
matches.
NVLconsidersanexpression—suchasacolumn—andevaluatesits
valuetodeterminewhetherthevalueisNULL.
NVLispopularinmathequationswherethesourcedatamightbe
NULLbuttheequationrequiressomevalue,perhapsazero.
Theexpression(SALARY+BONUS)willreturnNULLifthe
valueforSALARYisequalto,say,100,butBONUSisNULL.The
expression(SALARY+NVL(BONUS,0))willreturn100ifthe
SALARYis100andtheBONUSisNULL.
NULLIFreturnsaNULLifbothparametersareequal.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
DescribeVariousTypesofConversionFunctions
1.Conversionfunctions:
A.Changeacolumn’sdatatypesothatfuturedatastoredinthe
tablewillbepreservedintheconverteddatatype.
B.Changeavalue’sdatatypeinanequationtotellSQLtotreatthe
valueasthatspecifieddatatype.
C.AresimilartoALTERTABLE…MODIFYstatements.
D.ArenotrequiredbecauseSQLperformsautomaticdatatype
conversionwherenecessary.
2.Whichofthefollowingstatementsaretrue?(Choosetwo.)
A.Youcanuseadatatypeconversionfunctiontoformatnumeric
datatodisplaywithdollarsignsandcommas.
B.Thepresenceofanexplicitdatatypeconversiondocumentsyour
intentinthecode.
C.Dependingonthevalues,youcansuccessfullyuseanexplicit
datatypeconversiontotransformnumericvaluestotextbutnotthe
otherwayaround;youcan’texplicitlyconverttexttonumeric.
D.Animplicitdatatypeconversionperformsfasterthananexplicit
datatypeconversion.
3.Conversionfunctionscannotbeusedto:
A.Formatdatevalues
B.Convertcolumnstonewdatatypes
C.Transformdata
D.Createuser-defineddatatypes
UsetheTO_CHAR,TO_NUMBER,andTO_DATEConversion
Functions
4.Ifyouwanttodisplayanumericvaluewithdollarsignsandcommas,
whichofthefollowingisthebestapproachtotake?
A.TheTO_NUMBERfunctionwithaformatmodel
B.TheTO_CHARfunctionwithaformatmodel
C.Acombinationofstringliteralsthatcontaincommasanddollar
signs,alongwiththeCONCATfunction
D.TheMONEYdatatype
5.WhichofthefollowingSQLstatementswilldisplaythecurrenttime,
inhours,minutes,andseconds,asdeterminedbytheoperatingsystemon
whichthedatabaseserverresides?
A.SELECTTO_CHAR(SYSDATE)FROMDUAL;
B.SELECTTO_CHAR(SYSDATE,'HR:MI:SE')FROMDUAL;
C.SELECTTO_CHAR(SYSDATE,'HH:MI:SS')FROMDUAL;
D.SELECTTO_CHAR(SYSDATE,'HH:MM:SS')FROMDUAL;
6.WhichqueryreturnsanexpressionofthedatatypeINTERVALYEAR
TOMONTHSrepresentinganintervalof1yearand3months?
A.SELECTTO_YMINTERVAL('01:03')FROMDUAL;
B.SELECTTO_YMINTERVAL('01-03')FROMDUAL;
C.SELECTTO_INTERVALYM('01:03')FROMDUAL;
D.SELECTTO_INTERVALYM('01-03')FROMDUAL;
7.Youneedtodeterminethedayoftheweekforaparticulardateinthe
future.Whichfunctionwillrevealthisinformation?
A.TO_CHAR
B.DAY_OF_WEEK
C.TO_DATE
D.Noneoftheabove
8.Youaretaskedtocreateareportthatdisplaysthehoursandminutesof
thecurrentdateinareport.Whichofthefollowingwillsatisfythis
requirement?
A.TO_DATE(SYSDATE,'HH:MM')
B.TO_DATE(SYSDATE,'HH:MI')
C.TO_CHAR(SYSDATE,'HH:MM')
D.TO_CHAR(SYSDATE,'HH:MI')
9.Whichformatmaskreturnsthelocalcurrencysymbol?
A.L
B.C
C.$
D.Noneoftheabove
ApplyGeneralFunctionsandConditionalExpressionsina
SELECTStatement
10.ThepurposeofNULLIFisto:
A.ReturnaNULLifasinglecolumnisNULL
B.ReturnaNULLifasingleexpressionisNULL
C.Bothoftheabove
D.Noneoftheabove
11.Considerthefollowingquery,itsoutput,andasubsequentquery:
Whatistrueofthefinalqueryshownpreviously?
A.Itwillreturn“norowsfound”becausethereisnoPRICEof10.
B.ItwillreturnonlytherowwhereLINE_ITEMis210.
C.ItwillreturnnorowsbecausethereisnoPRICEof10.
D.Itwillreturnthreerows,butitwillnotchangethepriceforline
items100and184.
12.ConsiderthefollowingtablelistingfromthetableALARM_HISTORY:
Youaretaskedtocalculatetheaveragenumberofalarmincidentsper
dayinALARM_HISTORY.Youknowthefollowingqueryissyntactically
correct:
However,youareawarethatthevalueforINCIDENTSmightbe
NULL,andyouwanttheAVGreturnedtobecalculatedacrosseveryday
inALARM_HISTORY,notjustthenon-NULLdays.Whichofthe
followingquerieswillachievethisgoal?
13.WhichofthefollowingcanbesaidoftheCASEstatement?
A.Itconvertstexttouppercase.
B.ItusesthekeywordIF.
C.ItusesthekeywordTHEN.
D.ItsENDkeywordisoptional.
14.Considerthefollowingstatement:
WhichofthefollowingstatementsistrueofthepreviousSELECT
statement?
A.Thestatementwillfailwithacompilationerrorbecausethereis
nocolumnaliasontheNVLexpression(line1).
B.Thestatementwillfailbecauseofsyntaxerrorsonlines2and3.
C.ThestatementwillfailbecauseofthekeywordENDonthe
fourthline.
D.Thestatementwillexecutesuccessfully.
15.TheDECODEexpressionalwaysendswith:
A.ThekeywordEND
B.Adefaultexpressiontoreturnifnoothervaluematchedthe
sourceexpression
C.Bothoftheabove
D.Neitheroftheabove
SELFTESTANSWERS
DescribeVariousTypesofConversionFunctions
1. B.AconversionfunctiontellsSQLtotreataspecifiedvalueasa
specifieddatatypeforanysubsequentusewithinaparticularexpression.
A,C,andDareincorrect.Conversionfunctionsdonotchangeanything
aboutatable’sstructure.TheyarenotthesameasALTERTABLE...
MODIFY,whichcanbeusedtochangeacolumn’sdatatypeinatable.
Conversionfunctionshaveatemporaryimpact;theirscopeistheSQL
expressioninwhichtheyarebeingused,andtheyleavenolastingimpact
beyondthat.However,theyareusedsinceyoucannotcountonSQL’s
implicitdatatypeconversionworkingasyourbusinessrulesmightrequire
atalltimes.ItistheformalrecommendationofOracletouseexplicitdata
typeconversionwhererelevantandrequiredandtonotcountonimplicit
conversionwithinyourproductionSQLcode.
2. AandB.Oneofthemostcommonusesofconversionfunctionsis
toformatdata,suchasnumericanddateformatting.Theuseofanexplicit
datatypeconversionfunctionclarifiesyourpurposeinthecodeandyour
expectationaboutwhatsortofvaluesarecontainedwithinthevarious
elementsofyourcode.
CandDareincorrect.Youcanexplicitlyconvertnumerictotextand
alsotexttonumeric;ifthevaluesmakesense,thenconversionwillsucceed.
Inotherwords,youcanconvertthetextvalue'1'tothenumericvalueof1.
Also,explicitconversionfunctionsperformmoreefficientlythanareliance
onimplicitconversions.
3. BandD.Conversionfunctionscannotchangethedatatypeofa
columntosomethingelse.Theycannotcreateuser-defineddatatypes.
AandCareincorrect.Conversionfunctionsarecapableofformatting
andtransformingdate,text,andnumericdataastheyperformdatatype
conversions.
UsetheTO_CHAR,TO_NUMBER,andTO_DATEConversion
Functions
4. B.TheTO_CHARfunctionwouldwork,alongwithaformat
model,suchasTO_CHAR(rawNumber,'$999,999.99').
A,C,andDareincorrect.TheTO_NUMBERfunctionworkswith
formatmasks,butitconvertsfromcharacterstonumericvalues,notthe
otherwayaround.Youmaybeabletouseacombinationofconcatenation
andstringliterals,butitwouldbepainstakinglydifficult,andpeoplewould
laughatyou.Suchanapproachwouldbeparticularlyproblematicina
dynamicenvironmentwherethesignificantnumbersinvolvedcould
fluctuate.ThereisnoMONEYdatatypeinOracleSQL.
5. C.Thecorrectformatmaskis'HH:MI:SS'.
A,B,andDareincorrect.TO_CHARwithnoformatmaskexecutes
successfullybutdoesnothingandshowsthedatealone.ThereisnoSE
formatmask.Districky—itworksandproducesoutput,buttheMM
formatmaskindicatesmonths,notminutes,andislogicallyincorrect.
6. B.TheTO_YMINTERVALfunctioniscorrect,withthesingle
parameterofastringcontainingtwonumbers,separatedbyadash,where
thefirstrepresentsyearsintheinterval,andthesecondrepresentsthe
numberofmonthsintheinterval.
A,C,andDareincorrect.ThereisnoTO_INTERVALYMfunction.The
useofacolonisinappropriateintheTO_YMINTERVALfunction.
7. A.Here’sanexample:SELECTTO_CHAR(SYSDATE,'Day')
FROMDUAL;.
B,C,andDareincorrect.ThereisnoDAY_OF_WEEKfunction.The
TO_DATEfunctionconvertstexttodateformatsbutdoesn’tincludethis
sortofformatting.
8. D.TheTO_CHARfunctionformatsdates.TheHHandMIformat
masksdisplayhoursandminutes,respectively.
A,B,andCareincorrect.TheTO_DATEfunctionwillnotaccept
SYSDATEasincomingdata.TheTO_DATEfunctiondoesperform
formatting,butgenerallynotfordisplayinareport;instead,itcanconvert
formatstotransformincomingdataintotheformatrequiredforstoragein
thedatabase.TheTO_CHARfunctioniscorrect,buttheMMformatmask
isusedformonths,notminutes.
9. A.Listhelocalcurrencysymbolformatmask.
B,C,andDareincorrect.Cisnotaformatmask.The$specifiesthatthe
USDcurrencysymbolshouldbeusedbutwilloverrideanyconflicting
localcurrencysymbol.
ApplyGeneralFunctionsandConditionalExpressionsina
SELECTStatement
10. D.ThepurposeofNULLIFistotaketwoparameters,bothofwhichare
expressions,andreturnaNULLvalueifthetwoexpressionsevaluateto
NULL.Onecommonuseistoanalyzetwosetsofdataandlookfor
discrepancies;theinclusionofNULLIFcanomitthoseexpressionsthatare
identicalinordertohighlightthediscrepancies.
A,B,andCareincorrect.NULLIFdoesnotparticularlycarewhether
oneexpressionisNULLornot;itassesseswhethertwoexpressionsare
identical.
11. D.TheSELECTwillreturnallthreerows,changingonlythepriceforline
items210to10,andnothingelse.
A,B,andCareincorrect.NVLisnotusedheretosearchforrowsthat
matchthespecifiednumber,whichinthiscaseis10.Itisusedtotransform
anyoccurrencesofNULLvaluestothespecifiednumber,which,again,in
thiscaseis10.NVLisnotincorporatedintotheWHEREclauseinthis
situation,soitisonlyfilteringdatawithintherows,notfilteringtherows
themselves;therefore,itisnotgoingtolimittherowsreturned,asisthe
casewithallfunctions.NVLisnodifferentinthatregard.
12. B.TheNVLfunctionshouldbeappliedfirst,whichmeansitshouldbethe
innermostnestedfunction.NVLrequirestwoparameters. A,C,andD
areincorrect.NVLdoesnotworkwithoneparameter,itrequirestwo.The
NVLfunctionshouldbetheinnermostfunctioninordertofirsttransform
NULL
13. C.ItusesthekeywordTHEN.Here’sanexample:SELECTCASE
CAPACITYWHEN2074THEN'MEDIUM'WHEN4000THEN
'LARGE'ENDFROMSHIPS;.
A,B,andDareincorrect.Itdoesnotconverttext;CASEisaconditional
expression.ItdoesnotincorporatetheIFkeywordbutisoftensaidtobe
sortofanIF-THEN-ELSEexpression.ThekeywordENDisrequired.
14. B.TheSQLstatementcontainsthesamesyntaxerrorrepeatedtwice:the
keywordWHEREisincorrect.ThekeywordWHENiscorrect.
A,C,andDareincorrect.Thecolumnaliasisoptionalbutnotrequired.
ThekeywordENDiscorrectandrequiredforCASE.Thestatementwill
notexecutesuccessfullyduetotheWHEREsyntaxconflict.
15. D.Neitheransweriscorrect.ThekeywordENDisusedwithCASEbut
neverappearswithDECODE.DECODEdoesacceptadefaultvalue,but
itsinclusionisoptionalandnotrequired.
A,B,andCareincorrect.
7
ReportingAggregatedDataUsingtheGroup
Functions
I
CERTIFICATIONOBJECTIVES
7.01DescribetheUseofGroupFunctions
7.02GroupDatabyUsingtheGROUPBYClause
7.03IncludeorExcludeGroupedRowsbyUsingtheHAVINGClause
✓Two-MinuteDrill
Q&ASelfTest
nChapter5,welookedatsingle-rowfunctions,whichprocessrows
individuallyandreturnoneanswerforeachrow.Thischapterreviews
functionsandfeaturesinSQLthathavetheabilitytoprocesszeroormorerows
asalogicalset,analyzedtogethertoreturnasingle-rowresult.Thesefunctions
arereferredtoasgroupfunctionssincetheyacceptinputfromgroupsofzeroor
morerows.WewillalsolookattwonewclausesintheSELECTstatement:the
GROUPBYclauseanditscompanion,theHAVINGclause.GROUPBYand
HAVINGareusedwithgroupfunctions.Youwillneedtofullyunderstandthese
conceptsandtheirusesinordertopasstheexam.
CERTIFICATIONOBJECTIVE7.01
DescribetheUseofGroupFunctions
ThefunctionswereviewedinChapter5arereferredtoassingle-rowfunctions.
Thetermsingle-rowmeansthateachfunctionreturnsonevalueforeachonerow
itencounters.Anothertermforsingle-rowfunctionisscalarfunction.
Thefocusofthischapteristhecategoryreferredtoasgroupfunctions.A
groupfunctionreturnsonevalueforeachsetofzeroormorerowsitencounters.
Therearetwokindsofgroupfunctions:aggregateandanalyticfunctions.
Aggregatefunctionsarealsoknownasmultirowfunctions.Aggregate
functionsaretypicallyusedwithaSELECTstatementthatselectsmanyrows,
wheretheaggregatefunctionscansasetofrowsandreturnsasingleanswerfor
allofthem.
Analyticfunctionscanconsiderasetofrowsandprocessthemasasingleset
orasvaryingsubsets,includingoverlappingsubsets.Inotherwords,asingle
sourcerowmayberepresentedinmorethanonesubsettedrowsofananalytic
function’soutput.
You’vealreadyseenthesyntaxofanalyticfunctionsinChapter5whenwe
lookedattheSTDDEV,PERCENTILE_CONT,LAG,andLEAD.We’llseethat
syntaxagainintheupcomingsectionabouttheRANKandDENSE_RANK
groupfunctions.
Manyofthegroupfunctionscanbeusedasanaggregatefunctionandalsoas
ananalyticfunction,basedonthesyntaxoftheparticularstatementinwhichitis
invoked.Thereareafewexceptions.Table7-1summarizessomeofthemore
commonlyusedgroupfunctionsavailableinSQL.Notethatmostofthe
functionslistedcanperformaseitheranaggregateorananalyticfunction;afew
arelimitedtoonlyonetype.
TABLE7-1 CommonlyUsedAggregateFunctions—Overview
Likescalarfunctions,groupfunctionsacceptinput,processthatinput,and
returnoutput.Alsolikescalarfunctions,groupfunctionsacceptinputofspecific
datatypesandreturnoutputofspecificdatatypes,andtheinputandoutputdata
typesarenotnecessarilythesame,aswithscalarfunctions.Whilenumeric
groupfunctions(whichprocessandreturnnumericdata)arethemostcommon,
manygroupfunctionsprocessdatawithcharacteranddatedatatypes.
Groupfunctionsmustbetreatedseparatelyfromscalarfunctionsbecause
theybehavedifferently.AtypicalSELECTstatementcannotinvokegroup
functionsandscalarfunctionsatthesamelevelofaggregation.Forexample,
consideratableSHIP_SHOPwiththreerowsofdata.Ifweexecuteasimple
SELECTstatementonthetablewithascalarfunctionlikeROUND,wewillget
onerowreturnedforeveryrowprocessed.
IfweexecuteasimpleSELECTstatementagainstthesamesetofthreerows
usingagroupfunctionlikeAVG(foraverage),wewillgetaone-rowresult
showingtheaveragevalueforallthreerows.
Theproblemhereisthatwearestartingwiththreerowsofinputandtryingto
combineresultsofascalarandgroupfunctionatthesamelevelofaggregation.
Thescalar(ROUND)wantstoreturnthreerows,butthegroupfunction(AVG)
wantstoreturnonerow.ThisisnotpermittedtogetherinthesameSELECT
outputandtriggerstheerrormessage.
However,wecanusethetwotypesoffunctionsatdifferentlevelsof
aggregationinthesameSELECTstatement.Forexample,wecouldfirstperform
theaverage(thegroupfunction)andthenroundtheresults(thescalarfunction).
Alternatively,wecouldroundtheindividualvaluesfirstandthentakean
averageoftheroundednumbers.
Eitherway,thepointisthatwecannotapplybothscalarandgroupfunctions
togetherontorowsatthesamelevelofaggregation.However,wecanchooseto
nestthefunctioncallswithinasingleSQLstatementtoprocesseachsetofrows
oneatatime,passingtheresultsofonetoanother,combinedwithinasingle
SELECTstatement,bynestingthefunctions.
Let’slookatthedetailedfunctionalityofsomeofthemorecommonlyused
groupfunctions.
GroupfunctionscanbecalledfromfourplacesinaSELECTstatement:the
selectlist;theORDERBYclause;andeitheroftwoadditionalclauseswe’ll
lookatinthischapter,namely,theGROUPBYclauseandtheHAVINGclause.
Themajorgroupfunctionsaredescribedindetailinthefollowingsections.
Note:Allfunctionsarepresentedintheiraggregatefunctionsyntaxunless
otherwisespecifiedinthetext.
COUNT
Syntax:COUNT(e1)
Parameters:e1isanexpression.e1canbeanydatatype.
TheaggregatefunctionCOUNTdeterminesthenumberofoccurrencesof
non-NULLvalues.Itconsidersthevalueofanexpressionanddetermines
whetherthatvalueisNOTNULLforeachrowitencounters.
Forexample,considertheVENDORStable,showninFigure7-1.
FIGURE7-1 TheVENDORStable
Let’slookatalltherowsintheVENDORStable:
Here’stheoutput,showingthatwehavetworowsinthetable:
Wehaven’tselectedeverycolumnhere,andwedon’tneedtoforourpurposes.
ButassumethattheblankentriesintheoutputareNULLvaluesandnotblank
spaces—sothattheSTATUScolumncontainsonlyonevalue,andCATEGORY
hasnone.
Nowlet’slookatthefollowingSELECTstatementthattriestocount
occurrencesofdataineachofthesecolumns:
ThetermNULLdoesnotdescribeavalueatallbutratherthelackofavalue.
Itisthedatabasesaying,“Idon’tknowwhatthisvaluemightbe,ifanything.”
KeepthisinmindeachtimeyouencounterthephraseNULL:aNULListhe
lackofavalue.
NoticethatCOUNTignoresanyandallvaluesthatareNULL.Finally,we
cansimplycountthenumberofrowsintheentiretable.
COUNTwillreturnonlythenumber,orquantity,ofnon-NULLvaluesin
columns;or,whenusedtocountrows,itreturnsthenumberofrows.
RecallthatSELECT*FROMtableistheshorthandwayofaskingtoselect
allthecolumnsinagiventable.TheCOUNTfunctionisoftenusedwiththe
asteriskinthisfashiontogetaquickcountonalltherowsinagiventableusing
COUNT(*).
Wecouldhavemixedthesefunctionsinvariouscombinations.
NotethataCOUNToftheasteriskisaskingforacountofallrows.Inthe
raresituationwherearowcontainsnothingbutNULLvaluesinallofits
columns,COUNT(*)willstillcountthatrow.
It’sworthnotingthatCOUNTwillneverreturnNULL.Ifitencountersno
valuesatall,itwillatleastreturnavalueof0(zero).Thisisnotthecasewith
alloftheaggregates,butit’struewithCOUNT.Thisbecomesimportantwhen
workingwithsubqueries,whichwe’llstudyinChapter9.
TheDISTINCTandALLoperatorscanbeusedwithaggregatefunctions.
DISTINCTreturnsonlyuniquevalues.ALListheoppositeofDISTINCTandis
thedefaultvalue.IfyouomitDISTINCT,theALLisassumed.Inotherwords,if
youhaveneverusedDISTINCT,thenyou’vealwaysbeenimplyingALLupto
nowandthusqueryingalltherelevantresults.Soifyouhavethreerowsof
PRICEvaluesof2.99,3.99,and3.99,thenDISTINCTwouldreturnonly2.99
and3.99,whereALLwouldreturnallthreevalues,includingtheduplicates.
HereisanexampleshowingDISTINCTandALLusedwithinaCOUNT
function:
TheCOUNTfunctioncountsoccurrencesofdata,ignoringNULL
values.Butwhencombinedwiththeasterisk,asinSELECTCOUNT(*)
FROMVENDORS,itcountsoccurrencesofrows—andwillincluderows
withallNULLvaluesintheresults.
ThisexampletellsusthatthetablecalledEMPLOYEEShassevenrowswith
valuesforLAST_NAME,ofwhichfiveareuniquevaluesforLAST_NAME,so
twoareduplicates.AlsorememberthatDISTINCTandALLcannotbeused
withtheasterisk.
SUM
Syntax:SUM(e1)
Parameters:e1isanexpressionwhosedatatypeisnumeric.
TheSUMfunctionaddsnumericvaluesinagivencolumn.Ittakesonly
numericdataasinput.SUMaddsallthevaluesinalltherowsandreturnsa
singleanswer.Here’sanexample:
SuchaquerywilladdupallthevaluesforSUBTOTALintheORDERStable
andproduceasingleresult.Here’sanotherexample:
Thisquerywillfindanyandallrowsforwhichtheorderhasan
ORDER_DATEvaluesometimeinthemonthofApril2017andthenwilladdup
allthevaluesintheSUBTOTALcolumnandproduceasingleanswer.
MIN,MAX
Syntax:MIN(e1);MAX(e1)
Parameters:e1isanexpressionwithadatatypeofcharacter,date,ornumber.
ForagivensetofrowsidentifiedbyaSELECTstatement,MINreturnsthe
singleminimumvalue,andMAXreturnsthesinglemaximumvalue.MINand
MAXcanworkwithnumeric,date,andcharacterdata,andtheyusethesame
basiclogicthatORDERBYusesforthedifferentdatatypes,specifically:
NumericLownumbersareMIN;highnumbersareMAX.
DateEarlierdatesareMIN;laterdatesareMAX.Earlierdatesare
lessthanlaterdates.
CharacterAislessthanZ;Zislessthana.Thestringvalue2is
greaterthanthestringvalue100.Thecharacter1islessthanthe
characters10.
NULLvaluesareignored,unlessallvaluesareNULL,inwhichcaseMINor
MAXwillreturnNULL.
Forexample,considerthefollowinglistofdatafromthetableEMPLOYEES:
Nowlet’sidentifyMINandMAXvalues.
NotethatHoddlesteinisalphabeticallythefirstvaluefromthelistof
LAST_NAMEvalues.
EventhoughthedatareturnedbyMINandMAXrepresentsthedatafound
withinasinglerowinthelist,donotbetrickedintothinkingthatthisrepresents
asingle-rowanswer—itdoesnot.SQLseeseachresponseofMINandMAXas
anaggregateanswer,meaningthattheindividualvalueistheanswer
representingthefullsetofrows.
AVG
Syntax:AVG(e1)
Parameters:e1isanexpressionwithanumericdatatype.
TheAVGfunctioncomputestheaveragevalueforasetofrows.AVGworks
onlywithnumericdata.ItignoresNULLvalues.Forexample,let’slookatthe
PAY_HISTORYtable;afterthat,we’llaskfortheaveragevalueofallthevalues
withintheSALARYcolumn.
Whilewe’reatit,wecannesttheresultsofthisquerywithinthescalar
functionROUND,likeso:
WecangetreallyfancyandformatthedatausingtheTO_CHARfunction
andaformatmodel.
IntheselastfewexamplesofSELECTstatements,we’venestedasingle
aggregatefunctionwithintwoscalar,orsingle-row,functions.Youcan
incorporateasingleaggregatefunctionwithinasmanynestedscalarfunctionsas
youwant.Theaggregatefunctionneednotbetheinnermostfunction;youcan
includeoneaggregatefunctionwithanynumberofscalarfunctionsinanested
combination,providedthatalloftheparameterdatatypesarerespected.Butif
youwanttoincludetwoaggregatefunctionswithinanestedcombination,be
careful—therearelimitationsontheuseofnestedaggregatefunctions.Wewill
addressthatissuelaterinthischapter.It’smorecomplexthanitmightappear.
DISTINCTandALLareavailableforusewithAVG.Intheeventthata
table’sdatalistingincludessomerepeatedvalues,theuseofDISTINCTwill
transformtheresultssothattheaverageiscomputedonlyonuniqueoccurrences
ofeachvalue.
MEDIAN
Syntax:MEDIAN(e1)
Parameters:e1isanexpressionwithanumericordatedatatype.
MEDIANcanoperateonnumericordatedatatypes.ItignoresNULLvalues.
TheMEDIANfunctionissomewhatrelatedtoAVG.MEDIANperformsasyou
mightexpect:fromasetofdata,MEDIANreturnseitherthemiddlevalueor,if
thatisn’teasilyidentified,thenaninterpolatedvaluefromwithinthemiddle.In
otherwords,MEDIANwillsortthevalues,andifthereisanoddnumberof
values,itwillidentifythevalueinthemiddleofthelist;otherwise,iftherean
evennumberofvalues,itwilllocatethetwovaluesinthemiddleofthelistand
performlinearinterpolationbetweenthemtolocatearesult.
Here’sanexample:
IfyouweretoexecutethepreviousSQLstatements,thevaluereturnedbythe
SELECTstatementwouldbe3.
RANK
RANKhastodowiththenumericrank(1,2,3,andsoon)ofavaluewithina
largegroupofvalues.Whenatiedsetofvaluesamongrowsisencountered,
RANKassignsthesameranknumbertothetiedrowsbutkeepscountofeach
rowandresumescountingsubsequentrowswiththecorrectlynumbered
position.
TheanalyticversionofRANKreturnstherankingsofasetofrows.The
aggregateversionhasoneparameterofanexpressionpertainingtoarowand
returnstherankforthatvalue.BothversionsofRANKaredescribedinthe
followingsections.
RANK:Analytic
Syntax:RANK()OVER(PARTITIONBYp1ORDERBYob1)
Parameters:p1isapartition.ob1isanexpression.
TheuseofPARTITIONBYisoptional.Allotherelementsarerequired.
TheRANKfunctioncalculatestherankofavaluewithinagroupofvalues.
RanksmaynotbeconsecutivenumberssinceSQLcountstiedrowsindividually,
soifthreerowsaretiedforfirst,theywilleachberanked1,1,and1,andthe
nextrowwillberanked4.
Forexample,notetheuseofRANK()inthefollowingline2(linenumbers
added):
Intheexample,thevaluesreturnedbyRANKareinthecolumnSQ_FT_RK.
TherowsarepartitionedbyROOM_STYLE,sothosearesortedfirst;then
withinagivenpartition,rowsarerankedbySQ_FT.Noteline14,whichisthe
startofanewROOM_STYLE,andtheRANKvaluerestartsat1.Alsonotethat
thenextline,line15,hasthesamevalueforSQ_FT,sotherankingistiedat1.
Next,line16isranked3sincethisisthethirdrowof'Suite'ROOM_STYLES,
andtheSQ_FTof586isnottiedwithanyotherrow.
RANK:Aggregate
Syntax:RANK(c1)WITHINGROUP(ORDERBYe1)
Parameters:c1ande1areexpressions.
Inthisformat,theparameterscanberepeatedinsuchawaythatforeachc1,
youcanhaveacorrespondinge1;foreachc2(ifincluded),theremustbea
correspondinge2;andsoon.Eachsuccessiveparameterisseparatedfromthe
previousparameterbyacomma,asin
Also,thedatatypeofc1mustmatchthedatatypeofe1,thedatatypeofc2
(ifincluded)mustmatchthedatatypeofe2,andsoon.
Here’sanexample:
TheexampleshowsthatforaSQ_FTvalueof533,therankingis4.
DENSE_RANK
DENSE_RANKissimilartoRANK.DENSE_RANKreturnsthenumericrank
(1,2,3,andsoon)ofavaluewithinalargegroupofvalues.Whenatieis
encountered,DENSE_RANKassignsthesamenumbertoeachequivalentvalue.
Butwhenitresumescountingafteratie,thisiswhereDENSE_RANKdiffers
fromRANK.TheDENSE_RANKfunctionwillnotskipanynumbers,andit
willassignthenextsequentialnumber,regardlessofhowmanytied(equivalent)
valuesitjustnumbered.
DENSE_RANK:Analytic
Syntax:DENSE_RANK()OVER(PARTITIONBYp1ORDERBYob1)
Parameters:p1isapartition.ob1isanexpression.
InthecaseofDENSE_RANK,ifthreerowsaretiedforfirst,theywilleach
beranked1,1,and1,andthenextrowwillberanked2.
Forexample,notetheuseofDENSE_RANK()inthefollowingline2:
Notelines16and17.WhenweusedRANK,theranksherewere3and4,
respectively.UsingDENSE_RANK,therankingsare2and3.Oncethetwotied
rowsonlines14and15arereturned,DENSE_RANKresumesranking
subsequentrowswiththenextsequentialnumber,regardlessofhowmanytied
rowsmayhavepreceded.
DENSE_RANK:Aggregate
Syntax:DENSE_RANK(c1)WITHINGROUP(ORDERBYe1)
Parameters:c1isaconstant;e1isanexpressionwithadatatypematchingthe
correspondingc1datatype.Numericandcharacterpairsareallowed.
TherulesfortheaggregateformofDENSE_RANKarethesameasRANK’s
aggregateform.ThedifferenceisthatDENSE_RANKwillreturnavalue
consistentwiththeDENSE_RANKlogicasexplainedintheprevioussection;
thatis,ifaseriesoftiedrowsisencountered,ranknumbersofsubsequentrows
willbeassignedwiththenextsequentialnumber,regardlessofhowmanytied
rowspreceded.So,iffourrowsaretiedforsecond,theywilleachberanked2,
2,2,and2,andthenextrowwillberanked3.
FIRST,LAST
Syntax:aggregate_functionKEEP(DENSE_RANKFIRSTORDERBYe1)
aggregate_functionKEEP(DENSE_RANKLASTORDERBYe1)
Parameters:e1isanexpressionwithanumericorcharacterdatatype.
ThefunctionsFIRSTandLASTaresimilar.Bothareconsideredaggregate
functionsaswellasanalyticfunctions.Foragivenrangeofsortedvalues,each
returnseitherthefirstvalue(FIRST)orthelastvalue(LAST)ofthepopulation
ofrowsdefininge1,inthesortedorder.
Here’sanexample:
Inthisexample,wearedoingthefollowing:
First,we’resortingalltherowsintheSHIP_CABINStable
accordingtothevalueintheGUESTScolumn,andwe’reidentifyingthe
FIRSTvalueinthatsortorder,whichisacomplexwayofsayingthat
we’reidentifyingthelowestvaluefortheGUESTScolumn.
ForallrowswithaGUESTvaluethatmatchesthelowestvaluewe
justfound,determinetheMAXvalueforSQ_FT.
Inothers,displaythehighestnumberofsquarefeetforanyandall
cabinsthataccommodatethelowestnumberofguestsaccordingtothe
GUESTScolumn.
ExperiencedprofessionalsmightrecognizethatFIRSTandLASTperform
tasksthatcanalsobedonewithcertainusagesofself-joinsorviews,whichwe
examineinlaterchapters.Whileself-joinsandviewsarebeneficialfora
varietyofreasons,theuseofFIRSTorLASTasshownpreviouslywillachieve
performanceimprovementsoverthealternativeapproaches.
Others
Therearemoreaggregatefunctionsthanaredescribedinthissection.They
includefunctionstoworkwithnestedtables,functionstoperformlinear
regressionanalysis,andvariousformsofstatisticalanalysis.Thesefunctions
aren’tspecificallyreferencedinthecertificationexamguideobjectives,sowe
won’treviewthemallhere.ButyoucanfindfulldescriptionsoftheminOracle
Corporation’sSQLLanguageReferenceManual.
CERTIFICATIONOBJECTIVE7.02
GroupDatabyUsingtheGROUPBYClause
TheGROUPBYclauseisanoptionalclausewithintheSELECTstatement.Its
purposeistogroupsetsofrowsandtreateachindividualsetasawhole.Inother
words,GROUPBYidentifiessubsetsofrowswithinthelargersetofrowsbeing
consideredbytheSELECTstatement.Inthisway,it’ssortoflikecreatinga
seriesofmini-SELECTstatementswithinthelargerSELECTstatement.
GROUPBYisuniquetotheSELECTstatement;itdoesnotexistinother
SQLstatements.
Let’stakeanotherlookattheSHIP_CABINStable,whichnowhassomenew
columnssincethelasttimeweworkedwithit(seeFigure7-2).
FIGURE7-2 TheSHIP_CABINStable
Let’srunthisSELECTstatementagainstthetable,lookingonlyatrows
whereSHIP_ID=1:
Theresultsareshownhere:
TakealookatthecolumncalledSQ_FT,showingthenumberofsquarefeet
ofeachroomontheship.Let’scomputetheaveragesquarefeetforroomsand
roundofftheanswer:
That’stheaverageforallofthecabinsontheship.Butlookatthedata
listing,andyou’llseethateachoftheship’scabinsseemstofallintooneoftwo
differentcategoriesaccordingtothedataintheROOM_STYLEcolumn.Each
roomiseithera'Suite'ora'Stateroom'.
Ifwewantedtolookattheaverageforjustthesuitesandalsoforjustthe
staterooms,wecouldruntwoindividualqueries,likethis:
Thatisusefulinformation,butit’sarelativelycumbersomewaytogetit.
Usingthisapproach,wehaveto(a)identifytheindividualvaluesfor
ROOM_STYLEandtypethemcarefullyintoourqueries,(b)runmultiple
queries,and(c)obtainouroutputviamultiplequeries.
ThebetterwaytogetthisdoneiswiththeGROUPBYclause.Wecangetthe
sameinformationbytellingSQLtogrouptherowsaccordingtotheirvaluesfor
ROOM_STYLE,whatevertheymaybe.Here’sthequery:
Inthisparticularexample,weaddtheGROUPBYclausetotellSQLtogroup
therowsthathavethesamevalueforROOM_STYLE,andthenwecomputethe
AVGfunctionforeachgroup,ratherthanforalltherowsinthetable.Notethat
we’restillusingtheWHEREclause,soweonlyaddressrowswithaSHIP_ID
valueof1.
TogetanideaofwhatSQLdoeswiththisquery,let’sfirstsorttherows
accordingtoROOM_STYLEandhighlightthetwodifferentgroupsofrows.
OurGROUPBYquerydidn’tincludeanORDERBYclause,butwechoseto
sorttheserowstohighlightthefactthattherearetwogroupsofrows.
NowgobackandlookatourSELECTstatement.Didwespecifyanything
about'Suite'or'Stateroom'?Notspecifically.Wedidn’thaveto.Thedirectiveto
GROUPBYROOM_STYLEtellsSQLtogroupeachsetofrowsthatsharethe
samevalueforROOM_STYLE,whateverthatmaybe.
Wecouldhaveincludedmultipleaggregatefunctionsinthisquery’sselectlist
ifwewanted.Here’sanexample:
TherulesforformingaGROUPBYclauseareasfollows:
TheGROUPBYcanspecifyanynumberofvalidexpressions,
includingcolumnsofthetable.
GenerallytheGROUPBYisusedtospecifycolumnsinthetable
thatwillcontaincommondatainordertogrouprowstogetherfor
performingsomesortofaggregatefunctiononthesetofrows.
Thefollowingaretheonlyitemsallowedintheselectlistofa
SELECTthatincludesaGROUPBYclause:
ExpressionsthatarespecifiedintheGROUPBY.
Aggregatefunctionsappliedtothoseexpressions.
ExpressionsthatarespecifiedintheGROUPBYdonothavetobe
includedintheSELECTstatement’sselectlist.
Let’strygroupingthissamesetofrowsbysomethingelse.Inthisquery,
we’llgroupbytheROOM_TYPEcolumninstead.We’lladdafewotherfeatures
aswell.
Noticethefollowingchangestoourquery:
Aswestated,wechosetogroupbytheROOM_TYPEcolumn.We
alsoputROOM_TYPEintheselectlist.
WeaddedanORDERBYclausethatissortingonthesecond
columnfromtheselectlist,whichinthiscaseistheAVGoftheSQ_FT
column.
WereplacedtheMINfunctionwiththeMAXfunction,justforfun.
UnrelatedtotheGROUPBYfunctionality,wechosetoapplya
formatmodeltotheAVGoutputtocleanitupalittle.
Wealsoaddedacolumnaliasforeachofthelastthreeexpressions,
omittingtheoptionalkeywordASforeachcolumnalias.
NoticetheresultsofourmodifiedSELECTwithGROUPBYclause:
ThevaluesforROOM_TYPEareautomaticallylisted,andinthis
case,fivevalueswerefound—sowehavefiverowsinouroutput,each
representingasetofrowsinthesourcetable.
TheaggregatefunctionsofAVG,MAX,andCOUNTareall
calculatedforeachindividualgroup.
Thatlastpointisimportant.It’stheentirepurposeoftheGROUPBY
function.Ifyoudon’tunderstandit,thentrythis—lookattheoutputofthefirst
row,whichisfortheROOM_TYPEvalueof'Royal',andconsiderthatthe
individualrowyouareseeingintheoutputisthesamedatayouwouldgetifyou
ranthisqueryalone,withouttheGROUPBYclause:
Intheprecedingquery,we’veeliminatedtheGROUPBYclauseand
introducedaWHEREclausetolookonlyatROOM_TYPE='Royal'.Theresult
isthesamedatawefindinthefirstrowoftheGROUPBYweranearlier,except
forthevalueoftheROOM_TYPEcolumn,whichwas'Royal'.Ifyourepeated
thisqueryfourmoretimesandchangedtheROOM_TYPEvalueeachtimeto
theotherfourroomtypevalues('Presidential','Skyloft','Standard',and'Large'),
youwouldeventuallyre-createthesameresultsoftheonesingleGROUPBY
statementweexecutedearlier.
Groupingbyaparticularcolumntransformsthatcolumnintoanaggregate
value—ifonlytemporarilyforthepurposeofthequery.
MultipleColumns
YoucangroupmultiplecolumnswithasingleGROUPBYclause.
Herearesomedetailsoftheprecedingexample:
TheGROUPBYclauseincludestwocolumnsfromthetable:
ROOM_STYLEandROOM_TYPE.Theorderisimportant:ittellsSQL
togroupallrowsfirstthatsharethesamevaluefortheROOM_STYLE
and,foreachsetofrowswiththesameROOM_STYLE,grouprows
withthesameROOM_TYPEvalue.Thereareapparentlysixsuch
groups,accordingtotheoutput.
TheSELECTstatement’sselectlisthappenstoincludethe
ROOM_STYLEandROOM_TYPEcolumnsinthesamepositionsas
theyareintheGROUPBYclause;thisisnotrequired,butitmakesthe
outputlistingeasytoread.
TheORDERBYclausetellsSQLtosorttherowsbasedonthevalue
inthethirditemintheselectlist,whichistheMINaggregatefunction.
EachoftheaggregatefunctionsisformattedwiththeTO_CHAR
formatmodeltoincludecommaswhereappropriateandnarrowthe
columnstoareasonablewidth.
Thefinalcolumninourselectlistisanexpressionthatcalculatesthe
MINandMAXvalues,determinesthedifferencebetweenthem,and
formatstheresults.
Clearlythere’salotgoingoninthisSELECTstatement,butit’sagreat
exampleofaGROUPBYinaction.
ORDERBYRevisited
WhenaGROUPBYisusedinaSELECTstatement,thenifthereisanORDER
BYclauseincludedaswell,itsusewillbesomewhatrestricted.Thelistof
columnsorexpressionsinanORDERBYthatispartofaSELECTstatement
thatusesGROUPBYislimitedtothefollowing:
ExpressionsspecifiedintheGROUPBYclause
Expressionsspecifiedintheselectlist,referencedbyposition,name,
oralias
Aggregatefunctions,regardlessofwhethertheaggregatefunctionis
specifiedelsewhereintheSELECTstatement
ThefunctionsUSER,SYSDATE,andUID
AsingleSELECTstatementmustproduceoutputatjustonelevelof
aggregation.ThisiswhyaSELECTstatementcannotmixscalarand
aggregatevaluesinaselectlist,unlessitistonestthemwithineach
other.
NotethatwhenaGROUPBYisused,theORDERBYclausemustreference
eithercolumnsinthetablethatarespecifiedintheGROUPBYclauseorthe
outputofanaggregatefunctionorboth.Otherreferencesarenotpermitted.
That’snotthecaseforSELECTstatementsingeneral.InascalarSELECTyou
canuseORDERBYoncolumnsinthetablewhethertheyareincludedinthe
SELECTornot.Butthat’snottruewhenaGROUPBYisinvolved.ORDERBY
ismorelimited.
NestingFunctions
Youmightrecallfromourexamplesthatwe’venestedfunctionsinsomeofour
SQLstatements.Theconceptofnestingfunctionsreferstothepracticeof
positioningafunctioninsuchawaythatthevalueitreturnsbecomestheinput
parameterforanotherfunction.Here’sanexample:
Inthisexample,theMEDIANaggregatefunctionisnestedwithinthe
TO_CHARfunction.Thus,theMEDIANfunction,inthisexample,istheinner
function,anditreturnsavaluethatbecomesaninputparametertothe
TO_CHARconversionfunction,whichistheouterfunction.Aslongasthedata
typesmatchup,nestingisallowed.Inthisinstance,MEDIANcanbeusedlike
thisonlyifitisreturningavalueofthedatatypethatTO_CHARcanaccept.
Now,rememberthattherearetwogeneraltypesoffunctions:single-row,or
scalar,functions;andmultirow,oraggregate,functions.Scalarfunctionsreturn
onevalueforeachrowencounteredbytheSQLstatementinwhichthescalar
functionisapplied.Aggregatefunctionsreturnonevalueforeveryzeroormore
rowsencounteredbytheSQLstatement.
Therulesfornestingfunctionsdiffer,dependingonwhetheryouarenesting
aggregateorscalarfunctions.
Scalarfunctionscanbenestedmultipletimes,aslongasthedatatypesmatch.
Thereasonisthatscalarfunctionsalloperateonthesamelevelofdetailwithin
therows—foreveryonerow,ascalarfunctionreturnsonevalue.
Aggregatefunctions,ontheotherhand,behavedifferentlythanscalar
functionswhenitcomestonesting.Thereasonisthataggregatescombinedata
frommultiplerowsintoasinglerow.Oncethathasbeenaccomplished,your
resultingvaluenolongerrepresentsthesamelevelofdetailyouwereoriginally
dealingwith.
Forexample,let’slookagainattheSHIP_CABINStableandconsidera
simpleSELECTstatementwithaGROUPBYclause:
ThisSELECTgroupsrowsaccordingtoROOM_STYLEandROOM_TYPE,as
we’veseen,anddisplaystheMAXvalueforSQ_FTwithineachgroup.The
resultissixrows,whichtellsusthatwehavesixuniquegroupsfor
ROOM_STYLEandROOM_TYPE.Ittellsusnothingaboutthenumberof
rowsthatmightbefoundwithinthesourcedata—butjustsoyouknow,it’sthe
samedatalistwesawearlierinthischapter,whichconsistedof12rows.
Nowlet’strytocomputetheAVGvalueofthesesixMAXvalues:
IfwetrytoexecutethisSELECTstatement,thiswillbetheresult:
Whyarewegettingthiserror?Thereasonissimple:byintroducingAVGinto
theSELECTstatement’sexpressionlist,wearemovingupthelevelof
aggregationahigherdegree,andweareinformingSQLthatwesimplywantone
answerforallofthosegroupedrows.Theproblem:ourGROUPBYistryingto
displayonlyoneanswerforalltherows,buttherearesixdifferent
ROOM_STYLEandROOM_TYPEvaluesforthoserows.Inotherwords,there
isnosingleanswerthatcanrepresentallsixofthoserows.
OnesolutionistomodifyourSELECTstatementbyremovingitemsfromthe
selectlistthatareatinconsistentlevelsofdetail,likethis:
Nowwegetananswer,andwecanseetheresultdisplaysinjustonerow,
whichinturnrepresentsthesixrowsfromthepreviousquery,whichitself
represented12rows.So,wehaveaggregated12rowsinto6andthen6into1—
allwithonequery.Inotherwords,thislatestSELECTstatementanditsAVG
resultrepresentanaggregationofanaggregation.
Let’stryathirdlevelofnestedaggregate:
Itcan’tbedone.Twolevelsdeepisthefurthestyoucangowithnested
aggregatefunctions.
However,weareallowedtointroducenestedscalarfunctionsatanytime.
Here’sanexample:
Tosumup:
Youareallowedtonestaggregatefunctionsuptotwolevelsdeep.
Eachtimeyouintroduceanaggregatefunction,youarerollingup
lower-leveldataintohigher-levelsummarydata.
YourSELECTstatement’sselectlistmustalwaysrespectthelevelof
aggregationandcanonlyincludeexpressionsthatareallatthesame
levelofaggregation.
Andfinally,rememberthatscalarfunctionscanbenestedatanytimeand
havenoeffectonmodifyingthelevelsofrowaggregation.
CERTIFICATIONOBJECTIVE7.03
IncludeorExcludeGroupedRowsbyUsingthe
HAVINGClause
TheHAVINGclausecanexcludespecificgroupsofrowsdefinedintheGROUP
BYclause.YoucouldthinkofitastheWHEREclauseforgroupsofrows
specifiedbytheGROUPBYclause.
TheHAVINGclauseisuniquetotheSELECTstatement;itdoesnotexistin
otherSQLstatements.
TheHAVINGclausedoesnotdefinethegroupsofrowsthemselves;those
groupsmustalreadybedefinedbytheGROUPBYclause.HAVINGdefinesthe
criteriauponwhicheachoftheGROUPBYgroupswillbeeitherincludedor
excluded.
TheHAVINGclausecanbeinvokedonlyinaSELECTstatementwherethe
GROUPBYclauseispresent.
Ifitisincluded,GROUPBYandHAVINGmustfollowWHERE(if
included)andprecedeORDERBY(ifincluded).Table7-2showsthese
relationships.
TABLE7-2 ClausesinaSELECTStatement
Here’sanexample:
NotetheHAVINGclauseonlines7and8.ThisparticularHAVINGrestricts
thegroupsidentifiedintheGROUPBYclausetoonlythoserowswhere
ROOM_TYPE='Standard'orROOM_TYPE='Large'orthevaluefor
MIN(SQ_FT)isgreaterthan1200.
Astheprecedingexampleshows,HAVINGcanusethesameBoolean
operatorsthatWHEREdoes—AND,OR,andNOT.Thesearetheonly
restrictionsonHAVING:
ItcanbeusedonlyinSELECTstatementsthathaveaGROUPBY
clause.
Itcanonlycompareexpressionsthatreferencegroupsasdefinedin
theGROUPBYclauseandaggregatefunctions.
HAVINGcanincludescalarfunctionsaslongastheserestrictionsare
respected.Inotherwords,ascalarfunctioncanbeincorporatedintoalarger
expressionthatreferencesaGROUPBYgrouporanaggregatefunction.Just
rememberthatHAVINGdealswithgroupsofrows,notindividualrows.
CERTIFICATIONSUMMARY
Multirowfunctionsdifferfromsingle-rowfunctionsinthattheyreturnonevalue
foragroupofrows,whereassingle-rowfunctionsreturnoneanswerforeach
individualrow.Single-rowfunctionsarealsoreferredtoasscalarfunctions;
multirowfunctionsarealsoreferredtoasaggregatefunctions.Theavailable
aggregatefunctionsinSQLincludethecommonlyusedfunctionsCOUNT,
SUM,MIN,MAX,AVG,andMEDIAN.Thereareaggregatefunctionsto
supportstandarddeviationandvariance,ranking,linearregressionanalysis,
groupingwithROLLUPandCUBE,XMLsupport,andworkingwithnested
tables.
AggregatefunctionscanbecalledfromfourplacesinaSELECTstatement:
theselectlist,theGROUPBYclause,theHAVINGclause,andtheORDERBY
clause.
IfanaggregatefunctionappearsintheselectlistoftheSELECTstatement,
thenallotherexpressionsmustbeatthesamelevelofaggregation.Youcannot
use,inasingleSELECTstatement,ascalarfunctionononecolumnandan
aggregatefunctiononanother.TheSELECTmustbeabletoreturnrowdatathat
iscollectivelyatthesamelevelofdetail.
TheGROUPBYclausespecifiesoneormoreexpressionsthatSQListouse
togrouprowstogether.AnyvaluesdisplayedintheSELECToutputmustbe
displayedonceforeachgroup.Inthisfashion,theGROUPBYcantransforma
singlecolumnreferenceintoanaggregatereferencebyspecifyingthatcolumnas
aGROUPBYitem.
AnycolumnorexpressionspecifiedintheGROUPBYclausecanalsobe
includedintheSELECTstatement’sselectlist.However,thisisnotrequired.
TheHAVINGclausecanbeusedtofilteroutgroupsthathavebeenspecified
withtheGROUPBYclause.HAVINGworksmuchliketheWHEREclause:
whiletheWHEREclausefiltersoutindividualrows,HAVINGdoesthesame
thingforgroupsofrows.HAVINGisallowedonlyiftheGROUPBYclauseis
present.
IfHAVINGandGROUPBYareincludedinaSELECTstatement,theymust
followtheWHEREclause(ifused)andprecedetheORDERBYclause(if
used).GROUPBYoftenprecedesHAVING,butHAVINGispermittedto
precedeGROUPBYintheSELECTstatement’ssyntax.
✓TWO-MINUTEDRILL
DescribetheUseofGroupFunctions
Groupfunctionsarealsoknownasaggregate,ormultirow,
functions.
Multirowfunctionsreturnonevalueforeverysetofzeroormore
rowsconsideredwithinaSELECTstatement.
Therearegroupfunctionstodetermineminimumandmaximum
values,calculateaverages,andmore.
Groupfunctionscanbeusedtodeterminerankwithinagroupof
rows.
AggregateandscalardatacannotbeincludedinthesameSELECT
statement’sselectlist.
TheCOUNTfunctioncountsoccurrencesofdata,asopposedtothe
SUMfunction,whichaddsupnumericvalues.
TheMINandMAXfunctionscanoperateondate,character,or
numericdata.
TheAVGandMEDIANfunctionscanperformaverageandmedian
calculations,andtheycanignoreNULLvaluesintheircomputations.
SomefunctionssuchasRANKusethekeywordsWITHINGROUP
(ORDERBY)toprocessavalueandidentifyitsrankingwithinthe
overallsetofrowsinthedataset.
GroupDatabyUsingtheGROUPBYClause
TheGROUPBYclauseisanoptionalclauseintheSELECT
statementinwhichyoucanspecifyhowtogrouprowstogetherinorder
toprocessthemasagroup.
TherowgroupsidentifiedbyGROUPBYcanhaveaggregate
functionsappliedtothemsothatthefinalresultoftheSELECTisnota
singleaggregatevaluebutaseriesofaggregatefunctionresults,oneper
group.
GROUPBYcanspecifycolumnsinatable,whichwillhavethe
effectofgroupingrowsintheSELECTthatsharethesamevaluesin
thosecolumns.
WhateveryouspecifyintheGROUPBYmayalsobeincludedin
theSELECTstatement’sselectlist—butthisisnotrequired.
TheeffectofGROUPBYonacolumnistochangethatcolumn
intoanaggregatevalue;inotherwords,bygroupingrowsthathave
commondataforagivencolumnandbyspecifyingthecolumninthe
GROUPBY,youelevatetheinformationinthecolumnfromscalarto
aggregateforthepurposesofthatSELECTstatement.
GROUPBYcanspecifyoneormoreexpressions.
IncludeorExcludeGroupedRowsbyUsingtheHAVINGClause
TheHAVINGclauseisanoptionalclausefortheSELECT
statementthatworksincoordinationwithGROUPBY.
YoucannotuseHAVINGunlessGROUPBYispresent.
HAVINGspecifiesgroupsofrowsthatwillbeexcludedinthe
outputoftheSELECTstatement.
HAVINGperformsthesamefunctionforGROUPBYthatWHERE
performsfortherestoftheSELECTstatement.
HAVINGspecifiesgroupsusingthesameexpressionlogicand
syntaxthatWHEREwoulduse.
TheGROUPBYandHAVINGclausesarenotrequired,butifused,
theymustfollowtheWHEREclauseandprecedetheORDERBY
clause.
WhileGROUPBYtypicallyprecedesHAVINGincommon
practice,thisisnotrequired,andtheycanappearineitherorder;
HAVINGcanprecedeGROUPBY.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
DescribetheUseofGroupFunctions
1.Whichofthefollowingistrueaboutaggregatefunctions?(Choose
two.)
A.ReturnonevalueforeachgroupofrowsspecifiedinaSELECT
statement.
B.Arealsocalledgroupfunctions.
C.Willcausearun-timeerrorwhenusedinSELECTstatements
thatreturnzerorowsoronerow.
D.Canoperateonlywithnumericdata.
2.Reviewthefollowingillustration:
NowreviewthisSQLstatement:
Whatcanbesaidofthisstatement?
A.ItwillfailtoexecutebecauseORDER_DATEisadatedatatype,
andnoaggregatefunctioncanworkwithadatedatatype.
B.Itwillfailtoexecutebecauseitmixesscalarandaggregatedata
intheselectlist.
C.Itwillexecutesuccessfullybutnotproduceanymeaningful
output.
D.ThereisnothingwrongwiththeSQLstatement.
3.Whichofthefollowingaggregatefunctionscanbeusedoncharacter
data?(Choosetwo.)
A.COUNT
B.MIN
C.AVG
D.MEDIAN
4.ExaminethefollowingdatalistingofatablecalledPERMITS:
Whichoneofthefollowingaggregatefunctionscouldbeusedto
determinehowmanypermitshavebeenfiledbyVENDOR_ID101?
A.SUM
B.COUNT
C.MEDIAN
D.HAVING
5.Reviewtheillustrationfromquestion2,andthenreviewthefollowing
SQLstatement:
WhatwillresultfromanattempttoexecutethisSQLstatementonthe
CRUISE_ORDERStable?
A.Itwillfailwithanexecutionerrorbecauseyoucannotusethe
AVGfunctiononaPRIMARYKEYcolumn.
B.Itwillfailwithanexecutionerrorbecauseyoucannotusethe
MINfunctiononaDATEdatatype.
C.Itwillfailwithanexecutionerrorifthetablecontainsonlyone
row.
D.Itwillexecuteandperformasintended.
6.ReviewthefollowingdatalistingfromatableSCORES:
Nowconsiderthefollowingquery:
Whatwillbetheresultofthisquery?
A.ItwillresultinasyntaxerrorbecauseoftheTO_CHAR
function.
B.Itwillresultinanexecutionerror.
C.90.00.
D.60.00.
7.Reviewthefollowingillustration:
WhichofthefollowingSQLstatementswillexecutecorrectly?
A.SELECTRANK(100000)WITHINGROUP(ORDERBY
PROJECT_COST)FROMPROJECTS;
B.SELECTRANK(100,000)WITHINGROUP(ORDERBY
PROJECT_COST)FROMPROJECTS;
C.SELECTRANK(7500000)GROUPBY(ORDERBY
PROJECT_COST)FROMPROJECTS;
D.SELECTRANK('Upgrade')WITHINGROUP(ORDERBY
PROJECT_COST)FROMPROJECTS;
8.WhichofthefollowingaggregatefunctionsignoresNULLvaluesin
itscalculations?(Chooseallthatapply.)
A.MEDIAN
B.AVG
C.SUM
D.MAX
9.Anaggregatefunctioncanbecalledfromwithin:(Choosetwo.)
A.TheHAVINGclauseofanINSERTstatement
B.TheORDERBYclauseofaSELECTstatement
C.TheexpressionlistofaDELETEstatement
D.TheselectlistofaSELECTstatement
GroupDatabyUsingtheGROUPBYClause
10.Reviewtheillustrationfromquestion7.YourtaskistodefineaSELECT
statementthatgroupsrowsaccordingtotheirvalueforPURPOSEand,for
eachpurpose,addsupthevaluesstoredinDAYS.Whichoneofthe
followingquerieswillperformthistask?
11.Reviewtheillustrationfromquestion2,andthenlookattheSQLcodethat
follows:
Recallthatthe'Q'formatmodelisforquarter,soTO_CHARusinga
DATEdatatypewiththe'Q'formatmaskistranslatingthedateintothe
quarterinwhichitfalls—1,2,3,or4.Giventhat,whichofthefollowing
statementsistrueoftheSQLstatement?
A.Itwillfailbecauseofasyntaxerrorinline4sinceyoucannot
usetheTO_CHARfunctionintheGROUPBYclause.
B.Itwillfailbecauseofasyntaxerrorinline1sinceyoucannot
usetheTO_CHARfunctionwiththeCOUNTaggregatefunction.
C.Itwillexecuteandshowthenumberofordersinthe
CRUISE_ORDERStableforeachquarterintheyear2009.
D.Noneoftheabove.
12.Reviewtheillustrationfromquestion7,andthenlookattheSQLcodethat
follows:
WhatwillhappenifyoutrytoexecutethisqueryonthePROJECTS
table?
A.Itwillfailwithasyntaxerrorbecauseline1isnotcorrect.
B.Itwillfailwithanexecutionerrorbecauseyoucannotusea
VARCHAR2columninaGROUPBYclause.
C.Itwillsucceedanddisplayonerowforeachdifferentvaluein
thePURPOSEcolumn.
D.Itwillsucceedanddisplayonerow.
IncludeorExcludeGroupedRowsbyUsingtheHAVINGClause
13.WhichofthefollowingstatementsistrueaboutHAVING?(Choosetwo.)
A.ItcanbeusedonlyintheSELECTstatement.
B.ItmustoccuraftertheGROUPBYclause.
C.ItmustoccuraftertheWHEREclause.
D.Itcannotreferenceanexpressionunlessthatexpressionisfirst
referencedintheGROUPBYclause.
14.Reviewtheillustrationfromquestion7,andreviewtheSQLstatementthat
follows:
WhichofthefollowingstatementsistrueforthisSQLstatement?
A.Itwillfailtoexecutebecauseofasyntaxerroronline4.
B.ItwillincludeonlythoserowswithaPROJECT_COSTvalueof
lessthan500000.
C.ItwillincludeonlythosegroupsofrowsforagivenSHIP_ID
withanaveragevalueofPROJECT_COSTlessthan500000.
D.Itwillfailtoexecutebecauseofasyntaxerroronline1.
15.Reviewtheillustrationfromquestion7.Yourassignment:createaSELECT
statementthatqueriesthePROJECTStabletoshowtheaverageproject
costforeachPURPOSE.Youknowthereareonlytwovaluesfor
PURPOSEinthetable:'Upgrade'and'Maintenance'.Youwanttorestrict
outputtothoserowswhereDAYSisgreaterthan3.Whichofthefollowing
SELECTstatementswillperformthistask?
SELFTESTANSWERS
DescribetheUseofGroupFunctions
1. AandB.Aggregatefunctionsreturnonevalueforeachgroupof
rowsintheSELECTstatement.Theyarealsoreferredtoasgroup
functions,ormultirowfunctions.
CandDareincorrect.AGROUPBYcanbeusedinaSELECT
statementthatreturnszerorows,onerow,ormultiplerows.Someaggregate
functionsoperateoncharacteranddatedatatypes;theyarenotrestrictedto
numericdata.
2. B.Itmixesscalardata(theCRUISE_ORDER_IDcolumn)and
aggregatedata(theCOUNTfunctionappliedtotheORDER_DATE
column).ThisisnotpossiblewithoutaGROUPBYclause.TheGROUP
BYclausecouldbeusedtotransformtheCRUISE_ORDER_IDcolumn
intoanaggregatevaluebyspecifyingGROUPBYCRUISE_ORDER_IDat
theendofthestatementbeforethesemicolonterminationcharacter.
A,C,andDareincorrect.Someaggregatefunctionscanworkwiththe
datedatatype,andCOUNTisoneofthem.
3. AandB.COUNTnumbersoccurrencesofdata.Thatdatacan
includecharacter,date,ornumericdatatypes.MINdeterminesthe
minimumvaluebutwillworkwithcharacterdatatodeterminethevalue
representingthevaluethatwouldappearfirstinanalphabeticsortingofthe
candidatevalues.
CandDareincorrect.AVGworkswithnumericdataonly;MEDIAN
workswithnumericanddate/datetimedataonly.
4. B.COUNTwilldeterminetheoccurrencesofVENDOR_IDinthe
datalisting.
A,C,andDareincorrect.SUMaddsnumbers,whichisnotdesiredhere.
MEDIANdeterminesanaveragevalue.HAVINGisnotanaggregate
function;itisaclauseoftheSELECTstatement.
5. D.Itwillexecute.Thestatementissyntacticallycorrect.
A,B,andCareincorrect.YoucanuseAVGwithaPRIMARYKEY
column.Itmightnotproduceanyusefulinformation,butit’sallowed.You
canalsouseMINwithDATEdatatypes,aswellascharacterstrings.It
doesn’tmatterifthetablehasonlyonerow;thestatementwillstillwork.
Youareallowedtouseanaggregatefunctiononzero,one,ormorerows.
6. C.TheAVGwillcomputebyignoringtheNULLvalueand
averagingtheremainingvalues,resultinginananswerof90.00.
A,B,andDareincorrect.Thereisnosyntaxerrorhere;theTO_CHAR
functioncorrectlyformatstheoutputtoincludecommasifnecessary.There
willbenoexecutionerror,either.IftheAVGfunctionincludedNULL
valuesand,say,treatedthemaszeros,thentheanswerwouldbe60.00.That
couldbeaccomplishedwiththeNVLfunction,asin
AVG(NVL(TEST_SCORE,0)).Butthat’snotincludedasanoptionhere.
7. A.Therequesttoranktheliteralnumericvalueof100000within
thesetofvaluesforPROJECT_COSTasksSQLtoestablishanumeric
rankingforthevalue100000withinthesetofrowsandindicatewherea
rowcontainingavalueof100000forPROJECT_COSTwouldfallwithin
thesortedlist,ifthereweresucharow.
B,C,andDareincorrect.Thenumericliteralvaluecannotincludea
comma.Inotherwords,withintheargumentsforRANK,thevalueof
“100,000”(withoutquotes)isnotseenasonehundredthousandbutinstead
isseenasonehundred,followedbyasecondparameterofthreezeros.Two
parameterscannotbeacceptedbyRANKunlesstherearetwo
correspondingWITHINGROUPexpressions;thereisonlyoneinthe
answerprovided.InC,theGROUPBYismisplaced.InD,'Upgrade'
representsaninvaliddatatypebecausethedatatypesofbothRANKand
ORDERBYmustmatch,andinthisexample,PROJECT_COSTisa
numericdatatype,asweseeintheaccompanyingexhibit.
8. A,B,C,andD.Allofthefunctionsmentionedignorenullvalues.
MAXinparticularisworthemphasizing—rememberthatNULLvaluessort
higherthanNOTNULLvalueswhenORDERBYsortsonacolumn
containingNULLvalues.However,whilethatistrue,onlyNOTNULL
valuesareconsideredbytheMAXfunction.Thesameistruefortheother
functionslistedinthequestion.
Alloftheanswersarecorrect.
9. BandD.TheSELECTstatementallowsanaggregatefunctiontobe
calledfromtheORDERBYclauseandtheselectlist.Ifyouspecifyan
aggregatefunctionfromwithinanORDERBYclausewhenaGROUPBY
clauseispresent,theORDERBYwillsorttheaggregaterowsthateach
representagroupofrows.
AandCareincorrect.ThereisnoHAVINGclauseinanINSERT
statement.ThereisnoexpressionlistinaDELETEstatement.
GroupDatabyUsingtheGROUPBYClause
10. A.SomemightprefertoplacethePURPOSEcolumnbeforethe
SUM(DAYS)expressionintheSELECTexpressionlist,butthatisnot
required.
B,C,andDareincorrect.Bissyntacticallyincorrectsinceyoucannot
putanaggregatefunctionwithinaGROUPBYclause.Cisincorrect
becausetheCOUNTfunctionisusedinsteadofSUM.COUNTwould
counttheoccurrencesofdata,ratherthansumupthevalues.Disjusta
randomcombinationofreservedwordsandnonsense.
11. C.Thestatementissyntacticallycorrectandwillexecute.
A,B,andDareincorrect.TheTO_CHARfunctionisascalarfunction
and,assuch,isnotsubjecttothesamerestrictionsthatanyaggregate
functionis.Forexample,theTO_CHARusedintheGROUPBYclauseis
fine.AndbyusingtheTO_CHARexpressionintheGROUPBY,itcan
alsobeusedintheSELECTexpressionlistinline1,alongwiththe
aggregatefunctionCOUNT.
12. D.Itwillsucceedanddisplayonerow.Thereasonyouknowthisis
becauseline1showsanaggregateofanaggregatewithaGROUPBY
clause.
A,B,andCareincorrect.Line1iscorrect;youareallowedtonestone
aggregatewithinoneotheraggregatefunction.YoucanuseGROUPBYto
groupanydatatype;thereisnorestrictionongroupingbycharacterdata.If
youweretouseonlyoneaggregatefunction,theresultwoulddisplayone
rowforeachuniquevalueofPURPOSE.ButbynestingCOUNTwithin
COUNT,youareaddingupallofthoserowsanddisplayingoneaggregate
answer.
IncludeorExcludeGroupedRowsbyUsingtheHAVINGClause
13. AandC.HAVINGisvalidonlyintheSELECTstatement,nottheother
SQLstatements.HAVINGmustoccuraftertheWHEREclause.
BandDareincorrect.HAVINGcannotbeusedwithoutGROUPBY,but
itisnotrequiredtofollowGROUPBY.HAVINGisnotlimitedto
expressionsidentifiedintheGROUPBYclause;instead,itislimitedto
anyvalidexpressionthataddressesthegroupsestablishedwithinthe
GROUPBYclause.Inotherwords,aggregatefunctionscanbeinvoked
fromwithinHAVING,whethertheyarecalledbyGROUPBYornot.
14. C.Thestatementissyntacticallycorrectandwillproduceaseriesofrows
ofdata.EachrowwillrepresentallvaluesforeachSHIP_IDvalueinthe
table.EachrowrepresentingeachSHIP_IDwillhaveonemaximumvalue
forDAYS.AnysetofrowsforSHIP_IDwhoseaveragevalueof
PROJECT_COSTislessthan500000willbeincluded;allotherswillbe
excluded.
A,B,andDareincorrect.Thereisnosyntaxerroronline4.The
HAVINGclauseisnotrequiredtoreferenceanythingintheGROUPBY.
HAVINGcanreferenceaggregatefunctions;itsonlylimitationisthatit
cannotdirectlyreferencecolumnsinthetableifthosecolumnshavenot
beenincludedintheGROUPBYclause.(ColumnsomittedfromGROUP
BYmaybeincorporatedincertainexpressionsinHAVINGbutcannotbe
directlyreferencedasstandalonecolumns.)Bcouldbetrueonlyifthe
WHEREclausewerepresentandfilteringrowsasBdescribes—the
HAVINGclausedoesn’tincludeorexcluderowsonanindividualbasisbut
insteadincludesorexcludesgroupsofrowsasdefinedbytheGROUPBY
clauseandtheHAVINGclause.
15. A.OneofthemostimportantaspectsofunderstandingHAVINGisto
knowwhennottouseit,andthisisagreatexampleofthat—nothingin
thisquestionsaysanythingaboutrestrictinggroupsofdata,andthatisthe
onlyreasonwhyyouwoulduseHAVING.TheWHEREclauseachieves
thetaskofensuringthatonlyrowswhereDAYSisgreaterthanthreewill
beconsidered.
B,C,andDareincorrect.Thetaskdefinedbythequestiondoesn’t
requireHAVING.Thereisnodescriptioninthequestionthatasksfor
anythingabouttheGROUPStobeexcluded.Bissyntacticallyincorrect
becauseHAVINGcanreferenceonlyaggregatefunctionsorcolumnsthat
areidentifiedintheGROUPBY,andthisdoesneither.Cissyntactically
incorrectbecauseyoucannotenclosethefinalexpressioninparenthesesby
itself.Dissyntacticallycorrectbutdoesnotproducetheanswerthatis
describedinthequestion.Itwillinsteadgroupalltherowsbyboth
PURPOSEandDAYS,whichisnotwhatwasaskedfor;suchaquerycan
potentiallyproducemanymorerowsthanjustthetwoexpected.Inother
words,insteadofgettingonegroupofrowspervalueinPURPOSE,you’ll
getafinerdivisionofdetailwitheachsetofrowscontainingaunique
combinationofbothPURPOSEandDAYS,andthatissomethingdifferent.
8
DisplayingDatafromMultipleTables
T
CERTIFICATIONOBJECTIVES
8.01DescribetheDifferentTypesofJoinsandTheirFeatures
8.02WriteSELECTStatementstoAccessDatafromMoreThanOneTable
UsingEquijoinsandNon-Equijoins
8.03JoinaTabletoItselfbyUsingaSelf-Join
8.04ViewDataThatGenerallyDoesNotMeetaJoinConditionbyUsingOuter
Joins
✓Two-MinuteDrill
Q&ASelfTest
hischapterreviewsvarioustypesofjoins.AjoinisaSELECTstatementthat
retrievesdatafromtwoormoretablesandconnectsthatdatatoreturna
mergedsetofrows.Toaccomplishthejoin,theSELECTstatementspecifies
datainonetablethatisidenticaltodatainanothertable.Tablesthatshare
commondataelementsthatsupportjoinsaresaidtoberelatedtoeachother.
ThisiswhyaSQLdatabaseiscalledarelationaldatabasemanagementsystem;
joiningtablesisthewholepurposeofSQLdatabasesystems.
Thischapterwilllookat
Equijoins,whichjoindatausingtheequalityoperator
Non-equijoins,whichjoindatausingnon-equalityoperators
Innerjoins
Outerjoins
Naturaljoins
Self-joins
We’lldiscussthesyntaxofalloftheseformsofjoinsandlookattheuseof
tablealiases,aswellasanumberofexamples.
CERTIFICATIONOBJECTIVE8.01
DescribetheDifferentTypesofJoinsandTheir
Features
ThereareseveraltypesofjoinsinSQL.Themostcommonlyusedisthe
equijoin.Lesscommonisthenon-equijoin.We’lldiscussbothinthissection.
TypesofJoins
Joinsarecharacterizedinmanyways.Onewayajoinisdefinedisintermsof
whetheritisaninnerjoinoranouterjoin.Anotherissueisthatofequijoinsand
non-equijoins.Thesedescriptionsarenotmutuallyexclusive.
Let’sbrieflylookateachtypeofjoin,afterwhichwewillanalyzeeachonein
detail,withexamples.
InnerJoinsvs.OuterJoins
TherearetwomajorcategoriesofsyntaxforcreatingjoinsinOracleSQL:
Innerjoinsconnectrowsintwoormoretablesifandonlyifthere
arematchedrowsinallthetablesbeingjoined.
Outerjoinsconnectrowsintwoormoretablesinawaythatismore
inclusive—ifdataexistsinonetablethathasnomatchingvaluesin
another,theunmatchedrowwillstillbeincludedintheoutput.
Equijoinsvs.Non-Equijoins
Separatefromtheissueofinnerandouterjoinsistheissueofequijoinversus
non-equijoin:
Equijoinsconnectdataintwoormoretablesbylookingforcommon
dataamongthetables’columns.Inotherwords,anequijoinlooksforan
exactmatchofdata.
Non-equijoinsconnectdatabylookingforrelationshipsthatdon’t
involveequality,suchas“lessthan”or“greaterthan”relationships,or
situationswheredatainonetableiswithinarangeofvaluesinanother.
Mostofthejoinswe’llworkwithwillbeequijoins,butwe’lllookatnon-
equijoinsaswell.
OtherJoins
Thereareotherjoins,suchasself,andnaturaljoins.We’llrevieweachin
subsequentsectionsofthischapter.
CERTIFICATIONOBJECTIVE8.02
UseSELECTStatementstoAccessDatafromMore
ThanOneTableUsingEquijoinsandNon-Equijoins
Thissectionlooksatvariousformsofjoins.Ajoinisaquerythatassociates
rowsofdatainonetablewithdatainanothertable.Atwo-tablejoiniscommon,
butyoucanjointhreeormoretables.Onapracticallevelaquerythatjoinstoo
manytablesintroducesperformanceandmaintenancechallenges.Buthowmany
tablesare“toomany”forajoin?MostindustryleadersIknowsayfiveisabout
thelimit,butI’veseennine-tablejoinsthatmadesenseforacertaincontextona
particularproject.
Thissectionlooksatinnerjoins,includingnaturaljoins,multitablejoins,
non-equijoins,andtheUSINGclause.
InnerJoins
Thefirsttypeofjoinwe’llreviewisaninnerjoin.Aninnerjoinreturnsa
mergedrowfromtwoormoretablesifandonlyiftherearematchedvalues
amongalljoinedtables.Foranygivenrow,ifthereisn’tamatchedvalueinall
tables,thennorowisreturned.
Forexample,let’sconnecttwotableswithaninnerjoin.Everyshipinthe
SHIPStablecanbeassignedahomeportinthePORTStable.Thisisrecordedin
thedatabasebyassigningaHOME_PORT_IDtoeachrowintheSHIPStable.
ThisiswhytheSHIPStableincludesacolumncalledHOME_PORT_ID,which
isdesignatedaFOREIGNKEY.TheFOREIGNKEYconstraintreferencesthe
PORT_IDcolumninthePORTStablesothatanyentryintheSHIPStable’s
HOME_PORT_IDwillbeidenticaltothePORT_IDforthatPORTasitalready
existsinthePORTStable’sPORT_IDcolumn.
Let’slookatoursampledatainthesetables.Firsthere’sthePORTStable:
Next,here’stheSHIPStable:
Asyoucanseefromthesedatalistings,manyshipshaveaHOME_PORT_ID
thatmatchesaPORT_IDinthePORTStable.Ifyouweretoidentifythehome
portfor,say,theCoddElegance,youwouldseethatit’sPORT_ID3,whichis
Tampa.Seeit?Didyoulookatthesampledatatoconfirmwhatwejust
described?Ifyoudid,youcomparedthevalueofHOME_PORT_IDinSHIPSto
thevalueofPORT_IDinPORTs.Thatispreciselywhatyouhavetoexplainin
SQLsyntaxsothatSQLcandothesamething.Inotherwords,tojointhese
tablestogether,wedothefollowing:
IdentifybothtablesintheFROMclause,separatedbythekeywords
INNERJOIN.
Definethecolumnfromeachtablethatisbeingusedtojointhedata
intheONcondition.
Here’sthecodeforaninnerjoin(linenumbersadded):
TheORDERBYissomethingweadded;it’snotrequiredforthejoin.
NotethatthekeywordINNERisnotrequired;wecaneliminateitandgo
withthisapproach:
ThisqueryisthesameastheINNERJOINquerywithonevariation:we
removedtheoptionalkeywordINNERfromline2.Everythingelseisthesame.
Whicheversyntaxweuse—withorwithoutthekeywordINNER—theresult
isthesame.
That’stheoutputfromourinnerjoin.
NotethatwecanaddadditionalWHEREclausecriteriatoourjoin.Let’ssay
wewantedtorestrictouroutputsothatonlytheCharlestonrowswereincluded.
Let’smodifytheINNERJOINsyntax:
Theresultwillbetolimitourresultstoonlythoseshipsthatareportedin
Charleston.
NowgobackbeforeweaddedtheWHEREclauseandlookatouroriginal
outputfromthefirstinnerjoin.Doyouseesomethingmissing?Lookforthe
CoddChampion—itisn’tintheoutput.ThereasonisbecausetheCodd
Champion,akaSHIP_ID3,hasnoassignedvalueforHOME_PORT_ID.Asa
result,thereisnomatchingrowinthePORTStable,andsinceweusedan“inner
join”format,weonlyreturnrowswheretherearematchedvaluesinthejoin
criteria.TheresultisthattheCoddChampionisomitted.Andthat’snotall—we
alsodon’tseeanyvalueforthePORT_ID4,'Miami'.Thereasonisthesame—
thereisnoshipassignedtoMiamiasahomeport.
Thisiswhyourjoinisaninnerjoin.Itonlyreturnsrecordsthathavematched
rowsinbothtables.Ifyouwanttoincludedatainouroutputfromrowsthat
aren’tnecessarilymatchedinalltables,usethe“outerjoin”format.We’lllookat
outerjoinsshortly.
OlderInnerJoinSyntax
Beforewemoveontoouterjoins,let’sreviewanoldvariationoninnerjoin
syntax.Hereitis:
(Note:Thistimeweusedtablealiases.Mostjoinsconnecttablesby
referencingcolumnswithidenticalnames.Inthisexample,thePORTStable
usesPORT_ID,andtheSHIPStableusesHOME_PORT_ID,sotablealiasesare
notrequired.However,ifSHIPShadnameditsforeignkeyPORT_ID,theuseof
tablealiasesinourexamplewouldberequired.You’lllearnmoreabouttable
aliasesinafewpages.)
Inthisform,thejoinisaccomplishedinlines2and3,wherewelistthe
joinedtablesintheFROMclauseandalsoidentifythejoincriterioninline3
withanequalsign.Inthissyntax,thereisnokeywordJOINorON.The
WHEREclausecanincludeadditionalcriteriaasanyWHEREclausemight.
Here’sanexample:
ThisistheolderformofaninnerjointhatOraclehasused,anditstillworks.
Butthatversion,whileclear,succinct,easytouse,andverypopular,is
nonethelessinconsistentwithANSIstandards.Theversionwereviewedearlier
—theversionthatusestheJOINandONkeywords—isformallypreferredandis
consistentwiththeANSIstandardforSQLjoins.
UsingTableAliases
Inourexamplessofar,we’vejoinedtablesusingcolumnsthathavehaddifferent
columnnames.Thisisn’talwaysthecase,however.Forexample,lookatthetwo
tablesinFigure8-1.
FIGURE8-1 TheEMPLOYEESandADDRESSEStables
TheEMPLOYEEStableandtheADDRESSEStablebothhaveacolumn
calledEMPLOYEE_ID.ThatcolumnisthePRIMARYKEYinEMPLOYEES,
andit’stheFOREIGNKEYinADDRESSES.Usingwhatwe’veseensofar,we
mighttrythissyntax:
There’saproblemwiththissyntax.Lookatline1.Thefirstiteminour
SELECTstatement’sselectlistisEMPLOYEE_ID,butwhichtable’s
EMPLOYEE_IDareweintendinghere?Chancesareitwon’tmakethatmuchof
adifferencewithregardtodatadisplay,sincebothcolumnscontainthesame
data—unlessweuseaformofOUTERJOIN,inwhichcasetheremaybea
difference.Regardless,that’snohelptousherebecauseSQLwillrejectthis
statementanywaybecauseoftheambiguouscolumnreference.
Onesolutionistousethefulltablenameasaprefixtothecolumn.
We’veaddedthefulltablenameinfrontofeachreferencetoEMPLOYEE_ID,
separatedbyaperiod,toclarifyourintent.Notethatweneededtomakethese
changesthreetimes—onceonline1andtwiceonline3.Thisisperfectly
acceptableandrepresentsclearandthoroughdesign.
There’sanalternative,however,andit’sthetablealias.Here’sanexampleof
thetablealiasinaction:
Firstlookatline2.AftereachtablereferencedintheFROMclause,welefta
space,followedbyanamewespecify.Thenameneedstomatchtherulesfor
namingdatabaseobjects.ForEMPLOYEESwechoseEM,andfor
ADDRESSESwechoseAD.Wecouldhavechosenanythingwithintherulesof
namingdatabaseobjects.
Sincewechosetocreatetablealiases,wewerealsoabletousethetablealias
asprefixesonlines1and3.Theresultisamoreeasilyreadablequery.
Notethescopeofthetablealiasisthestatementitself.Oncethestatementhas
completedexecuting,thetablealiasisnolongeruseful;itmustbespecified
anewinanysubsequentSQLstatements.
There’snorightorwronganswerastowhichapproachyoushouldchoose—
thefulltablenameprefixorthetablealiasprefix.Eitherway,youshould
considerthefollowingpoints:
Whenwritinganyqueryinwhichacolumnreferenceisambiguous,
youmustdosomethingtoidentifythecolumnclearlytotheSQL
statement,usingeitheratableprefixoratablealias.Otherwise,you’ll
getanerrormessageandtheSQLstatementwon’texecute.
Theuseoftableprefixesandtablealiasesisontheexam.
Thetablealiasismorecommonlyused,inmyever-so-humbleopinion.But
bothwork.
AlsonotethattablealiasescanbeusedinINSERT,UPDATE,MERGE,and
DELETEstatements,aswellasSELECT.
NaturalJoins
Sofar,manyoftheexampleswe’veseenhavejoinedtablesusingcolumnsof
differentnames,suchasHOME_PORT_IDandPORT_ID.It’smorecommon,
however,forsuchcolumnstobenamedwiththesamename.Inotherwords,
whendatabasedesignerscreatetwotablesandintendtolinkthemtogether,itis
gooddesigntogiveidenticalnamestoanycolumnsthatwillbelinked.It’snot
necessarilybaddesigntodootherwise—italldependsonreadabilityandintent.
Butthepointforourdiscussionhereonnaturaljoinsisthatyouwilloftenwork
withtablesthatshareidenticalcolumnnames,anditwillbethesecolumnsupon
whichyourjoinswillprobablybebuilt.
Anaturaljoinisaninnerjoinbydefault,butitcanalsobealeftouterjoin,
rightouterjoin,orafullouterjoin.
Forexample,reviewFigure8-1again.Aswesawintheprevioussection,the
twotablesshownbothhaveacolumncalledEMPLOYEE_ID.Thiscolumnisa
FOREIGNKEYintheADDRESSEStableandthePRIMARYKEYofthe
EMPLOYEEStable.
ThenaturaljoinapproachtellsSQLtolocateanycolumnsinthetwotables
withacommonname,andusethemtojointhetables.Here’sanexample:
NoticetheuseofthekeywordsNATURALJOINinline2.Alsonoticethat
there’snokeywordONanywhereandnowherethatweestablishthejoin
betweenthetwocommoncolumns—whichinthesetwotablesare
EMPLOYEES.EMPLOYEE_IDandADDRESSES.EMPLOYEE_ID.The
NATURALJOINdoesn’trequireanexplicitdeclarationofthesecolumns,
providedthatthecolumnnamesareidentical.
Alsonoticesomethingelse:seethereferencetoEMPLOYEE_IDinline1?
RememberthattherearetwoEMPLOYEE_IDcolumns—oneinEMPLOYEES
andoneinADDRESSES.Normallysuchareferenceinajoinwouldrequirea
tablealias.Butthenaturaljoinforbidssuchtableprefixesonjoincolumnnames.
Theirusewouldresultinasyntaxerror.However,tableprefixesareallowedon
othercolumns—butnotthejoincolumnsinanaturaljoin.
Finally,anaturaljoindefaultstoaninnerjoin,butitworkswithaleftouter
join.
Italsoworkswitharightouterjoin.
Finally,itevenworkswithafullouterjoin.
TheSELECTlistmayreferenceacolumnthatiscommontobothtablesbut
notqualifiedwithatablenameprefix.Ifthishappens,whichtabledoesthe
valuecomefrom?Theanswerdependsonwhichtypeofnaturaljoinisused:
Ifaninnerjoinoraleftouterjoinisused,theleftmosttableisthe
sourceofthevalue.
Ifarightouterjoinisused,therightmosttableisthesource.
Ifafullouterjoinisused,bothtables’rowswillbecombinedtoformthe
output,sothevaluewillbetakenfromthecombinationofbothtables.
USING
ThekeywordUSINGissimilartothenaturaljoin,inthesensethatitsuse
dependsonthepresenceofidenticallynamedcolumnsintheJOIN.Like
NATURAL,USINGcanbeusedwithbothinnerandouterjoins.
Let’slookatanexample.FollowingisalistingofdataintheEMPLOYEES
table:
NextisalistingoftheADDRESStable:
Here’saquerythatjoinsthetwotableswithaUSINGclausethatspecifies
theEMPLOYEE_IDcolumn:
Notethesyntaxhere—we’reusingaLEFTJOINontwotablesthatsharethe
samecolumnnameEMPLOYEE_ID.Aswe’vealreadyseen,thisisavariation
ofanouterjoin.ThekeywordOUTERisoptionalandomittedfromthis
example.
NoticethekeywordUSINGonline3.USINGisfollowedbyacolumnname
enclosedinparentheses.Notablenameprefixisallowedbeforethecolumn
name—nothere,andnotelsewhereinthestatementsuchasline1.
Sincethetablenameprefixisnotallowedinline1,howdoyouknowwhich
table’sEMPLOYEE_IDisintendedintheselectlistinline1?Theansweristhat
itmaybeoneortheother,dependingontherow.Inanouterjoin,whichisalso
anequijoin,thevaluesinbothtablesforEMPLOYEE_IDeitherwillbeidentical
toeachotherorwillincludeoneNULLvalueinoneofthetwotables'columns.
Theoutput,therefore,willshowavalueifanyispresentineithertable;
otherwise,aNULLvaluewilldisplay.Thereasonthisworksisthatthevalues
willneverconflictinanouterjoin.Thejoincondition,bydefinition,willreject
conflictingvaluesandexcluderowswithconflictingvaluesforthejoin
condition.Theresultisthatifyouincludethejoincolumnintheselectlist—
suchastheEMPLOYEE_IDcolumninline1oftheexample—thentheoutput
ofanouterjoin’s“joincolumn”specifiedwiththeUSINGclausewillshowa
valuewhereveravalueispresentineithertable’sjoincolumn;otherwise,itwill
displayaNULLvalue.
Let’sextendourexample.
Thisexampleassumesthepresenceofanadditionalcolumn
(OFFICE_NAME)inbothtablesandperformsthejoinusingthecombinationof
EMPLOYEE_IDandOFFICE_NAME.
MultitableJoins
Sofarwe’velookedonlyatjoinsthatconnecttwotables.Butjoinscanconnect
two,three,ormoretables.Forexample,seeFigure8-2.
FIGURE8-2 PORTS,SHIPS,andSHIP_CABINStables
ThesethreetablescanbejoinedinaSELECTstatementlikethis:
NoticethesyntaxforthisSELECTstatementthatjoinsthreetables:
TheFROMkeywordappearsonce.
Afterline2,whentheoriginaltwo-tablejoincompletes,line3opens
withthekeywordJOIN.
Line3continueswiththethirdtablename,followedbyatablealias,
followedbytheexplicitlydefinedjoincriteria.
Line3intheprecedingSELECTstatementcanberepeatedandeditedas
requiredinordertojoinadditionaltablesbeyondthesethree.
Non-Equijoins
Sofar,allthejoinswe’veseenhavebeenequijoins.Inotherwords,thejoins
haveusedcolumnscontainingcommondatavaluesamongthejointablesand
havejoinedrowsinthetablesbasedonfindingequalvaluesinthejoincolumns.
Non-equijoinsrelateonerowtoanotherbywayofnon-equalcomparisons,
suchascomparisonsofgreaterorlesservalueorperhapscomparisonsthatlook
forarangeofvalues.Suchjoinsareunusualbutimportant.Andtheyarepartof
thecertificationexamcriteria.
Let’slookatanexample.SeeFigure8-3.
FIGURE8-3 TheSCORESandGRADINGtables
NotethatthesetablesdonothaveaFOREIGNKEYrelationship.Aswe’ve
alreadynoted,thatisnotrequiredtojointables.
Let’slookatsomedatainthesetables.First,here’sSCORES:
Next,GRADING:
TheideahereisthattheSCOREStablelistssomeactualscoresonexams,and
theGRADINGtablecontainsinformationaboutgradingcriteria.
IntheSCOREStable,wehavearowofdatashowingthatthetestidentified
withaSCORE_IDvalueof1receivedascoreof95.Accordingtothe
GRADINGtable,thatshouldbeagradeofA.
Let’screateaSELECTstatementthatjoinsthesetablestodetermineeachtest
score’sgrades.
Notethesyntaxofthisjoin.Online2wehaveatypicalJOINsyntax,butonline
3,insteadoftheequijoin,weconnectthetwotablesbycomparingthevaluein
theTEST_SCOREcolumnofSCORESandseewhetherit’sBETWEENthe
valuesfortheGRADINGtable’sSCORE_MINandSCORE_MAXcolumns.
Hereistheoutput:
Thisisanexampleofanon-equijoin.ThesyntaxoftheONconditionina
non-equijoinissimilartothesyntaxfortheWHEREclauseintheSELECT,in
thatyoucanusecomparisonexpressions,thegreater-thanorless-thanoperators,
SQLfunctions,andBooleanoperatorstoconnectaseriesofcomparisons.
CERTIFICATIONOBJECTIVE8.03
JoinaTabletoItselfbyUsingaSelf-Join
Aself-joinisatablethatisjoinedtoitself.Aself-joinisbasedonthevalueina
columnofatableasitcomparestothevalueswithinanothercolumn—oftena
differentcolumn—inthesametable.Theself-joinreturnsoneormorerows
fromatablethataremergedwithotherrowsinthesametablebasedonthejoin
criteria.
(Note:Syntacticallyyoucanjoinacolumntoitselfinthesametable,as
opposedtoadifferentcolumninthesametable.Itdoesn’tdomuchlogically,but
thesyntaxwillexecute.)
Self-joinscanuseallthesamevariationsonjoincriteriathatanyothertable
joincanuse.Inotherwords,self-joinscanbeinnerjoinsorouterjoins,equijoins
ornon-equijoins,andsoon.
Let’swriteaself-joiningSELECTstatement.Forstarters,seeFigure8-4.The
POSITIONStablelistsjobtitleswithinourCoddCruisesorganization.
FIGURE8-4 ThePOSITIONStable
Here’salistingofsomeofthecolumnsinthePOSITIONStable:
NotethecolumnREPORTS_TO.Itindicatesthat,forexample,CrewChief
reportstothepositionofPOSITION_ID2,whichisDirector.
Self-ReferencingForeignKeys
ThePOSITIONStableissupportedwithaforeignkeythatpointstoitself,which
iscreatedwiththisSQLstatement:
Notethataforeignkeyisadvisedbutnotrequiredinordertoperformthe
self-join.
Self-JoinSyntax
Nowthatwehaveourtable,ourdata,andouroptionalforeignkeyconstraint,
let’slookataquerythatwillconnectallofthistogether.Tocreatetheself-join,
weneedtodothefollowing:
IdentifythetabletwiceintheFROMclause.
Defineourjoincriteria—whichinthiscasewillbeanOUTERjoin
sothatwecanincludethehighest-levelpositionthatdoesn’thavea
REPORTS_TOvalue—andthereforeisn’t“matched”withanything.
Applyatablealiastoallappropriatereferences,beingcarefultojoin
theREPORTS_TOcolumninthefirsttablereferencetothe
POSITION_IDcolumninthesecondtablereference.
Here’sthequery:
Andhere’stheoutput:
Besureyouhaveasolidcommandofthejoinsyntaxforallformsof
joins.ThatshouldincludeNATURAL,USING,andthevariousinner
joinsandouterjoins.Allformsarefairgameontheexam.
Theresultisalistingofpositionsandthesupervisoreachreportsto.Allof
thisdataisfoundintheonetablePOSITIONS.YoucanseethatintheSELECT
statement’soutput,boththePOSITIONcolumnandtheBOSScolumncontain
datathatisfoundinthePOSITIONcolumnofthePOSITIONStable.Butthe
self-joinreturnsameaningfuloutputdisplaywithacolumnaliasonthesecond
referencetoPOSITION.
CERTIFICATIONOBJECTIVE8.04
ViewDataThatGenerallyDoesNotMeetaJoin
ConditionbyUsingOuterJoins
Anouterjoinisajointhatreturnsallthesamedataasaninnerjoinbutalso
returnsadditionalrows,namely,thoserowsthatdon’thavematchesinallthe
tablesthatarejoinedtogether.Therearethreetypesofouterjoins—LEFT,
RIGHT,andFULL.Eachisdescribedhere.
LEFTOUTERJOIN
Toseeonetypeofouterjoininaction,let’scontinuewithourexampleand
modifyourqueryjustalittletomakeitanouterjoin.
NoticetheadditionofthekeywordsLEFTOUTERinline2.Thefollowingare
therowsreturnedbythiscode:
BychangingourFROMclausefromaJOINtoaLEFTOUTERJOIN,we
havechangedthequeryfromaninnerjointoanouterjoin.(Rememberthat
JOINdefaultstoINNERJOIN.)Andnoticethatouroutputnowincludesdata
forSHIP_ID3.AlsonoticethattherowforSHIP_ID3showsnovaluefor
PORT_NAME,whichiscorrect—noHOME_PORT_IDvaluewasassignedto
it.
AlsonotethattheOUTERkeywordisoptional.Inotherwords,thisisjustas
good:
Inthisexample,OUTERisomitted,buttheeffectisthesame.
RIGHTOUTERJOIN
Butwestilldon’tseeourPORT_NAMEofMiami.So,let’schangeourquery
again.
Notethatwe’vereplacedthekeywordLEFTwiththekeywordRIGHTinline
2.Hereistheresult:
We’venowincludedtherowforMiami.ButwelostourrowwiththeCodd
Champion.That’sbecausethisRIGHTOUTERJOINreturnsunmatchedrows
fromtherightsideofthejoin,whichinthisexampleisthePORTStable(see
line2oftheSELECTstatement).ButwetookawayourLEFTOUTERJOINto
SHIPS.
Asbefore,OUTERisoptional.RIGHTJOINwilldothesamethingas
RIGHTOUTERJOIN.
FULLOUTERJOIN
IfwewanttocombinetheeffectsofaRIGHTOUTERJOINandLEFTOUTER
JOIN,wecanusetheFULLOUTERJOIN.
Line2showstheuseofthekeywordsFULLOUTERJOIN,andtheoutputisas
follows:
Andherewehaveallofourrows,mergedwherematched,butallreturned
regardless.Aswithallotherouterjointypes,thekeywordOUTERisoptional.
FortheRecord:OracleOuterJoinSyntax:(+)
TheLEFT,RIGHT,andFULLOUTERsyntaxusagesareANSIstandardand
featuredonOracle’sexam.Inaddition,OracleSQLoffersanalternativeouter
joinsyntaxthatemploysaplussignenclosedinparentheses.Thissyntaxisused
quiteabitandlongpredatestheANSIstandardsyntaxinOracleSQL;however,
theouterjoinplusoperatorisnotontheexam.
Let’slookatthesyntaxanyway.Ifyou’reaveteranOracleprofessional,you
mightthinkthisbookisincompletewithoutatleastamentionoftheouterjoin
plusoperator.Let’srestatetheearlierLEFTOUTERJOINexamplewiththeplus
operator.
Notethespecialcharactersattheendofline3.Theplussigninparentheses
definesthisqueryasaleftouterjoin.Itisaleftouterjoin,buttheplussigngoes
ontherightside;IthinkoftheplusoperatorasaddingfakeNULLrowsonthe
rightsidetoenabletheotherwiseunmatchedrowsonthelefttobeincludedin
thereturnedrowset.
Tocreatearightouterjoininthissyntax,yousimplymovetheplussignto
theleftside.
Youcan’treallydoafullouterjoinusingthissyntax,butyoucanusetheset
operatorUNIONtocombinealeftouterjoinandarightouterjointoachievethe
sameresult.
(Note:SetoperatorsareaddressedindetailinChapter11.)
So,that’stheplusoperator.ButitwasneverANSIstandard.Furthermore,
OracleCorporationformallyrecommendsthatyouavoidusingitfromnowon
andstickwiththekeywordsINNERJOIN,OUTERJOIN,andalltheother
relatedkeywords.Inspecialsituationstheplusoperatornowhassome
restrictionsandlimitationsthatdon’tpertaintotheINNERJOINandOUTER
JOINkeywords.
Butyouwon’tbetestedonit—you’llbetestedonthenewerLEFT,RIGHT,
andFULLOUTERJOINformats.
CERTIFICATIONSUMMARY
ThereareseveralwaystojointablesinSQL.Theinnerjoincomparescommon
valuesinrowsoftwoormoretablesandreturnsdatafromarowonlyifthatrow
hasamatchinthejoinedtable.Theouterjoinwillshowarowasoutputwhether
thatrowhasajoinedrowinanothertableornot.
Somejoinsareequijoins,whichmeansthattheyjoinrowsinonetablewith
rowsinanothertablebylookingforvaluesinbothrowsthatareequaltoeach
other.Non-equijoinslookforvaluesthathavesomerelationshipotherthan
equality,suchasgreaterthan,lessthan,orinbetweenarangeofvalues.
Primarykeyandforeignkeyrelationshipshelpprotecttheintegrityofdatain
columnsthatareintendedtojointables,buttheirpresenceisnotrequiredin
ordertocreateasuccessfuljoin.
Whentwoormoretablesarejoined,anyoftheircolumnsmaybeincludedin
theSELECTstatement’sselectlist.However,asyntaxerrormayresultifthetwo
tableshavecolumnsthatsharethesamename.Insuchsituations,thetablename
canbeplacedinfrontofthecolumnnameasaprefixtoeliminateanyambiguity.
Asanalternative,thetablecanbeassignedanaliasnamethatwilllastonlylong
enoughfortheSELECTstatementtoexecute.Thealiascanthenbeusedasa
prefixinfrontofanycolumnname,anditmayberequiredinfrontofthe
otherwiseambiguouscolumnnames.
Anaturaljoindoesnotspecifywhichcolumnsarebeingusedtoconnecttwo
ormoretablestogether,relyinginsteadontheassumptionthatthecolumnsto
formthejoinhavethesamenameaseachother.Naturaljoinsareinnerjoinsby
default.
TheUSINGkeywordcandosomethingsimilartotheNATURALkeyword.
USINGcannamethecommoncolumnonetime,andtheSELECTstatementwill
completethejoinbasedonthatcolumn,aswellaseliminatingtheneedfora
tableprefixoraliasinfrontofthekeycolumn.
Multitablejoinscanbeperformedwithanyjointype.
Non-equijoinsusecomparisonoperators,Booleanlogic,oranythingelseto
establishcomparisonlogicbetweentwoormoretablesinajoin.
Aself-joinoccurswhenatableisjoinedtoitself.Typicallyonecolumninthe
tableisjoinedtoadifferentcolumninthesametable.
✓TWO-MINUTEDRILL
DescribetheDifferentTypesofJoinsandTheirFeatures
Theinnerjoincomparesarowinonetabletorowsinanothertable
andreturnsthefirsttable’srowonlyifamatchingrowinthesecond
tableisfound.
Theouterjoincomparesarowinonetabletorowsinanothertable
andreturnsthefirsttable’srow,aswellasdatafrommatchingrowsin
thesecondtablewhereveramatchisfound.
Theequijoinidentifiesaparticularcolumninonetable’srows,
relatesthatcolumntoanothertable’srows,andlooksforequalvaluesin
ordertojoinpairsofrowstogether.
Thenon-equijoindiffersfromtheequijoininthatitdoesn’tlookfor
exactmatchesbutinsteadlooksforrelativematches:greaterthan,less
than,orarange,suchasonetable’svaluethatisbetweentwovaluesin
thesecondtable.
Theself-joinconnectsatabletoitself.
WriteSELECTStatementstoAccessDatafromMoreThanOne
TableUsingEquijoinsandNon-Equijoins
AjoinisanySELECTstatementthatselectsfromtwoormore
tables.
Ajoinwillconnectrowsinonetablewithrowsinanothertable.
ThetablealiasexistsonlyforthedurationoftheSQLstatementin
whichitisdeclared.
Tablealiasesarenecessarytoeliminateambiguityinreferringto
columnsofthesamenameinajoin.
Thenaturaljoindoesnotnametheconnectingcolumnbutassumes
thattwoormoretableshavecolumnswithidenticalnamesandthatthese
areintendedtobetheconnecting,orjoining,columns.
TheUSINGkeywordcanempoweraninner,outer,orotherjointo
connectbasedonasetofcommonlynamedcolumns,inmuchthesame
fashionasanaturaljoin.
Joinscanconnecttwo,three,ormoretables.
JoinaTabletoItselfbyUsingaSelf-Join
Theself-joinconnectsatabletoitself.
Self-joincriteriacomparesacolumninatablewiththesameor
anothercolumninthesametable.
Self-joinscanalsobereferredtoasrecursivejoins.
Self-joinscanbewrittenasequijoins,non-equijoins,innerjoins,
andouterjoins.
ViewDataThatGenerallyDoesNotMeetaJoinConditionby
UsingOuterJoins
Theouterjoincomparesrowsintwotablesandreturnsoutput
whetherthereisamatchingrowornot.
Theleftouterjoinshowsalltherowsinonetableandonlythe
matchingrowsinthesecond;therightouterjoindoesthesamethingin
reverse.
Thefullouterjoinshowsallrowsinbothtablesonewayorthe
other—eitherasamatchedrowsetorasastandalonerow.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseallthecorrectanswersforeach
question.
DescribetheDifferentTypesofJoinsandTheirFeatures
1.Aninnerjoinqueriesfromtwotables(lookingatvaluesincolumns
andoptionallyusingexpressionsthatreferencecolumns)andcomparesthe
resultingvaluesinonesetofrowswiththeresultingvaluesinanothersetof
rows,lookingfor:
A.Valuesthatmatch
B.Valuesthatmayormaynotmatch
C.Valuesinthefirstsetthataregreaterthanvaluesinthesecond
set
D.Valuesinthefirstsetthatarelessthanvaluesinthesecondset
2.WhichofthefollowingsymbolsismostlikelytobeusedinaSELECT
statementusinganon-equijoin?
A.!=
B.<>
C.<=
D.Noneoftheabove
3.Equijoinslookfor:
A.Exactdatamatches
B.Rangesofdatamatches
C.Comparisonsusinganycomparisonoperatorprovidedthatthe
resultingcorrelationsoccurinbothtables
D.Noneoftheabove
WriteSELECTStatementstoAccessDatafromMoreThanOne
TableUsingEquijoinsandNon-Equijoins
4.ReviewthisSQLstatement:
Whichoneofthefollowingkeywordsinthisstatementisoptional?
A.JOIN
B.INNER
C.ON
D.Allarerequired
5.ReviewtheINVOICESandVENDORStables.
NextreviewthefollowingSQLstatement:
WhichofthefollowingstatementsistruefortheSQLstatement?
A.Itwillexecutesuccessfully.
B.ItwillfailwithasyntaxerrorbecausethereisnoONclause.
C.Itwillfailwithasyntaxerroronline1becauseVENDOR_IDis
ambiguous.
D.Itwillfailwithasyntaxerroronline3becauseofthe
parenthesesaroundVENDOR_ID.
6.Reviewtheillustrationfromquestion5andthenreviewthefollowing
SQLstatement:
Whatkindofjoinisthis?(Choosetwo.)
A.INNER
B.OUTER
C.NATURAL
D.Equijoin
7.Atablealias:(Choosetwo.)
A.Renamesatableinthedatabasesothatfuturejoinscanusethe
newname.
B.Isthesamethingasadatabaseobjectsynonym.
C.ExistsonlyfortheSQLstatementthatdeclaredit.
D.Canbeusedtoclearupambiguityinthequery.
8.ReviewthePOSITIONS,EMPLOYEES,andPAY_HISTORYtables.
ReviewthefollowingSQLstatement:
WhichofthefollowingistruefortheSQLstatement?(Choosetwo.)
A.Itwillfailbecausetherearenotablealiases.
B.Itwillexecutesuccessfully.
C.Itisanouterjoin.
D.Itconnectsthreetables.
9.Reviewtheillustrationfromquestion8andthenreviewthefollowing
SQLstatement:
WhichofthefollowingstatementsaccuratelydescribetheSQL
statement?(Choosetwo.)
A.Itcontainsasyntaxerroronline3.
B.Itisaninnerjoin.
C.Itisanon-equijoin.
D.Itcontainsasyntaxerroronline2andshouldhaveanadditional
keywordwiththeJOINkeyword.
10.Howmanytablescanbejoinedinaquery?
A.Onlytwo
B.Asmanyasyoulike,providedtheyareallconstrainedwith
PRIMARYKEYandFOREIGNKEYconstraintstoensurethatthe
joinconditionwillwork
C.One,two,three,ormore
D.Nomorethanseven
11.Youhavetwotables.OnetableiscalledCUSTOMERS.Anotheriscalled
PURCHASES,anditrecordsalistofcustomertransactions.Yourgoalisto
createaSELECTstatementthatwillshowallcustomersbylastnamein
alphabeticalorder,alongwithanypurchasestheymayhavemadeinthe
pasttwoweeks,asrecordedinthePURCHASEStable.It’spossiblethat
manycustomershavemadenopurchasesinthepasttwoweeks,butyou
stillwantthemincludedintheoutput.Bothtablescontainacolumncalled
CUSTOMER_ID.WhichofthefollowingwillbetrueoftheSELECT
statementyou’llneedtocreate?(Choosetwo.)
A.Itwillbeaninnerjoin.
B.Itwillbeanouterjoin.
C.Itwillbeacross-join.
D.Itwillbeanequijoin.
JoinaTabletoItselfbyUsingaSelf-Join
12.Aself-joinis:(Choosetwo.)
A.ASELECTstatementthatspecifiesonetableonceintheFROM
clause
B.ASELECTstatementthatspecifiesonetabletwiceintheFROM
clause
C.ASELECTstatementthatjoinsatabletoitselfbyconnectinga
columninthetabletoadifferentcolumninthesametable
D.ASELECTstatementthatusestheSELFJOINkeywords
13.Reviewtheillustrationfromquestion8.Whichofthefollowingisavalid
self-joinstatement?(Chooseallthatapply.)
ViewDataThatGenerallyDoesNotMeetaJoinConditionby
UsingOuterJoins
14.Reviewtheillustrationfromquestion5.Whichofthefollowingisa
syntacticallycorrectouterjoinquery?(Choosetwo.)
15.ThedifferencebetweenanINNERandanOUTERjoinis:
A.TheINNERjoinrelatesatabletoitself;theOUTERjoinrelates
atabletoothertables.
B.TheINNERjoindisplaysrowsthatmatchinalljoinedtables;
theOUTERjoinshowsdatathatdoesn’tnecessarilymatch.
C.TheOUTERjoinrelatesatabletotablesinotheruseraccounts;
theINNERdoesnot.
D.TheINNERrunsondatainsidethetable;theOUTERrunson
dataoutsideofthetable.
SELFTESTANSWERS
DescribetheDifferentTypesofJoinsandTheirFeatures
1. A.Aninnerjoinlooksforvaluesthatmatch.
B,C,andDareincorrect.Aninnerjoinignoresrowswherevaluesdon’t
match;anouterjoinmayreturnsomeofthoserows.Anon-equijoinmay
leveragematchesdefinedbygreater-thanorless-thancomparisonoperators.
2. C.Thenon-equijoinperformscomparisonsusingrelationshipsthat
don’tinvolveequalitybutwherethereisstillsomesortofmatchingcriteria,
suchaslessthan,greaterthan,orvalueswithinarange.
A,B,andDareincorrect.Thenot-equalsigns!=and<>arenotwhatis
intendedwithanon-equijoin.Remember,thesearenot“not-equal”joins
butrather“non-equijoins.”
3. A.Equijoinslookforexactdatamatches.
B,C,andDareincorrect.Non-equijoinsuserangesofmatches.
Equijoinsdon’tuseanycomparisonoperator;theyuseonlyequalsigns.
WriteSELECTStatementstoAccessDatafromMoreThanOne
TableUsingEquijoinsandNon-equijoins
4. B.INNERisoptional.WhencreatinganINNERJOIN,youcanjust
usethetermJOINwithoutthereservedwordINNER,andthejoinwillbe
assumedtobeINNER.
A,C,andDareincorrect.JOINisrequired.SoisON.
5. A.Itwillexecutesuccessfully.
B,C,andDareincorrect.EventhoughthisisaJOIN,thepresenceof
USINGeliminatestheneedforanONclause.WithUSING,atablealiasis
notrequired,norisoneallowedintheselectlist.Theparenthesesaround
VENDOR_IDonline3arefine.
6. AandD.TheINNERkeywordisoptional,butthatiswhatthisisby
default.It’salsoanequijoin,inthatthetwotablesarejoinedbydefining
valuesthatmatchequallyintheVENDOR_IDcolumn—thisisspecifiedby
useoftheUSINGclauseonline3,whichisequivalenttoON
VENDORS.VENDOR_ID=INVOICES.VENDOR_ID.
BandCareincorrect.ItisnotanOUTERjoin;ifitwere,theOUTER
keywordmustbespecified.ItisnotaNATURALjoinforthesamereason
—ifitwere,theNATURALkeywordmustbespecified.
7. CandD.Thetablealiasgoesawayafterthequeryisover.Itcanbe
usedtoclearupconfusioninthesyntaxofastatementbyaddingitasa
prefixatthebeginningofanycolumnthatsharesthesamenamewith
anothercolumninajoinedtable.
AandBareincorrect.Thetablealiasisnotthesameasadatabaseobject
synonym.ThetablealiassurvivesonlywithintheSQLstatementthatcalls
it;afterthat,itgoesaway.
8. BandD.Itwillexecutesuccessfully,anditconnectsthreetables.
AandCareincorrect.Itdoesnotrequiretablealiases.Itisaninnerjoin,
notanouterjoin.
9. BandC.Thequeryisaninnerjoin.ThekeywordINNERis
optionalandomittedinthisinstance.Thequeryisanon-equijoin,wherein
theONconditioncomparesthePAY_HISTORYtable’sSALARYcolumn
ofvaluestotheMAX_SALARYandMIN_SALARYofthePOSITIONS
table.
AandDareincorrect.Thestatementcontainsnosyntaxerrors.
10. C.Youcanjoinasmanytablesasyouwant.Rememberthatjoiningone
tabletoitselfisaself-join.
A,B,andDareincorrect.Youarenotlimitedtotwotables,norareyou
requiredtoonlyjointablesthathaveconstraintsonthem.Youarenot
limitedtoseventables.
11. BandD.TheSELECTmustbeanouterjointoincludeallrecordsinthe
CUSTOMERStablewhetherornottheyhaveacorrespondingrowinthe
PURCHASEStableinthelasttwoweeks.Also,sincebothtablescontaina
CUSTOMER_ID,you’lluseanequijointolocateexactmatchesbetween
thetwotables.
AandCareincorrect.Thequerycannotbeaninnerjoin,becauseifit
were,itwouldonlyshowcustomerswhohavemadepurchasesinthepast
twoweeks.Itcannotbeacross-join,whichisaCartesianproduct,because
allthatwoulddoisconnecteverycustomerwitheverypurchasewithout
anyregardforwhetherthecustomeractuallymadethepurchaseor
someoneelsedid.
JoinaTabletoItselfbyUsingaSelf-Join
12. BandC.Inaself-join,thetablenameisrepeatedtwiceintheFROM
clause,andperhapsmorethantwice.Aself-joinismostcommonlyusedto
joinacolumninatabletoadifferentcolumnwithinthesametable.
AandDareincorrect.Theself-joinsyntaxnamesthesamenametwice
—ormore—intheFROMclause.ThereisnosyntaxinOracleSQL
involvingthekeywordsSELFJOIN.
13. A,C,andD.AllofthesearevalidSQLstatements.Thefirstisatypical
innerjoin.CspellsouttheoptionalwordINNERforthesameresultasA.
Ddefinesavalidouterjoinandisalsoaself-join.
Bisincorrect.ThereisnokeywordSELF,asinSELFJOIN.
ViewDataThatGenerallyDoesNotMeetaJoinConditionby
UsingOuterJoins
14. AandC.TheLEFTJOIN...ONsyntaxiscorrect.SoistheRIGHT
OUTERJOIN...ONsyntax.RememberthatthekeywordOUTERis
optional.
BandDareincorrect.TheOUTER...ONsyntaxisincorrect;thereis
noOUTERbyitself.TheFULLOUTER...ONsyntaxisalsoincorrect.
InneitheroftheseistherequiredkeywordJOINpresent.
15. B.INNERshowsdataonlywhenthere’sarow-to-rowmatchbetween
tables,whereasOUTERcanshowdataforrowsinonetablethatdon’t
matchtherowsinthejoinedtable.
A,C,andDareincorrect.Adescribesajointhat“relatesatableto
itself.”Thatisaself-join,notaninnerjoin.Thefactthatatablemayor
maynotexistinotheruseraccountsisirrelevant;youcanjointables
whetherornottheyareinthesameuseraccount.OUTERdoesnotrunon
dataoutsideofthetable;alljoinsreferencedatawithineachoftheir
respectivereferencedtables.
9
T
UsingSubqueriestoSolveQueries
CERTIFICATIONOBJECTIVES
9.01DefineSubqueries
9.02DescribetheTypesofProblemsSubqueriesCanSolve
9.03DescribetheTypesofSubqueries
9.04QueryDataUsingCorrelatedSubqueries
9.05UpdateandDeleteRowsUsingCorrelatedSubqueries
9.06UsetheEXISTSandNOTEXISTSOperators
9.07UsetheWITHClause
9.08WriteSingle-RowandMultiple-RowSubqueries
✓Two-MinuteDrill
Q&ASelfTest
hischapterlooksatsubqueries.AsubqueryisaSELECTstatementwithina
largerSQLstatement.Thesubqueryconceptbuildsonmanyofthefeatures
we’vealreadylookedatandcombinestheminawaythatmakesSQLquite
powerful.However,subqueriesintroducesomecomplexitiesthatareimportant
tomaster.Theyareanimportantpartofthecertificationexam.
CERTIFICATIONOBJECTIVE9.01
DefineSubqueries
Asyou’vealreadyseen,aqueryisaSELECTstatement.Asubqueryisa
SELECTstatementthatexistswithinanotherSQLstatement—sortofa“sub”
SQLstatement.SQLstatementsthatacceptsubqueriesincludeSELECT,
INSERT,UPDATE,MERGE,andDELETE.SubqueriesarenotlimitedtoDML;
theycanalsobeusedinaCREATETABLEorCREATEVIEWstatement.
Mostsubqueriesaresyntacticallyautonomous,meaningyoucouldexecute
thesubquerysuccessfullyonitsown,separatefromtheparentquery.However,
somesubqueriesarenotstandalonequeriesbutinsteadarecorrelatedtothe
largerparentqueryinawaythattiesthetwoqueriestogether.
Asubquerymayreturnoneormorecolumnsinoneormorerows.One
commonuseofasubqueryistoreturndatathatisofusetotheparentquery,
suchascriteriawithinaWHEREclause,forexample.ASQLstatementthat
includesasubqueryaspartofitscodeisconsideredtheparenttothesubquery.
AparentSQLstatementmayincludeoneormoresubqueriesinitssyntax.
Subqueriesmayhavetheirownsubqueries.Inotherwords,aSQLstatement
mayhaveasubquery,whichinturnmayhaveanothersubquerywithinit,andon
andon.ThestartingSQLstatementinsuchasituationisthetop-levelquery,and
anysubsequentsubquerythatcontainsasubquerywithinitisaparenttoits
subquery.Aparentquerymayalsobereferredtoasanouterquery.
AnyvalidSELECTstatementcanqualifyasasubqueryofanotherstatement.
SELECTstatementsthatcanbemadeintoasubqueryincludethosethatretrieve
datafromoneormoretablesorviews;thosethatusecomplexexpressionsor
scalaroraggregatefunctions;andthosethatincludetheWHEREandGROUP
BYclauses,HAVINGclauses,joins,oranyoftheotherfeaturesavailableto
SELECTstatements.
Asubqueryisnotrestrictedtoretrievingdatafromthesametableortablesas
theparentquery.Infact,subqueriesoftenretrievedatafromtablesotherthan
thosespecifiedintheparentquery.Thetablesofthesubqueryarenotrequiredto
haveanykeyrelationshiporjoinorotherlogicalrelationshiptothetablesofthe
parentquery.Sucharelationshipmayexistbetweentheparentandthesubquery
—butitisnotrequired.
Subqueriescanbeusedtosolveavarietyofproblems.
CreatingcomplexmultistagequeriesSubqueriescanfindanswers
toquestionsandthenusethoseanswerstoasknewquestions.Inother
words,inasingleSELECTstatement’sWHEREclause,asubquerycan
finddatabasedonsomecriteria,thenusethatanswertoidentifya
secondaryanswer,andfinallypassthatanswerontotheparentquery,all
inthesameSQLstatement.Thiscanberepeatedwithinmultiplestages
inwaysthatastandaloneparentquerycannotdowithouttheuseofa
subquery.
CreatingpopulatedtablesAsubquerycanbeincorporatedintoa
CREATETABLEstatementtoquicklycreateandpopulateatablefrom
anexistingdatasourceatthetimethetableiscreated.
ManipulatinglargedatasetsSubqueriescanbeincorporatedinto
anINSERTorUPDATEstatementtomovelargeamountsofdataand
insertorupdatemanyrowsofinformationbymovingdatafromone
sourceintoanotherinasingleSQLstatement.
CreatingnamedviewsAsubqueryisusedtocreateviewobjectsat
thetimeofcreation.
DefiningdynamicviewsAsubquerycanbeusedtoreplaceatable
referenceinaFROMclause.Thisformofsubquery,alsoknownasan
inlineview,isdiscussedinChapter10.
DefiningdynamicexpressionswithscalarsubqueriesThereisa
formofsubquerythatwillreturnonlyonecolumn’sworthofdatainone
row;thatis,itwillreturnasinglevalue.Suchasubquerycanbeusedin
almostanyplaceinaSQLstatementwhereanexpressioncanbeused.
Asyoucansee,subqueriesarepowerful,candoawidevarietyoftasks,and
canoccurinalmostanySQLstatementinalmostanyclause.Thischapterwill
exploremanyexamplesoftheseusagesofsubqueries.
CERTIFICATIONOBJECTIVE9.02
DescribetheTypesofProblemsSubqueriesCanSolve
Subqueriesareanidealsolutiontoseveralcommondatachallenges.Sometimes
asubqueryistheonlysolution.Subqueriesareidealforfindingdatathatisatthe
topofsomescale,isaboveaverage,isbelowaverage,orsomethingcomparable.
Youmightfirstuseaquerythatinvolvesanaggregatefunctionandthenusethe
resultofthatquerytofindrecordsthatcorrelatetotheresult.
Let’slookatanexamplewithsomecode.ConsideratableSALES_DATA.
Let’saddrecordstothetableforsalesrepresentativesshowingsalesbyyear
fortheyears2016through2018.
Youaretaskedwithlistinganyandallsalesrepswhosesalesfor2016
surpassedthesalesteam’saveragesalesfortheprioryearof2017.
Onewaytodothisistofirstgettheaveragesalesfor2017.
Next,usetheresultstolookforsalesrepsin2018whosoldatahigherlevel.
That’sonewaytogettheanswer.Butasubquerywouldhavefoundthe
answerinasinglequery.
Youcanusesubqueriesformanypurposes.
Topopulateatableusingzerotomoresourcerowswithinan
INSERTstatementordovirtuallythesamethingwithinaCREATE
TABLEstatement.
TocreateaVIEW.
TospecifyvaluesassignedtoanUPDATEstatement.
Toperformcomparisonsagainstaggregatedresults.
Tocreateinlineviews:asubqueryinaFROMclauseofaSELECT
statement.Thereisnolimittohowmanysubqueriesdeepyoucango
withinaninlineview;youcanhavesubqueriesofsubqueriesof
subqueriesinthiscontext.
Asanalternativetoexpressions.
Tonestotherqueries.AsubqueryintheWHEREclauseofa
SELECTstatementisknownasanestedsubquerybecauseitisnested
withinthelargerquery(theSELECTstatementitself).Youcannestupto
255subqueriesinthisway.
TohaveacorrelatedsubquerywithinaSELECT,UPDATE,or
DELETE.
Theremainderofthischapterwillexploretheseandotherexamplesof
subqueries.
CERTIFICATIONOBJECTIVE9.03
DescribetheTypesofSubqueries
Therearemanytypesofsubqueries.Herearethemajortypes:
Single-rowsubqueriesAsingle-rowsubqueryreturnsasinglerow’s
worthofdatainitsresult.Single-rowsubqueriesmayincludemultiple
columns’worthofdataorasinglecolumn’sworthofdata.
Multiple-rowsubqueriesAmultiple-rowsubqueryreturnszero,
one,ormorerowsinitsresult.Itisnotguaranteedtoreturnmultiple
rows,butitmaydoso,andthustheparentqueryshouldbestructuredto
receivemultiplerowsjustincaseinordertoavoidthepossibilityofan
executionerror.Forexample,aparentquerymayuseanequalsignto
compareitsownreturnvalueswiththereturnedvaluesofasubquery.An
equalsignperformsacomparisontoasinglevalue,sointhecaseofthe
subquery,onlyonerowshouldbereturned.Butifthesubqueryreturns
multiplerows,theparentquery(andthereforethequeryasawhole)will
failwithanexecutionerror—itdependsonwhetherthesubqueryactually
returnsmultiplerows.Itmightnot,butitcertainlycanatanytime.
Therefore,theparentquerytoamultirowsubquerytypicallyusesa
comparisonoperator(suchasIN)thatallowsformultiplerowsofvalues
tobereturned.
Multiple-columnsubqueriesMultiple-columnsubqueriesreturn
morethanonecolumnintheirresult.Thisrequirestheparentqueryto
receivemultiplecolumnsfromthesubqueryandinvolvesspecialsyntax
considerations,aswejustdiscussed.Amultiple-columnsubquerycanbe
eitherasingle-rowsubqueryoramultiple-rowsubquery.
CorrelatedsubqueriesAcorrelatedsubqueryisasubquerythat
specifiescolumnsthatbelongtotablesthatarealsoreferencedbythe
parentquery.Inamultilevelseriesofsubqueries,subquerieswithin
subqueries,andsoon,thecorrelatedparentquerycanbeanynumberof
levelshigherthanthesubquery.Thecorrelationinvolvesmorethanthe
subquerymerelyaccessingthesametablesandcolumnsthroughitsown
directcalltothetable;rather,thecorrelatedsubqueryperformsrow-by-
rowanalysisincooperationwiththeparentquery,accessingdataand
referencingthatdatainitsownexpressionsinordertocoordinaterow
processingwiththecorrelatedparent.Correlatedsubqueriescanexistin
SELECT,UPDATE,andDELETEstatements.Acorrelatedsubquery
mayalsobeasingle-row,multiple-row,ormultiple-columnsubquery.
ScalarsubqueriesIfasingle-rowsubqueryconsistsofonlyone
column’sworthofoutput,thenitisknownasascalarsubquery.Scalar
subqueriescanbeusedinalmostanylocationthatanexpressioncanbe
used,whichisnottrueforotherformsofsubqueries.Ascalarsubquery
canalsobecorrelated.
Notethatthedifferenttypesofsubqueriesaren’tmutuallyexclusive.A
singletypeofsubquerymayfallintomultiplecategoriesofsubqueries
describedinthischapter.
Asyoucansee,therearemanytypesofsubqueries.Let’sbeginlookingat
themindetail.
CERTIFICATIONOBJECTIVE9.04
QueryDataUsingCorrelatedSubqueries
Acorrelatedsubqueryisaquerythatisintegratedwithaparentquery.
Correlatedsubqueriesincludereferencestoelementsofaparentquery,andthus,
theydonotexistasstand-alonequeriesliketheexamplesyou’veseensofar.Up
tonow,anyofthesubqueriesyou’veseencouldhavebeenexecutedontheir
own.That’snotthecasewithcorrelatedsubqueries.
Let’stakealookatanexampleusingtheSHIP_CABINStable.InChapter7,
yousawtheSHIP_CABINStableinFigure7-2,alongwithadatalisting
showingthe12rowsofinformationinoursampletable.Eachrowin
SHIP_CABINSshowsthatacabinisofROOM_STYLESuiteorStateroom.
Eachindividualroom’svalueforSQ_FTisshown,andthevaluesarenotallthe
same.
Ourcurrentchallengeistocreateasinglequerythatlistsallthecabinsinthe
shipwhosesize—asmeasuredbytheSQ_FTcolumn—islargerthantheaverage
cabinforitsROOM_STYLE.
Inotherwords,weneedto
IdentifytheaveragesquarefootageforeachROOM_STYLEin
SHIP_CABINS
Useaveragesquarefootagevaluetodisplayeachshipcabinwhose
SQ_FTisgreaterthantheaverageforitsROOM_STYLE
Withoutacorrelatedsubquery,we’dberequiredtocreateseparatequeriesto
getthisinformation.Wewouldneedthefollowing:
Onequerytogettheaverages
Anotherquery—orqueries—tocomparetheindividualaveragesfor
eachROOM_STYLE
Butwithacorrelatedsubquery,wecandoitallatonce.Here’stheSQL(line
numbersadded):
Notethesubquerythatstartsonline3andcontinuesthrough(andincludes)line
5.Inparticular,notethesecondROOM_STYLEattheendofline5.Seethe
tablealiasofA?Thatisareferencetoacolumnoftheparentquery—notthe
subquery.Seeline2toconfirmthattheparentquery’stableisaliasedwiththeA
prefix.
Thisisthecorrelationinthiscorrelatedsubquery.Thisqueryisnotexecuting
asastand-alonequeryandthenpassingbackitsresultlikenoncorrelated
subqueriesdo.Instead,thecorrelatedsubqueryisexecutingonceforeachvalue
thattheparentqueryfindsforeachrow,passingthevalueforthe
ROOM_STYLEcolumnintothesubquery,anddeterminingtheaveragesquare
footageforthatparticularROOM_STYLE.Finally,itusestheresultofthat
queryinline3todeterminewhethertherowintheparentqueryisgreaterthan
theaverageofSQ_FTfortheROOM_TYPEornot.
Here’stheoutput:
Onewaytovalidatetheseresultswouldbetogetalistofeach
ROOM_STYLEanditsaveragevalueforSQ_FT.Here’saquerytocalculate
thatinformation:
ThisoutputconfirmstheaverageSQ_FTforeachROOM_STYLE,whichis
informationwecouldusetogobackandconfirmthatourcorrelatedsubquery
displayedonlythoseroomnumberswhoseindividualSQ_FTvaluesarehigher
thantheaveragefortheappropriateROOM_STYLE.Andtheyare.
CorrelatedsubqueriescanexistinSELECT,UPDATE,andDELETE
statements.Theyare“correlated”bywayofacolumnreferencefromtheparent
querywithinthesubquery.
Atablealiasisnotnecessarilyrequiredinthesubqueryifnocolumnname
conflictexists.Inourexample,therewassuchaconflict,sowewererequiredto
useatablealias.Butthat’snotnecessarilyrequiredinanycorrelatedsubquery.
Wecouldhavejustreferencedanycolumnfromtheparentquery,andaslongas
thereisn’tanidenticallynamedcolumninthesubquery,notablealiasis
required.
It’simportanttonotethatcorrelatedsubqueriesmayintroduceperformance
degradationintoaquery.Theprocessofcorrelatingrowsfromoneormore
subquerieswiththeouter,orparent,queryorqueriesmayconsumeasignificant
amountofprocessingtime.However,sometimesacorrelatedsubquerycan
accomplishtasksthatnootherformofquerymayaccomplish.
CERTIFICATIONOBJECTIVE9.05
UpdateandDeleteRowsUsingCorrelatedSubqueries
Let’slookattheuseofcorrelatedsubqueriesinanUPDATEstatementanda
DELETEstatement.
UPDATEwithaCorrelatedSubquery
AnUPDATEstatementcanhaveacorrelatedsubqueryintheseplaces:
IntheSETclause
IntheWHEREclause
Aswesawinanearliersection,thecorrelatedsubquerywillrequiresome
waytoidentifyanexpressionasbeingfromtheparentquery.Themostcommon
waytodothisistoassignatablealiastothetablenameintheUPDATEand
thenusethatsametablealiaswithinthecorrelatedsubquery.
Let’slookatanexample.First,reviewtheINVOICEStableshowninFigure
9-1.
FIGURE9-1 TheINVOICEStable
Ourtaskistogobacktoourhistoricalinvoicesandgivea10percent
discounttowhomeverplacedoursinglebiggestorderfortheirrespective
quarter.Sointhefirstquarter,weneedtofindthesinglebiggestinvoiceand
determinea10percentdiscountonthatinvoice,thendothesamethingforthe
secondquarter,andsoon.
Toaccomplishthisfeat,we’llneedtomodifytheinvoicesothatwechange
thevalueintheINVOICEStable’sTERMS_OF_DISCOUNTcolumntothe
string'10PCT'—andonlyfortheappropriateinvoicerecord.Andwe’llneedto
dothefollowing:
IdentifytherowwiththehighestvalueforTOTAL_PRICEforany
givenquarter,whichwecanidentifyusingtheTO_CHARformatmask
QontheORDER_DATEcolumn
UpdateaninvoiceonlyifithasthehighestTOTAL_PRICEforthe
quarter
Here’sanUPDATEstatementthatdoesthetrick:
Noticethefollowingitemsintheprecedingquery:
WechoosetocreateatablealiascalledINV,whichisdeclaredatthe
endofline1andreferencedinline6.
Thesubquerystartsinline3andrunsthroughline6.
Thecorrelationoccursinlines5and6,wherethesubquery’s
referencetoINVOICE_DATEiscomparedtotheparentquery’s
INV.INVOICE_DATE.Thecomparisonisperformedbyconvertingboth
datestothe'RRRR-Q'format,whichmeanstheyearandquartersothat,
forexample,thedate'31-MAY-17'wouldconvertto'2017-2'.
Online3isthecomparisonbetweentheparentqueryandthe
subquery,whichisanequalsign,indicatingthattheparentqueryis
expectingasingle-rowsubquery.Giventhatthesubqueryisreturningthe
aggregatevalueMAXforTOTAL_PRICEandnoGROUPBYis
involvedinthesubquery,thenthesubquerywillindeedreturnnomore
thanonerow.
HereisanexampleofacorrelatedsubqueryusedintheSETclauseofan
UPDATEstatement:
Intheprecedingcode,wedothefollowing:
Lines5through7WelookforrecordsinthePORTStablethatany
shipcallsitshomeport,bywayoftheHOME_PORT_IDcolumn.We
usethekeywordEXISTS,whichwewillreviewlaterinthischapter.
EXISTStellsusquitesimplywhetherthereareanyrowsreturnedbythe
subqueryatall.Inotherwords,we’resimplyaskingwhetherthereare
anyrowsinSHIPSthatcontainavalueforHOME_PORT_IDthat
correspondstoagivenrowintheparentUPDATEstatement’sPORTS
table.Ifyes,thesubqueryreturnsaTRUE.
Lines2through4Then,ifwefindsuchPORTS,weupdatetheir
capacitytoequalthetotalnumberofshipsintheSHIPStablecurrently
callingthatporthome;thisisaccomplishedinthecorrelatedsubquery
thatcountsthenumberofrecordsinSHIPSthatsharethesame
HOME_PORT_IDvaluewiththeparentUPDATE.
NotethatthisexampleofanUPDATEusestwocorrelatedsubqueries;bothof
thesubqueriesarecorrelatedbecausebothincludetheP.PORT_IDreferencein
theirWHEREclauses,onlines4and7.
NotethatasubqueryoftheformSELECTCOUNT(*)FROMTABLEwill
alwaysbeasingle-rowsubquery.Ifnorowsarefound,thesubqueryreturnsa
singlerowwithavalueofzero.Ifmultiplerowsexistinthetable,thesubquery
returnsasinglerowwithavaluerepresentingthenumberofrowsfound.This
istrueforqueriesusingtheCOUNTfunctionbutnotforqueriesusingother
aggregates,suchasAVG,MIN,MAX,orSUM.ThisisuniquetoCOUNT.
Nextwe’lllookathowtousecorrelatedsubqueriesinaDELETEstatement.
DELETEwithaCorrelatedSubquery
TheDELETEstatementcanbeusedwithacorrelatedsubqueryintheWHERE
clausetodeterminewhichrowstodeletefromagiventable.Thesyntaxis
similartothecorrelatedsubquerysyntaxforSELECTandUPDATEstatements.
CorrelatedsubqueriesarenotlimitedtotheSELECTstatement.They
canalsobeusedinUPDATEorDELETEstatements.
Let’stakealookataDELETEstatementfortheSHIP_CABINStable.This
DELETEwillremovethosecabinswiththesmallestbalconysquarefootagefor
eachROOM_TYPEandROOM_STYLE.Inotherwords,foragiven
ROOM_TYPEofSuiteandaROOM_STYLEofOceanView,we’llremovethe
rowforthecabinwiththesmallestbalcony,andthenwe’llmoveonanddothe
samefortheStateroomwithOceanViewthathasthesmallestbalcony,andso
on.Here’sthequery:
Noticethatinthisexample,thecorrelationinvolvestwocolumns,inlines5
and6.
CERTIFICATIONOBJECTIVE9.06
UsetheEXISTSandNOTEXISTSOperators
TheEXISTSkeywordtestsfortheexistenceofanyrowsinasubquery.Ifno
rowsarefound,theanswerisFALSE.Otherwise,thesubqueryreturnsTRUE.
NOTEXISTSreversestheresults.
Let’slookatanexample.ThefollowingquerylooksforPORTSthathaveany
sortofrecordatallintheSHIPStablewithaHOME_PORT_IDvaluethat
matchesanyofthePORT_IDvalues.Here’sthequery:
EXISTSdoesnotcompareanythingtothesubquery.Thereisno
“expressionequalsexpression”formatwithEXISTS.Itssyntaxis
simple:thekeywordsWHEREEXISTSandthesubquery.Nothingmore.
NotethekeywordEXISTSonline3.Theentiresubqueryisexecuted,even
thoughEXISTSneedonlyknowwhetherthesubqueryreturnsanyrows,so
bewareusingEXISTSwithsubqueriesthatreturnlargenumbersofrows.
It’sworthnotingthatthissortofqueryissometimesreferredtoasasemijoin,
whichisaSELECTstatementthatusestheEXISTSkeywordtocomparerows
inatablewithrowsinanothertable.
CERTIFICATIONOBJECTIVE9.07
UsetheWITHClause
YoucanusethekeywordWITHtoassignanametoasubqueryblock.Oncethe
nameisassigned,youcanreferencethenamefromelsewhereinthequery.
WITHisconsideredaclauseoftheSELECTstatement.
Let’slookatanexample.We’lluseWITHtodeclaretwodifferent
subqueries.We’llnameonePORT_BOOKINGSandtheother
DENSEST_PORT(seethefollowinglisting,lines2and8)andtheninvokeboth
ofthembynameinaSELECTstatement(lines12through14).Here’sthecode:
Theseriesofoneormoresubqueryblocksdefinedbeforethe
SELECTstatementisreferredtoasthesubqueryfactoringclause.WITH
candefineonesubqueryfactoringclause;itmustbedefinedbeforethe
SELECTstatement.
NotethatneitherPORT_BOOKINGSnorDENSEST_PORTisadatabase
object.Theyarethenamesofqueriesthatexistsolelywithinthis
WITH/SELECTstatement.
Alsonotethesubqueriesonlines3through6andonlines9through10.Also
notethattheonlysemicolonisattheendoftheentirestatement,notattheend
ofanyindividualSQLstatementwithintheoverallWITHstatement.
Internally,OracleSQLtreatsanamedquerywithintheWITHclauseasa
temporarytableorasaninlineview.(WeexaminedinlineviewsinChapter8.)
TheWITHclausecanbeusedinthetop-levelqueryofaSELECTstatement
andinmany(butnotall)subqueriesoftheSELECTstatement,suchasshownin
line14.IfyouuseWITHtonameasubquery,thatnameisn’trecognizedwithin
thesubqueryitselfbutisrecognizedinmosteveryotherlocationintheoverall
query.Inotherwords,considerline8,wherewenameandspecifythesubquery
DENSEST_PORT.Wecouldn’treferencethenameDENSEST_PORTinlines9
through10,butwecanreferencethenameeverywhereelse.
CERTIFICATIONOBJECTIVE9.08
WriteSingle-RowandMultiple-RowSubqueries
Inthissection,we’llcreatesubqueriesthatreturnoneexpressionineithera
single-rowormultiple-rowanswer.
Single-RowSubqueries
Asingle-rowsubqueryisasubquerythatreturnsonerow.Forexample,let’ssay
you’retaskedwiththejobofidentifyingthenamesofemployeesofourfictional
company,CoddCruiseLines.You’retaskedtolookforemployeeswhoare
assignedtothesameshipasanemployeenamedAlSmith.SeeFigure9-2for
theentity-relationshipdiagram(ERD)ofthetablewe’llworkwith.
FIGURE9-2 TheEMPLOYEEStable
Youcouldperformthistaskintwosteps.Step1istofindtheSHIP_IDvalue
oftheshiponwhichAlSmithisassigned,likethis:
Step2istousetheSHIP_IDvaluetolocateotheremployeesonthesame
ship.
There’sananswer—intwosteps.Notbad.
Butasubquerycouldhavediscoveredtheanswerinonestep,likethis:
Thisonequeryachievesthesamethingastheprevioustwoqueries.Notewhat
we’vedonehere—we’veeditedthesecondoftheprevioustwoqueriesby
replacingSHIP_ID=1withSHIP_ID=andthesubqueryonlines3through6.
We’veliterallyplacedthefirstoftheprevioustwoquerieswithinthesecondof
thosetwoqueries.
Thereisaninherentriskwiththisparticularsyntax.Noticetheequalsignon
line3.That’stheparentquery’swayofsayingthatitisexpectingone—andonly
one—rowfromthesubquery.Inotherwords,itisexpectingthisquerytobea
single-rowsubquery.
Here’stheproblem:whathappensifthatsubqueryreturnsmorethanone
row?WhatifthereismorethanoneAlSmithintheEMPLOYEEStable?
Let’sfindout—let’strysearchingforemployeeswhoworkonthesameship
asanyonewhoselastnameisSmith,regardlessoffirstname.
Noticethetextoftheerrormessage:“single-rowsubqueryreturnsmorethan
onerow.”Inotherwords,weapparentlydohavemorethanonepersoninthe
EMPLOYEEStablewithalastnameofSmith.
Thiscreatesaproblem.Ourqueryhasanequalsignonline3,andthat’swhy
oursubqueryisexpectedtobeasingle-rowquery.
Thereareafewalternativeswecouldtakehere.Ifwewanttoretainthe
integrityofthesingle-rowsubquery,thenweneedtoeditthatsubquerytoensure
thatitwillreturnone,andonlyone,row.
Therearemanywaystoguaranteeaone-rowresponse.Forexample,a
subquerythatusesaWHEREcriterionbasedonaprimarykeyorsomeother
uniquevaluewillreturnonlyonevalue,likethis:
Ofcourse,thatassumesyouknowthevaluefortheappropriate
EMPLOYEE_ID.
Anotherexamplewouldbeasubquerythatreturnsanaggregatefunction
withoutaGROUPBYclause,likethis:
Aggregatefunctionsalwaysreturnasinglerow,aslongasnoGROUPBYis
involved.Logically,though,thisisn’talwaysanoptiontosolvetheparticular
businesschallengeyoumightbefacing.
StillanotherexamplewouldbeasubquerythatusestheROWNUMfeatureto
limitthenumberofrowsintheresponse,likethis:
RememberthattheROWNUMpseudocolumnassignsrownumberstothe
query’soutput(beforeprocessingtheORDERBYclause)andcanbeeffectivein
limitingoutput.Inthisexample,itensuresthatwereceiveonlyaone-row
response.Butagain,thismaynotlogicallysupporttheoriginalintentofyour
query.
Themoralofthestoryistousethesingle-rowsubquerywhenyouknowthe
resultwillbeonerow.Otherwise,you’dbetterusesomethingotherthanthe
single-rowsubqueryformatoryou’llruntheriskofanexecutionerror.
Also,ifthesubqueryreturnsnorowsatall,thennoerrorwillresult.The
querywillexecute,butthesubquerywillreturnaNULLvaluetotheparent
query.
KeepinmindthatafailedexecutionattemptinSQLisn’tnecessarilyabad
thing.Sometimesit’sagoodideatocreateasingle-rowsubqueryinsituations
whereyouwanttodeliberatelyfailtheparentqueryifmultiplerowsarefound
inthesubquery.Thiscanbeausefulfeaturethatcanhelpflagbigger
problemselsewhereinthedatabase,suchasthefailureofauniqueidentifying
mechanismlikeaprimarykey,orsomeotherlogicalerrorbeyondyour
immediateSQLcode.WhenyourSQLstatementsareembeddedwithinsome
otherprogramsthathavethecapabilitiesofhandlingfailures,orexceptionsas
theyarecalledinlanguageslikeOraclePL/SQLandJava,youcanprogram
thosesystemstotakeevasiveorcorrectiveactionsandaddresswhatmightbea
muchbiggerproblem.
YoucanusemultiplesubquerieswithinasingleWHEREclause.Here’sa
SQLstatementwithmorethanonesubquery:
Noticeintheexamplewhatishappeningonline6.Inthatportionofthe
query,wearecomparingaparentcolumnnamedSSNtothesubquerycolumn
calledSOCIAL_NUMBER.Subqueriesdonothavetosharethesamecolumn
namewiththeparentquery.Theonlythingthatisrequiredisthatthedatatypes
forSSNandSOCIAL_NUMBERbecomparable.Ifthedatatypesmatchup,the
comparisonisvalid.
Table9-1liststhecomparisonconditionsavailableforusewithsingle-row
subqueries.
TABLE9-1 Single-RowSubqueryComparisonConditions
ThekeywordINdeservesspecialattention.WhenthekeywordINisused,the
parentqueryseesthesubqueryaspotentiallyamultiple-rowsubquery,which
we’lldiscussinthenextsection.
So,single-rowsubqueriesareusefulforperformingmultistepquerieswhen
youcanguaranteethatthesubquerywillreturnasinglerow.Butwhenyour
subqueryreturnsmultiplerows,youneedtotakeadifferentapproach.Let’slook
atthatnext.
Multiple-RowSubqueries
Amultiple-rowsubquerymayreturnmorethanonerowofanswerstotheparent
query.Forexample,wesawinourearlierexamplethatthereisapparentlymore
thanoneemployeeinourEMPLOYEEStablewithalastnameofSmith.
Becauseofthatfact,wecouldn’tusethesingle-rowqueryformatwitha
subquerythatsearchedforrowswithaLAST_NAMEvalueofSmith.Butwe
canusethatsubqueryinthemultiple-rowformat,asshownhere:
Nowourqueryisaskingtolisttheemployeeswhoworkonashipwith
anyonenamedSmithandthenlisttheSmithsthemselves.Butforourpurposes,
noteline3,wherewereplacedtheequalsignwiththereservedwordIN.Asa
resultofthatonechange,wenolongergetanerrormessagebutinsteadgetthis:
RememberfromourdiscussionoftheWHEREclauseandthesetof
comparisonoperatorsthatthekeywordINallowstheWHEREclauseto
compareonevaluetoasetofvalues.Thesamedynamicisatworkhere.IN
allowsthesubquerytoreturnmultiplerows.ThepresenceofthekeywordIN
directstheparentquerytoallowthesubquerytobeamultiple-rowsubquery.
Notethatthesubquerydoesn’thavetoreturnmultiplerows.Thepresenceof
INsimplyallowsforthepossibility.
Noticewedidn’tgetanexecutionerrorthistime.Instead,weobtainedoutput
andcannowseethatwehaveanemployeenamedSmithassignedtoSHIP_ID1
andanotheronSHIP_ID3.OurSELECTstatementreturnsrowsshowing
employeesoneithership.
Table9-2liststhecomparisonoperatorsthatcanbeusedwithamultirow
subquery.
TABLE9-2 MultirowSubqueryComparisonConditions
Youcanusegreater-thanorless-thancomparisonoperatorswithsingle-row
subqueriesbutnotmultirowsubqueriesunlessthoseoperatorsarecombined
withALL,ANY,orSOME.
ThekeywordsshowninTable9-2indicatethattheparentqueryisexpecting
thesubquerytobeamultirowsubquery.Amultirowsubquerycanreturn
anywherefromzerotomultiplerowsofanswers.
NOTINandNULLValuesintheSubquery
Considerthefollowing:
Sofar,sogood.Butlet’saddaNULLtotheKIDtableandtrytheNOTIN
again.
Sowhathappened?WhenaNULLisintroducedintotherowsetreturnedby
thesubquery,ano-winsituationresults.Howcanyouknowdefinitivelywhether
theparentqueryHOUSEvalueisnotequaltoanyofthevaluesreturnedbythe
subquerywhenthosevaluesincludeNULL?Remember,NULLisnot“blank.”It
is“Idon’tknow”—itisanunknownvalue.SoistheparentHOUSEvaluenot
equaltoavaluethatisn’tknownbythesubquery?Whocouldtell?Itis
impossibletotell,so“norowsselected.”
TheNOTINcomparisonoperatorwillalwaysruntheriskofthissituationif
thesubqueryincludesNULLvalues.OneapproachistoexcludeNULLvaluesin
thesubquerywhenusingNOTIN.
Theresultmakessense—butonlyifanyNULLvaluesareexplicitlyomitted
fromthesubquery.
CERTIFICATIONSUMMARY
AsubqueryisaSELECTstatementthatexistswithinalargerSQLstatement.
SubqueriescanbeincludedinaSELECT,INSERT,UPDATE,MERGE,or
DELETEstatement.SubqueriescanalsobeusedinaCREATETABLE
statement.
SubqueriescanbeusedinWHEREclausesofSELECT,UPDATE,and
DELETEstatements.TheycanbeusedintheUPDATE...SETclauseandthe
INSERTlistofvalues.Somesubqueriesmaybeabletosubstituteforany
expressionalmostanywhereanexpressionisaccepted,includingtheSELECT
listofaSELECTstatement.
Subqueriescanperformmultiple-stepqueriesinasingleSQLstatement.
Theycanbeusedtoreferencelookupinformationfromagivenquery.Theycan
populateatableatthetimeofcreationinaCREATETABLEstatement.They
areusedtocreateviews.
Therearemanytypesofsubqueries,includingsingle-row,multiple-row,
multiple-column,scalar,andcorrelated.
Single-rowsubqueriesreturnonerowofdatatotheparentquery.Multiple-
rowsubqueriescanreturnanywherefromzerotoonetomorethanonerow.
Multiple-columnsubqueriesarecomparedtorowsintheparentqueryusing
multiplecolumnsatonce.Scalarsubqueriesreturnonerowandonecolumn’s
worthofdataatalltimes.Correlatedsubqueriescontainconditionsinthe
subquerythatconnectrowsofdatawithrowsintheparentquery,muchlikea
joinmightdo.
✓TWO-MINUTEDRILL
DefineSubqueries
AsubqueryisaSELECTstatementcontainedwithinaSQL
statement.
TheouterSQLstatementiscalledtheparent.Theoutermostlevelis
thetoplevel.
Atop-levelSQLstatementcontainingasubquerycanbea
SELECT,INSERT,UPDATE,orDELETE,orelseaCREATETABLE
orCREATEVIEW.
Subqueriescanbenestedwithinothersubqueries.
Manysubqueriescouldfunctionasstandalonequeries.Someare
correlated,meaningthattheycontainreferencesthattiethemintotheir
parentqueries.
DescribetheTypesofProblemsSubqueriesCanSolve
Subqueriesareidealforqueriesbasedonaggregateresultsofother
queries.
Subqueriesareusedtocreateviewobjects.
YoucanuseasubqueryinaSELECT,UPDATE,orDELETE
statement.
Subqueriescanbeusedasalternativestoexpressions.
DescribetheTypesofSubqueries
Asingle-rowsubqueryreturnsonerowofdatatotheparentquery.
Amultiple-rowsubquerymayreturnmorethanonerowofdatato
theparentquery.
Multiple-columnsubqueriesreturntwoormorecolumns’worthof
dataatoncetotheparentquery,whichmusttestforallthecolumnsat
once.
Correlatedsubqueriesusedatafromaparentquerytodetermine
theirownresult.
Scalarsubqueriesalwaysreturnonevalue,representedinone
columnofonerow,everytime.
Themultiple-columnsubquerymaybeofthesingle-rowor
multiple-rowtypeofsubquery.
Acorrelatedsubquerymightbeasingle-row,multiple-row,or
multiple-columnsubquery.
QueryDataUsingCorrelatedSubqueries
Correlatedsubqueriesusedatafromtheparentinsubquery
predicatestodeterminewhatdatatoreturntotheparentquery.
Correlatedsubqueriesmaypresentsomeperformancedegradation;
however,theycanperformtasksthatcouldnototherwisebe
accomplishedinasinglequery.
UpdateandDeleteRowsUsingCorrelatedSubqueries
TheUPDATEandDELETEstatementscanusecorrelated
subqueries.
TheUPDATEstatementcanusecorrelatedsubqueriesintheSETor
WHEREclause.
TheDELETEstatementcanusecorrelatedsubqueriesinthe
WHEREclause.
UsetheEXISTSandNOTEXISTSOperators
TheEXISTSoperatorcanbeusedbyaparentquerytotesta
subqueryanddeterminewhetheritreturnsanyrowsatall.
NOTEXISTSreversesthefindingsofEXISTS.
UsetheWITHClause
TheWITHclausecandynamicallynameasubquerysothatthe
SELECTstatementfollowingtheWITHclausecanreferencethat
subquerybyname,treatingitasadynamictableinrealtime.
AnysubquerynamesassignedwithintheWITHclauseareonly
goodforthatstatement;theyarenotstoredinthedatabase.
WriteSingle-RowandMultiple-RowSubqueries
Theresultsofasingle-rowsubquerycanbecomparedtoan
expressionwithintheparentusingascalarcomparisonoperator,suchas
anequalsignoragreater-thanorless-thansign.
Thecolumnnamesarenotrequiredtomatchinsuchacomparison,
butthedatatypesmustmatchsothattheparentquerycancompare
columnsofanynametosubquerycolumnsofanyname,providedthe
datatypesmatch.
Multiple-rowsubqueriesarecompareddifferentlytotheparent
querythansingle-rowsubqueries.
Multiple-rowsubqueriesarecomparedtoexpressionsintheparent
querybyusingmultiple-rowcomparisonconditions,suchasIN,ANY,
orALL,incombinationwithsingle-rowcomparisonoperatorssuchas<,
>,=,!=.
Amultiple-rowsubquerycannotbecomparedtoaparentquery
expressionusingasingle-rowcomparisonoperator;ifsuchanattemptis
made,thestatementwillfailwithanexecutionerrormessage.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
DefineSubqueries
1.Whichofthefollowingformsofsubqueryneverreturnsmorethanone
row?
A.Scalar
B.Correlated
C.Multiple-column
D.Noneoftheabove
DescribetheTypesofProblemsSubqueriesCanSolve
2.Whichofthefollowingproblemscanbesolvedwithasubquery?
(Choosethetwobestanswers.)
A.Youaretaskedwithdeterminingtheminimumsalesforevery
divisioninamultinationalcorporation.
B.Youaretaskedwithdeterminingwhichdivisionsinacorporation
earnedsaleslastyearthatwerelessthantheaveragesalesforall
divisionsintheprioryear.
C.Youaretaskedwithcreatingaview.
D.Youaretaskedwithcreatingasequence.
DescribetheTypesofSubqueries
3.Whichofthefollowingstatementsaretrue?(Choosetwo.)
A.Asingle-rowsubquerycanalsobeamultiple-rowsubquery.
B.Asingle-rowsubquerycanalsobeamultiple-columnsubquery.
C.Ascalarsubquerycanalsobeamultiple-columnsubquery.
D.Acorrelatedsubquerycanalsobeasingle-rowsubquery.
4.Whichsubqueryincludesreferencestotheparentqueryandthus
cannotexecuteasastandalonequery?(Choosethebestanswer.)
A.Ascalarsubquery
B.Acorrelatedsubquery
C.Amultiple-columnsubquery
D.Areferentialsubquery
5.Whichofthefollowingcanasubquerybeusedin?(Chooseallthat
apply.)
A.AnINSERTstatement’sSELECT
B.AGRANTstatement
C.AWHEREclauseinaSELECTstatement
D.Aninlineview
6.Aninlineviewisaformofasubquery.
A.True
B.False
QueryDataUsingCorrelatedSubqueries
7.ReviewthisWORK_HISTORYtable.
Yourtaskistocreateaquerythatwilllist—foreachship—allofthe
EMPLOYEE_IDvaluesforalltheemployeeswhohavetheshortestwork
historyfortheirship.Inotherwords,iftherearetwoships,youwanttolist
alltheemployeesassignedtothefirstshipwhohavetheshortestwork
history,alltheemployeesassignedtothesecondshipwhohavethe
shortestworkhistory,andsoon.Whichofthefollowingquerieswill
accomplishthistask?(Choosetwo.)
8.ReviewthePORTSandSHIPStables.
Yourteamistaskedwiththejobofcreatingalistoftheshipswiththe
leastcapacityineachport.Inotherwords,eachshiphasahomeport.For
eachportthatisahomeporttoships,whichofeachport’sshipshasthe
leastcapacity?Yourteamproducesthefollowingqueryinanswertothis
task:
WhichofthefollowingstatementsistrueaboutthisSQLstatement?
A.Thestatementwillfailwithasyntaxerrorbecauseofthe
subqueryonlines1through3.
B.Thestatementwillfailwithanexecutionerrorbecauseofthe
subqueryonlines1through3.
C.Thestatementwillexecutebutwillreturnmeaningless
information.
D.Thestatementwillexecutesuccessfullyasintended.
9.Acorrelatedsubquery:
A.MaybeusedinaSELECTbutnotanUPDATE
B.Cannotbeexecutedasastandalonequery
C.Mustuseatablealiaswhenreferencingacolumnintheouter
query
D.Alloftheabove
UpdateandDeleteRowsUsingCorrelatedSubqueries
10.Whichofthefollowingcanacorrelatedsubquerybeusedin?(Choose
three.)
A.TheSETclauseofanUPDATEstatement
B.TheWHEREclauseofanUPDATEstatement
C.TheWHEREclauseofaDELETEstatement
D.TheFROMclauseofaDELETEstatement
11.Reviewtheillustrationfromquestion8andthefollowingSQLcode:
ThePORTStablehas15rows.TheSHIPStablehas20rows.Eachrow
inPORTShasauniquevalueforPORT_ID.EachPORT_IDvalueis
representedintheHOME_PORT_IDcolumnofatleastonerowofthe
SHIPStable.WhatcanbesaidofthisUPDATEstatement?
A.ThevalueforCAPACITYwillincreaseonceforeachofthe15
rowsinthePORTStable.
B.ThevalueforCAPACITYwillincreaseby20foreachofthe15
rowsinthePORTStable.
C.ThevalueforCAPACITYwillnotincrease.
D.Thestatementwillfailtoexecutebecauseofanerrorinthe
syntax.
UsetheEXISTSandNOTEXISTSOperators
12.AnothernameforanEXISTSqueryis:
A.Demijoin
B.Multiple-columnsubquery
C.Cross-join
D.Semijoin
13.Reviewtheillustrationfromquestion8andthefollowingSQLcode:
ThecodeisattemptingtodeleteanyrowinthePORTStablethatisnot
ahomeportforanyshipintheSHIPStable,asindicatedbythe
HOME_PORT_IDcolumn.Inotherwords,onlykeepthePORTSrows
thatarecurrentlytheHOME_PORT_IDvalueforashipintheSHIPS
table;getridofallotherPORTrows.That’stheintentoftheSQL
statement.WhatwillresultfromanattempttoexecutetheprecedingSQL
statement?
A.Itwillfailbecauseofasyntaxerroronline2.
B.Itwillfailbecauseofasyntaxerroronline4.
C.Itwillfailbecauseofanexecutionerrorinthesubquery.
D.Itwillexecutesuccessfullyandperformasintended.
UsetheWITHClause
14.TheWITHclausecanbeusedtonameasubquery.Whichofthefollowingis
alsotrue?(Choosetwo.)
A.ThenameofthesubquerycanbeusedintheSELECTstatement
followingtheWITHclause.
B.Thenameofthesubquerycanbejoinedtoothertablesinthe
SELECTstatementfollowingtheWITHclause.
C.ThenameofthesubqueryisstoredinthedatabasebytheWITH
statementandcanbereferencedbyotherSQLstatementsinlater
sessions.
D.Thenameofthesubquerycanbeinvokedfromwithinthe
subquerythatisnamed.
15.Reviewtheillustrationfromquestions8.Whichofthefollowingstatements,
whenexecuted,willresultinanerror?
WriteSingle-RowandMultiple-RowSubqueries
16.Whichofthefollowingcomparisonoperatorscanbeusedwithamultiple-
rowsubquery?(Choosetwo.)
A.=
B.>=ALL
C.LIKE
D.IN
17.ReviewthePORTSandSHIPStables:
Next,reviewthefollowingSQLcode:
YouknowthattherearefiverowsintheSHIPStablewithalength
greaterthan900.WhatwillresultfromanattempttoexecutethisSQL
statement?
A.Anexecutionerrorwillresultbecausethesubquerywillreturn
morethanonerowandtheparentqueryisexpectingonlyonerow
fromthesubquery.
B.AsyntaxerrorwillresultbecausePORT_IDand
HOME_PORT_IDinline3havedifferentcolumnnames.
C.Thestatementwillexecuteandproduceoutputasintended.
D.Noneoftheabove.
18.Whenisaqueryconsideredamultirowsubquery?(Choosethebestanswer.)
A.Ifitreturnsmultiplerowsatthetimeofexecution
B.Ifitmayormaynotreturnmultiplerows,asdeterminedbyits
WHEREclause
C.Ifitreturnsnumericdata,regardlessofthenumberofrowsof
dataitreturns
D.Alloftheabove
19.Whichofthefollowingisatruestatement?
A.IfaSELECTincludesaGROUPBYclause,thenanysubquery
usedwithintheSELECTmustalsohaveaGROUPBYclause.
B.Ifaqueryreturnsmultiplerows,itmaynotbeusedasa
subqueryforaSELECTstatementthatusesaGROUPBYclause.
C.ASELECTstatementwithaGROUPBYmayuseasubqueryto
returnavaluetotheoutermostWHEREclause.
D.TheonlyformofsubquerypermittedwithaGROUPBYclause
isacorrelatedsubquery.
20.ReviewthePORTSandSHIPStablesshowninquestion7.Thenreviewthe
followingSQLcode:
Whichofthefollowingistrueofthisstatement?
A.Thestatementwillfailwithasyntaxerrorbecauseofline3.
B.Thestatementwillfailwithasyntaxerrorbecauseofline5.
C.Whetherthestatementfailsdependsonhowmanyrowsare
returnedbythesubqueryinlines3through5.
D.Noneoftheabove.
SELFTESTANSWERS
DefineSubqueries
1. A.Ascalarsubqueryalwaysreturnsasinglevalue,whichistosayit
returnsonlyonecolumn,onerow.
B,C,andDareincorrect.Acorrelatedsubquerymayormaynotreturn
multiplerows.Multiple-columnsubqueriesmayormaynotreturnmultiple
rows.
DescribetheTypesofProblemsSubqueriesCanSolve
2. BandC.Theidealquerywouldfirstobtaintheaveragesalesforthe
prioryearandthenusetheresultstocomparetothesubsequentyear’s
sales.Youuseasubquerytocreateaview.
AandDareincorrect.Theminimumsalesateverydivisioncanbe
determinedusingaquerywithaGROUPBY.Asubqueryisnotrequiredor
particularlynecessaryhere,basedontheinformationprovided.Youdonot
useasubquerytocreateasequence.
DescribetheTypesofSubqueries
3. BandD.Asingle-rowsubquerymayconsistofmultiplecolumnsin
itssinglerow.Anditalsomaybecorrelated.
AandCareincorrect.Asingle-rowsubquerycannot,bydefinition,also
beamultiple-rowsubquery.Ascalarsubquerybydefinitioncanbeonly
onecolumninonerow,soitcannotbeamultiple-columnsubquery.
4. B.Acorrelatedsubqueryisthebestanswer.Thenameindicatesthat
thesubqueryiscorrelatedtotheparentquery.Technically,scalarand
multiple-columnsubqueriesmayalsobecorrelated,butweaskedforthe
bestanswer,andclearlythatiscorrelatedsubquery.
A,C,andDareincorrect.Technically,ascalarsubquerymayalsobea
correlatedsubquery,whichiswhythequestionaskedyoutopickthe“best
answer”—thetermcorrelatedrefersspecificallytotheconceptofreferring
totheparentquery,whereasascalarsubqueryrefersspecificallytoa
subquery’sreturnvalueasbeingasinglevalue.Thesameistruefora
multiple-columnsubquery—thatmayalsobeacorrelatedsubquery,butthe
term“multiple-column”isintendedtoemphasizethefactthatitreturns
multiplecolumns’worthofresultsatonce.Finally,areferentialsubquery
isn’tanything;wejustmadethatup.
5. A,C,andD.AsubquerycouldbeusedwithintheSELECT
statementofanINSERTstatement,includingtheSELECTstatement’s
WHEREclause,andwithinaninlineview.
Bisincorrect.AGRANTstatementisaDCLstatementandcannothave
asubquery.
6. A.Aninlineviewiscalledaviewsinceitisaquerythatistreated
likeatable.Thatbeingsaid,itssyntaxisthatofthesubquerysyntax.
Bisincorrectbecausethestatementistrue.
QueryDataUsingCorrelatedSubqueries
7. AandC.Aisaclassiccorrelatedsubquery,connectingthesubquery
totheparentbywayoftheW1.SHIP_IDvalue.Calsoworkswiththe<=
ALLcomparisoncondition.
BandDareincorrect.Bismissingthejoininthesubquerythatconnects
thesubquerywiththeparentquery.Dcomparestheparentquery’sWHERE
clausevaluetothesubquerywithaless-thansign,whichwon’twork—the
subqueryisalreadyselectingtheminimumvaluefromthesubquery,sothe
parentquerycan’tfindanythingthatwillbelessthantheminimum.
8. D.Thestatementissyntacticallyfine.TheSELECTincludestwo
correlatedsubqueries.Thefirst,inlines1through3,isanexpressioninthe
SELECTstatement’sselectlist.Thissubqueryiscorrelatedbywayofthe
referenceattheendofline3.Thesecondcorrelatedsubqueryisinlines5
through7,anditobtainstheminimumcapacityvalueforshipsbelongingto
eachport.
A,B,andCareincorrect.Thestatementwillnotfail,notwithasyntax
problemorwithanexecutionproblem.Thedataitreturnsisexactlyas
requested.
9. B.Acorrelatedsubquerycannotbeexecutedasastand-alonequery.
A,C,andDareincorrect.Acorrelatedsubquerycanbeusedina
SELECT,UPDATE,orDELETE.Acorrelatedsubquerydoesnothaveto
useatablealiaswhenreferencingcolumnsunlessthereisariskof
ambiguity.
UpdateandDeleteRowsUsingCorrelatedSubqueries
10. A,B,andC.Acorrelatedsubquerycanbeusedinanyoftheseanswers.
Disincorrect.AcorrelatedsubquerycannotbeusedintheFROMclause
ofaDELETEstatement.Note,however,thatthequestionisasking
specificallyaboutcorrelatedsubqueries.Whileyoucannothavea
correlatedsubqueryintheFROMclauseoftheDELETE,we’lllatersee
thatan“inlineview”canbeusedthere,andan“inlineview”isessentiallya
subquery—butnotacorrelatedsubquery.
11. A.TheCAPACITYwillincreaseonceforeachrowprocessedbythe
UPDATEifthatrowisfoundinthesubquery.
B,C,andDareincorrect.
UsetheEXISTSandNOTEXISTSOperators
12. D.Thesemijoinisthecorrectanswer.
A,B,andCareincorrect.Thereisnosuchthingasademijoin.A
multiple-columnsubqueryrequiresseveralcolumnsonbothsidesofthe
comparisoncondition.Across-joinisatablejoinwithnojoincriteria.
13. A.Itwillfailbecauseofasyntaxerroronline2—thefirstreferenceto
PORT_IDshouldberemoved.EXISTSdoesnotcomparethesubqueryto
anything.Inotherwords,line2shouldbeWHERENOTEXISTS
(SELECT*withoutthefirstPORT_IDreference.Otherthanthat,
everythingelseaboutthequeryisfine.
B,C,andDareincorrect.Line4hasnosyntaxerrors.Nordoesthe
subquerycontainanyexecutionerrors.ButneitherwilltheSQLexecute,
forthereasonswedescribedfortherightanswer.
UsetheWITHClause
14. AandB.ThenamecanbeusedintheSELECTfollowingtheWITH
clause.
CandDareincorrect.Thenameisnotstoredinthedatabasebythe
WITHstatement.ItexistsonlyfortheWITHclauseitselfandisnot
recognizedoutsideoftheWITHclause.TheoneplacewithintheWITH
clausethatdoesnotrecognizethesubquerynameiswithinthenamed
subqueryitself.
15. AandD.TheWITHclausemustnamethequeryinorderfortheSELECT
tobeabletoreferencethequerycontainedwithintheparentheses.The
syntaxofWITHdoesnotusetheSELECTprecedingtheWITH.
BandCareincorrect.Eachissyntacticallycorrect.Bothnamethequery
intheWITHclause.
WriteSingle-RowandMultiple-RowSubqueries
16. BandD.The>=ALLsyntaxis“greaterthanorequaltoall”thevalues
returnedbythesubquery,whichisidealforamultiple-rowquery.TheIN
comparisonoperatorisalsouseful.
AandCareincorrect.Theequalsignisrestrictedtoonlysingle-row
subqueries.TheLIKEoperatorisalsolimitedtosingle-rowsubqueries.
17. A.Thequerywillproduceanexecutionerrorbecausetheparentqueryis
expectingasingle-rowanswerfromthesubquery.Youknowthisbecause
ofthecomparisonoperatorinline3:thegreater-thansignisasingle-row
comparisonoperator.Thebetterchoiceheremightbe>ANYor>ALL,
dependingonthesituation.
B,C,andDareincorrect.ThereisnothingwrongwithPORT_IDand
HOME_PORT_IDhavingdifferentcolumnnames.Aslongastheirdata
typesmatch,alliswell,andyouknowtheirdatatypesmatchaccordingto
theillustrationprovided.
18. A.Itreturnsmultiplerowsatthetimeofexecution.
B,C,andDareincorrect.TheWHEREclauseiscertainlyimportant,but
thequery’sparticularformisnotimportant.Whatisimportantiswhether
thequeryreturnsmultiplerowsatthetimeitexecutes.Thepresenceof
numericdataisnotimportant,noristhenumberofcolumns.
19. C.AsubquerycanbeusedtoreturnavaluetotheWHEREclauseofa
SELECTstatement,regardlessofwhetheraGROUPBYisinvolved.The
issueofwhetherthesubqueryreturnsonerowormultiplesmustbe
handledcorrectly,aswe’vediscussedelsewhere.Butprovideditisdone
correctly,asubquerycanbeusedinthiscontext.
A,B,andDareincorrect.ThereisnoissuewithregardtoGROUPBY
andtheuseofsubqueries.ASELECTwithaGROUPBYisallowedthe
optionoftheuseofsubqueries,eithersingle-rowormultiple-row(orboth)
providedthattherulesofthesingle-rowand/ormultiple-rowsubqueryare
handledcorrectly.AGROUPBYispermittedtouseanyformofsubquery;
itisnotrestrictedtothecorrelatedsubquery.
20. A.Thestatementwillfailwithasyntaxerrorbecausetherearetwo
columnsinthesubquery,butonlyonevalueisontheleftsideofthe
comparisonoperatorIN.
B,C,andDareincorrect.Thesyntaxonline5isacceptable.Theuseof
INinline3ensuresthatthesubquerywillbepermittedtoreturneitherone
ormultiplerows,andwithallelsebeingacceptable,thestatementwould
otherwiseexecutesuccessfully.
10
ManagingSchemaObjects
I
CERTIFICATIONOBJECTIVES
10.01DescribeHowSchemaObjectsWork
10.02CreateSimpleandComplexViewswithVisible/InvisibleColumns
10.03Create,Maintain,andUseSequences
10.04CreateandMaintainIndexesIncludingInvisibleIndexesandMultiple
IndexesontheSameColumns
10.05PerformFlashbackOperations
✓Two-MinuteDrill
Q&ASelfTest
nadditiontotables,thereareotherimportantschemaobjects.Thischapter
looksatseveral,includingviews,sequences,andindexes.Thischapteralso
addressesadditionalfeatures:FlashbackTable,FlashbackDrop,andFlashback
Query.
CERTIFICATIONOBJECTIVE10.01
DescribeHowSchemaObjectsWork
Asyou’veseen,thereareseveralobjectsinthedatabase.Manyare“schema”
objects,meaningtheyare“owned”byauserandexistinacollectionwithina
useraccount.Schemaobjectsincludetables,views,indexes,andsequences.In
thissection,we’lllookatsomeofthefunctionalityofdatabaseobjectsandhow
theyworkwitheachother.
Tables
Allthedatainadatabaseisstoredintables.Whenyoucreateanewtable,the
informationaboutthattable,suchasitsnameandcolumnsandthedatatypesof
thosecolumns,isallstoredinasetofsystem-definedtablesthatarecollectively
knownasthedatadictionaryandthataremanagedautomaticallybytheOracle
system.(WeexaminethedatadictionaryinChapter12.)So,evendataabout
yourdata—inotherwords,metadata—isstoredintables.
Atable’scolumnsaregenerallystoredintheorderinwhichtheyarecreated,
butthisisn’tnecessarilytrueatalltimes.Also,ifyoualteratableviaALTER
andaddacolumntoitsstructure,thenewcolumnwillbeaddedattheendofthe
listofcolumnsinthetable’sstructure.
Constraints
Aconstraintisaruleonatablethatrestrictsthevaluesthatcanbeaddedtoa
table'scolumns.Notethatitisnotadatabaseobject,butitislistedinthedata
dictionaryandcanbenamedwiththesamenamingrulesofanobject.You’ve
alreadylookedatthedifferenttypesofconstraints:NOTNULL,UNIQUE,
PRIMARYKEY,FOREIGNKEY,andCHECK.
IfaSQLstatementattemptstoadd,modify,ordeletearowto/fromatable
andinsodoingviolatesaconstraint,theentireSQLstatementwillfailwithan
executionerror.
Views
Aviewactslikeatable.Ithasaname.Youcandescribetheviewwith
DESCRIBEinthesamewayyouwoulddescribeatable.YoucanrunaSELECT
statementonaviewjustasyouwouldselectfromatable.Dependingonthekind
ofviewyouareworkingwith,youmightevenbeabletoexecuteINSERT,
UPDATE,and/orDELETEstatementsonaviewtomanipulatethecontentsof
theunderlyingtables.
Butaviewisnotatable,anditstoresnodata.Aviewisnothingmorethana
SELECTstatementthatissavedinthedatabasewithanameassignedtoit.The
columnstructurethattheviewtakesonisformedbytheSELECTstatement’s
selectlist.Thedatatypesforthosecolumnsarepickedupautomaticallyfromthe
underlyingtableortheexpressionsusedintheSELECTstatementtocreatethe
view.
Indexes
Anindexperformsthesamejobthatatypicalindexinabookperforms.For
example,OracleCorporation’sSQLLanguageReferenceManualforOracle
12c’sR1releaseismorethan1,908pageslong.Whatifyouwerelookingfor
informationontheDISTINCTclauseoftheSELECTstatement?Youhaveafew
waystofindsuchinformationinthebook.Onewayistositdownandstart
readingthebookatthefirstpageandkeepreadinguntilyoufindthedatayou’re
lookingfor.Amuchmoreefficientwayistofliptothebackofthebookandfind
theindex,whichcontainsasummaryofimportanttopicsinalphabeticalorder.
WithinafewsecondsyoucanlookupthewordDISTINCT,notethepage
numberonwhichit’smentioned,andflipstraighttoit.That’samuchbetter
approach.
TheSQLINDEXobjectperformsinmuchthesameway.Whenyoucreatean
INDEXobject,youareidentifyingoneormorecolumnsinatablethatyou
believewillbefrequentlyusedtolookupdata.Thenyoucreatetheindexbased
onthatcolumn—orsetofcolumns—andOracleliterallybuildsaseparateobject
thattakesauniquelistofallthedatacurrentlyinthatcolumn,sortsit
appropriatelyaccordingtodatatype,andthenstoresinternaladdressing
informationthattiestheindextothesourcetableandtherowscontainedwithin.
Theresultisthatanyfuturequeriesonthetablethathappentoreferenceany
indexeddatawillcausethefollowingtooccurautomatically:
Performananalysistodeterminewhetherthequerywillbenefitby
usingtheindex
Ifyes,thenredirectthefocustemporarilytotheindex,searchthe
indexforanyofthedesireddataidentifiedbythequery,andobtaindirect
locationsoftheappropriaterows
Thedifferenceinperformanceispotentiallysignificant.Themoredatathatis
storedinatable,themorebeneficialanindexmaybe.
Sequences
Asequenceisacounter,meaningthatitissuesnumbersinaparticularseries,
alwayskeepingtrackofwhateverthenextnumbershouldbe.Ifyouever
watchedtheclassictelevisionsitcomSeinfeld,youmightrecalltheepisode
whereJerryandElainegotoabakerytopickupachocolatebobka,butdon’t
knowtotakeanumberfromthedispenserwhentheyfirstarriveandlosetheir
placeinlineasthebakerygetscrowded.Thatdispenser—whichissuespaper
ticketsidentifyingtheholderasbeing,say,“number42”inline—servesthe
samepurposeofaSEQUENCEobjectinthedatabase.
TheprimarypurposeofSEQUENCEistosupporttheprocessofaddingrows
toaparticulartableandprovidingthenextuniquevalueforaPRIMARYKEY
forthetable.That’sit.There’snothinginherentinaSEQUENCEobjectthatties
ittoaparticulartable.There’snothingautomaticintheSEQUENCEobjectthat
necessarilysupportsaparticulartable.It’suptothesoftwaredevelopertoknow
howtousetheSEQUENCEobjectcorrectly.Wewillexplorethisindetaillater
whenweaddressthesyntaxforworkingwithaSEQUENCE.
CERTIFICATIONOBJECTIVE10.02
CreateSimpleandComplexViewswith
Visible/InvisibleColumns
AviewisaSELECTstatementwithaname,storedinthedatabase,and
accessibleasthoughitwereatable.EarlieryousawtheWITHclausethatcan
assignanametoaquerywithinasingleSELECTstatement.Theviewobject
doesthesamethinginamorepermanentmanner,meaningthattheviewobject
residesinthedatabasealongsidetablesandotherdatabaseobjects.
Onceyou’vecreatedaview,youcanrefertoitinSELECTstatementsas
thoughitwereatable.NothingabouttheSELECTisdifferent—anyonelooking
atagivenSELECTstatementwillnotbeabletodeterminefromtheSELECT
statementaloneiftheFROMclausespecifiesatableoraview.
Viewsareusefulforavarietyofreasons.Onebenefitissecurity.For
example,consideratypicalscenariowhereyouhavealargetablethatcontainsa
combinationofsomesensitiveinformationalongwithsomeinformationthatis
ofageneralinterest.Youmightcreateaviewthatqueriesthegeneral-interest
columnsofthelargetableandthengrantprivilegesonthatviewtothegeneral
populationofusers.Thoseusersmaynowquerytheviewandgetdirectaccess
tothegeneralinformationwithouthavingaccesstomoresensitivedatathat
existsintheunderlyingtable.Viewsareagreatwaytomaskcertaindatawhile
givingaccesstootherdatainthesametable.
Anotherbenefittoviewsistheirabilitytomakeacomplexqueryeasierto
workwith.Forexample,youmightcreateaviewthatisbuiltonacomplexjoin
sothatthecomplexityisbuiltintotheview.Theresultisaviewobjectthat
appearstobeasingletable,whichyoumaynowqueryasthoughitwereatable.
Youcanevenjointheviewwithothertablesandotherviews.Inthissituation,a
viewcanbeusedtosimplifythecomplexityofacommonlyusedjoin.
Inthenextsection,we’llcreateaviewobject.
CreatingViews
Let’slookatanexample.First,reviewFigure10-1.We’llstartwithjustthe
EMPLOYEEStable—noticethatitincludescolumnsforemployeeID,name,
SocialSecuritynumber,dateofbirth,andprimaryphonenumber.
FIGURE10-1 DiagramsfortheEMPLOYEESandPAY_HISTORYtables
So,here’saproblem:whatifyouwantedtogiveaccesstothistablesothat
otherpeopleintheorganizationcangetthephonenumbersofemployees?Think
aboutthatsensitiveinformation,includingSocialSecuritynumbers,andyou
mighthavesecondthoughtsabouthavinganybodyquerytheEMPLOYEES
table.
Onesolutiontothispredicamentistouseaview.Let’screateaviewforthe
EMPLOYEEStable.
IfweexecutethisstatementinSQL,we’llgetthefollowingmessage:
(Note:ThisstatementisthemessagedisplayedbyOracleSQLDeveloper.
SQL*Pluswilldisplaya“Viewcreated”message.)
Nowthatwehavethisview,wecanworkwithitjustasifitwereatable.For
example,wecanuseDESCRIBEtoexplainit.
Additionally,wecanselectfromitwithSELECTasifitwereatable.
Theresultswilldisplayjustlikeanytable.Anyoneusing
VW_EMPLOYEES,runningSELECTstatementsonit,describingitsstructure,
anddoinganythingtheymightwantusingSQLcommandsmaynoteverrealize
it’snotatableatall.Thefactthatit’saviewisn’tnecessarilyobvious.Wechose
tonameitwithaVW_prefixforourownpurposes,butwecouldhavegivenit
anynamewewanted.
Thesyntaxrulesforcreatingavieware
ThekeywordsCREATEVIEW
TheoptionalkeywordsORREPLACE
Anamefortheview,specifiedaccordingtotherulesfornaming
databaseobjects
ThekeywordAS
Finally,avalidSELECTstatement,withafewrestrictions
OneoftherequirementsoftheCREATEVIEWstatementisthis:theresulting
VIEWmusthavevalidcolumnnames.ThismeansthatifyouchooseaSELECT
statementthatincorporatesanycomplexexpressionswithintheselectlist,each
expressionmustbeassignedacolumnalias,orcolumnnamesmustbeassigned
bytheCREATEVIEWstatementitself.Forexample,let’susetheOR
REPLACEoptiontocreateanewversionofourVW_EMPLOYEESview(line
numbersadded).
Whatwentwrong?Theproblemisonline3,wherewespecifytheexpression
thatformsthesecondcolumninourSELECTexpressionlist.Noticethatit
concatenatesthecolumnLAST_NAMEwithacomma,aspace,andthenthe
FIRST_NAMEcolumn.Here’stheproblem:whatisthenameofthiscolumn?
Thereisn’toneassigned,buttheCREATEVIEWstatementrequiresone.
Therefore,theattemptedCREATEVIEWstatementfails.
Tocorrecttheproblem,wecanspecifycolumnnamesintheCREATEVIEW
statement,likethis:
Nowwe’llhaveaviewconsistingofthreecolumnswiththenamesID,
NAME,andPHONE.Alternatively,wecouldhaveusedacolumnaliasinthe
SELECT
Youcanusecomplexqueriestocreateviews.Forexample,let’sgobackto
Figure10-1andbuildaquerythatjoinsdatafromthePAY_HISTORYtableinto
ourview,asfollows:
ThisstatementusesaSELECTstatementwithajoin,aGROUPBY,a
WHEREclause,andaggregatefunctions;itcreatesaVIEWobjectoutofallof
it.
VIEWobjectscanbebasedonSELECTstatementswithsubqueries,
functions,andmore.
Theviewcreatedwiththisstatementwillconsistonlyoftherowsinthe
SHIP_CABINStablewheretheSHIP_IDvalueisequalto1.The
SHIP_CABINStablemaycontainmorerowsthanthosewithaSHIP_IDof1,
butthoserowswon’tbefoundbywayofanyqueryontheSHIP_ONE_CABINS
view.
Also,takenoteagainoftheoptionalkeywordsORREPLACEinthe
CREATEVIEWstatement.Thesewordsdon’tworkwithCREATETABLE,but
theydowithCREATEVIEW.Becarefulwiththem—whenincluded,theywill
giveyounowarningifyouareorarenotoverwritingsomeexistingview.They
willsimplyoverwritewhatmayhavegonebeforeandreplaceitwiththenew
view.It’saconvenientoptionthatispowerful,sobecarefulwithit.Youhave
beenwarned.
ViewsandConstraints
Youcancreateconstraintsonaviewinthesamewayyoucancreatethemona
table.However,Oracledoesn’tenforcethemwithoutspecialconfigurationthat’s
availableprimarilytosupportcertaindatawarehousingrequirements.This
subjectisworthnotingbutnotspecificallyaddressedontheexam.
UpdatableViews
You’veseenhowwecanSELECTfromaview.ButcanwealsouseINSERT
andUPDATEandDELETE?
Theansweris,itdepends.Iftheviewcontainsenoughinformationtosatisfy
alltheconstraintsinanyunderlyingtables,thenyes,youcanuseINSERT,
UPDATE,orDELETEstatementsontheview.Otherwise,no.
Dependingonthenatureoftheconstraints,itmaybepossibletousesome
DataManipulationLanguage(DML)statementsbutnotothersontheview.For
example,iftheviewfailstoincludeanycolumnsfromtheunderlyingtablethat
haveNOTNULLconstraints,youwillnotbeabletoexecuteanINSERT
statement,butyoumaybeabletoissueanUPDATEorDELETEstatement.
Forexample,let’srevisittheEMPLOYEEStableinFigure10-1.Let’smake
anewviewonthattable,likethis:
Thisviewcontainsjustenoughinformationtoprintanemployeephonebook,
includingtheirnamesandphonenumbers.Oncewe’vecreatedthisview,wecan
selectfromit,likethis:
Fantastic.Butwait—wejusthiredsomeonenew.HernameisSonia
Sotogovernor,andwewanttoaddhernametothisview.Let’stryit.
Whoops.What’swronghere?Seetheerrormessage?Rememberthatour
underlyingtableistheEMPLOYEEStable,anditcontainsaPRIMARYKEYof
EMPLOYEE_ID,asshowninFigure10-1.Butourviewdoesn’tincludethat
column.Asaresult,thereisnowayforustoinsertavaluethroughthe
EMP_PHONE_BOOKviewsothatitwillprovideavaluefortherequired
columnofEMPLOYEE_ID.WecannotexecuteanINSERTstatementonthis
view.
However,wecanexecuteanUPDATEstatementontheview.Here’san
example:
Thisstatementworksperfectlyfineontheview.Thereasonisthatthe
changeswe’remakingwiththisUPDATEstatementdonotviolateany
underlyingconstraints.
Ifthereareanyconstraintsontheunderlyingtablethatyoucannotsatisfy
whenattemptingtoissueanINSERT,UPDATE,orDELETEonaview,thenthe
statementwon’twork.TheVIEWobjectmustprovideaccesstoanyofthe
underlyingtable’scolumnsinsuchawaythattheconstraintscanbehonoredto
satisfythoseconstraintsandexecutethestatementsuccessfully.Otherwise,the
INSERT,UPDATE,orDELETEstatementwillfail.
Inaddition,aviewthatisbasedonaggregatedrowswillnotbeupdatable.
YouwillbepreventedfromusingINSERT,UPDATE,orDELETEifyou
createaviewbasedonaSELECTstatementthatincludesanyofthefollowing:
Omissionofanyrequiredcolumns(NOTNULL)inthatunderlying
table
GROUPBYoranyotheraggregation,suchassetoperators
DISTINCT
AFROMclausethatreferencesmorethanonetable—thatis,
subqueriesintheSELECTormostjoins
Regardingthatlastitem,itistechnicallypossibletoexecuteDMLchangeson
joinswhereallupdatablecolumnsbelongtoakey-preservedtable.Thedetails
gobeyondthescopeofthisbook.Forthemostpart,youwillnotbeabletoissue
DMLchangestoaVIEWobjectbasedonajoin.
Aswe’vealreadyseen,aview’sSELECTstatementmayincludeexpressions
aspartofthecolumnsinitsformation,asfollows:
NotethattheprecedingqueryconcatenatestheFIRST_NAMEand
LAST_NAMEcolumnsintooneexpression.Asaresult,theindividualcolumns
cannotbemodifiedwithanINSERTorUPDATEstatement—thereisnowayto
singularlyrefertotheindividualcolumnsunlesstheyareaddedasindividual
itemsintheselectlist.However,EMPLOYEE_ID,therequiredcolumn,is
includedasanindividualcolumn,sothiswouldbeasatisfactorystatement:
ThatstatementwillsuccessfullyexecuteonourEMP_PHONE_BOOKview
andaddanewrowtotheunderlyingtable,assumingtheprimarykeyvaluefor
EMPLOYEE_IDisacceptedasanewuniqueentry.Butwe’renotabletoinsert
arowthroughtheviewusinganINSERTstatementthatreferencesthe
EMP_NAMEcolumnaliasoritscomponentcolumnsFIRST_NAMEand
LAST_NAME.Wesimplyhavetoomitanyreferencestothosecolumnsinour
DMLstatementsforourDMLtoexecutesuccessfully.TheINSERTINTO
EMP_PHONE_BOOKstatementwillcauseanewrowtobeaddedtothe
EMPLOYEEStable.ThatnewrowwillconsistofavalueforEMPLOYEE_ID
(102)andavalueforPRIMARY_PHONE('800-555-1212');allothercolumnsin
thenewrowwillshowasNULL—thatis,havenovalues.(Remember,NULL
representstheabsenceofinformation.)
Wemaydeletearowinthisview.Here’sanexample:
ThisstatementwillsuccessfullydeletetheentirerowforanEMPLOYEE_ID
of102.IfweissuedasimilarDELETEstatementforanyotherexistingvaluewe
canaccess,suchasPRIMARY_PHONEorEMPLOYEE_ID,andtherowwere
found,thentherow—theentirerowoftheunderlyingtable—wouldbedeleted.
Thatincludesdataincolumnswecan’tevenseewiththeview.Thewholerow
willbedeleted.
WithregardtothegeneralquestionofusingINSERT,UPDATE,and/or
DELETEonanygivenview,thegeneralanswerissimple:iftheviewprovides
row-level(notaggregated)accesstoone—andonlyone—tableandincludesthe
abilitytoaccesstherequiredcolumnsinthattable,thenyoucanuseINSERT,
UPDATE,and/orDELETEontheviewtoeffectchangestotheunderlyingtable,
inaccordancewiththerestrictionslistedearlier.Otherwise,youmaynotbeable
tosuccessfullyexecuteachangetotheview’sdata.
NotethattheINSTEADOFtriggerinPL/SQLcanbeusedtocausea
nonupdatableviewtobehaveasthoughitwereupdatable.ButPL/SQL
featuresarenotaddressedontheexam.
InlineViews
AninlineviewisasubquerythatiscontainedwithinalargerSELECTstatement
insuchawaythatitreplacestheFROMclauseofaSQLstatement.
Here’sanexample:
Inthisexample,theinlineviewisincludedintheparenthesesattheendof
line2.
Thereisnolimittothenumberofinlineviewsyoucannestwithininline
views.
This“unlimitednesting”isdifferentfromthelimitfortypicalsubqueries,
wherethelimitis255nestedsubqueries.
Inlineviewscanbecombinedwithvariouscomplexqueries,suchasthose
thatuseJOINandGROUPBYclausesandmore.Here’sanexample:
ThisstatementisasingleSELECTthatpullsdatafromtwoinlineviews,one
onlines2through4andthesecondonlines6through8.
InlineviewscanbeanyvalidSELECTstatement,placedintoaSQL
statementwheretheFROMclausewouldnormallygo.
Onegreatusageofaninlineviewistoaddressanissueinvolvingthe
pseudocolumnROWNUM.ROWNUMisarownumberautomaticallyassigned
toeachrowresultofaquery.ThechallengewithROWNUMisthatitis
assignedbeforetheORDERBYclauseisprocessed.Asaresult,youcannotsort
rowsandthenuseROWNUMasawayofdisplaying,forexample,theline
numberforeachrowofoutput.TheresultswillbemixedupsinceROWNUMis
determinedbeforeORDERBYisprocessed.ButyoucanmovetheORDERBY
clauseintoaninlineviewandthenusetheROWNUMpseudocolumnonthe
outerquerytodisplayrownumberscorrectly.Here’sanexample:
Inthisexample,weuseORDERBYintheinlineviewtosortourrowsby
INVOICE_DATE,andthenweuseROWNUMintheouterquerytolimitour
outputtojustthefirstthreerowsofdata.WealsoincludeROWNUMinour
selectlistsothatitappearsintheoutput.Withouttheinlineview,oddsarethat
ourROWNUMvalueswouldbeinanapparentlyrandomorderinsteadof
sequential.
So,whywouldyouwanttouseaninlineview?Therearemanyreasons.As
we’vealreadydemonstrated,inlineviewscanbeusedtocreatecomplexjoins
builtonaggregatedqueries.Anotherbenefithastodowiththenatureof
dynamicSQLasit’susedwiththird-generationlanguages.Manypopularweb
sitesarebuiltonwebpagesthataredynamicallyformedfromacombination
ofJava,PL/SQL,orPHPcodethatpullsdatafromthedatabaseandmerges
theoutputwiththelanguagesusedtoformwebpages.Afullexampleofsuch
ascenarioisbeyondthescopeofthisbook,butit’sworthnotingthatsuch
systemsrelyheavilyonroutinesthatcreateSQLcodedynamically,during
execution,inresponsetoqueriesfromendusers.Suchdynamicscenarioscan
benefitgreatlyfromtheabilityto,forexample,createastandardouterquery
inwhichtheinlineviewcanbesubstitutedbydynamiccode.Anendusermay
performasearchthatmightdrawdatafromanynumberofvarioussources
yetpresenttheoutputthroughafixedseriesofdataelements.Theinlineview
cansupportsuchasituation.
ALTERVIEW
TheALTERVIEWstatementisusedtoaccomplishanyofthefollowingtasks:
Create,modify,ordropconstraintsonaview
Recompileaninvalidview
Thesubjectofconstraintsonaviewisnotsomethingthatiscoveredonthe
exam.Oracledoesnotenforceviewconstraintswithoutspecialconfiguration
(seeDISABLENOVALIDATEinOracle’sdocumentation).
Recompilingaviewisastepyoumaywanttotakeifyou’vecreatedaview
andthenlaterperformedsomesortofmodificationontheunderlyingtableor
tablesuponwhichtheviewiscreated.Dependingonthechangeyoumaketothe
view’ssourcetable,theviewmayberenderedinvalidasaresult.Oncerendered
invalid,asubsequentattempttousetheviewwillresultinoneoftwooutcomes,
dependingonthenatureofthechangethatwasperformedtotheunderlying
table:
Outcome1Ifthechangeresultsinasituationwheretheoriginal
CREATEVIEWstatementwouldhavesuccessfulexecutedanyway,then
asubsequentstatementusingthatviewwillcausetheviewtobe
recompiledsuccessfully,andthestatementwillsuccessfullyexecuteas
thoughnoproblemeverexisted—becauseitdidn’t.
Outcome2Ifthechangeresultsinasituationwheretheoriginal
CREATEVIEWstatementwouldhavenotsuccessfullyexecuted,then
subsequentattemptstousetheviewwillfail.Anexampleofsucha
changewouldbetoalteranunderlyingtabletodropacolumnthatispart
ofaview’scolumnlist.
InChapter12we’llseehowyoucandeterminewhetheraviewisinvalidor
notbyqueryingthedatadictionary.
Analternativetoqueryingthedatadictionary,whichisnotalwaysavailable
toanapplication,istoissueanALTERVIEW…COMPILEstatement.This
statementcanbeusedtorecompileaninvalidview.Iftheviewcannotbe
recompiled,theALTERVIEW…COMPILEstatementwillsuccessfully
executewithamessagedeclaring“Warning:Viewalteredwithcompilation
errors.”Thedatadictionarywillshowtheviewasremaininginvalid.
Hereisanexampleofastatementthatrecompilesaview:
Youcannotchangeaview’sSELECTstatementwiththeALTER
VIEWstatement.Instead,youmustdropandre-createtheview.
Oncecompiledsuccessfully,theviewisbackinworkingcondition.Ifitdoes
notcompile,youknowthatthechangetotheunderlyingtablemayhave
fundamentallychangedthenatureoftheview’sstructure.Forexample,ifaview
queriesanamedcolumnfromanunderlyingtableandthatcolumnisrenamed
(ordropped,asIpointedoutearlier),thentherecompilationwillnotwork,and
youmayneedtore-createtheviewandreassessyourcode.
Inaddition,ifyousimplyattempttouseaninvalidview,itwillautomatically
compile.Ifitcanbecompiled,theattempttousetheviewwillbesuccessful,
withallelsebeingequal.However,ifitcannotberecompiled,thencontraryto
theALTERVIEW…COMPILEstatement,whichwouldexecutebutissuea
warning,anyattempttouseaninvalidviewthatcannotbeautomatically
recompiledwillresultinanerror.
Visible/InvisibleColumns
Viewsarebasedontables,andinOracle12c,atablecanhavecolumnsthatare
eithervisibleorinvisible.Howdoesthatimpactviews?Let’sstartbylookingat
theuseofinvisiblecolumnsintables.
InvisibleColumnsandTables
Thecolumnsinatablearevisiblebydefault.NewwithOracle12c,youcan
specifythatoneormorecolumnsbeinvisible.Here’sanexample:
NotethecolumnCONSTRUCTION_COST,whichisspecifiedas
INVISIBLE.Theothercolumnsarevisiblebydefault;onlythecolumn
CONSTRUCTION_COSTisinvisible.
So,whatdoesthismean?First,let’slookatdisplayingthetable’sstructure
withDESC.YoucandescribethetablewithDESCSHIP_ADMIN,andyouwill
seethetypicaltabledescription,butanycolumnspecifiedasINVISIBLEwillbe
omittedfromdisplay.
NotethatwithinOracle'sSQL*Plustoolspecifically,youcanusethe"SET
COLINVISIBLEON"statementtotemporarilyconfiguretheDESCstatement
toreturninvisiblecolumnsduringthatparticularSQL*Plussession.
YoucanuseINSERTwithatablethathasinvisiblecolumns,butyouhaveto
becareful.YoucanuseINSERTtoinsertvaluesintoaninvisiblecolumn,but
onlyifyouspecifythecolumnnames.IfyouomitthemintheINSERT,you’ll
getanerrormessage.Foranexample,seeFigure10-2.
FIGURE10-2 TheINSERTstatementandcolumnsthatarespecifiedas
INVISIBLE
NotethefirstINSERTstatementinthefigure,whichusestheshorthand
INSERTsyntaxthatomitsatable’scolumnsbeforetheVALUESclause;you’ll
getanerrormessageifaninvisiblecolumnispresentinthetable.Thisshorthand
syntaxisanimpliedreferencetoeverycolumninthetable.Inthiscase,the
SHIP_ADMINtablehasthreecolumns,butonlytwoarevisible.Thefinal
portionofthisfirstINSERTprovidesvaluesforthreecolumns,andthetablehas
threecolumns—butonlytwoarevisible.WiththeshorthandINSERTsyntax,
thisstatementfails.HadweusedashorthandversionofINSERTthatprovided
onlytwovalues—forthevisiblecolumns—thisstatementwouldwork.
Now,notethesecondINSERTstatement.Itdiffersfromthefirstonlyinthat
itspecifiesallthreecolumnnames,includingtheinvisiblecolumnname.This
secondINSERTexecutessuccessfully.
So,canyouinsertvaluesintotheinvisiblecolumnofatable?Theansweris
yes,providedthatyouspecifythecolumnnamesintheINSERTstatement.
Takenoteofthispattern;youwillseeitagain,asweturnourattentiontothe
useofinvisiblecolumnsandVIEWobjects.
InvisibleColumnsandViews
Rememberthataviewisanobjectbuiltonaqueryofoneormoretables.When
wespeakofaviewandinvisiblecolumns,wearetalkingaboutthecolumnsof
thetableortablesonwhichtheview’squeryisbased.Arethoseinvisible?Ifso,
thereareseveralissuestoaddress.
Asyoujustlearned,ifatablehasoneormorecolumnsspecifiedas
INVISIBLE,thenwildcardreferences(withtheasterisk)inanINSERT
statementwillnotrecognizetheinvisiblecolumn.Thesameissueappliesto
queriesusedtobuildaVIEW.
Forexample,let’sstartwiththesameSHIP_ADMINtablewejustcreated.
Remember,ithasthreecolumns,oneofwhichisinvisible.Italsonowhasone
rowofdata.SeeFigure10-3.
FIGURE10-3 TheSHIP_ADMINtablewithonerowofdata
Let’screatetwodifferentviewsontheSHIP_ADMINtable.
Forthefirstview,ourquerywilluseawildcardreferencetoallthetable’s
columns.Remember,thequeriedSHIP_ADMINtablehastwovisiblecolumns
andoneinvisiblecolumn.
SeeFigure10-4.Wecreatetheviewandthendescribeit.Theinvisible
columnisomittedfromtheview’sstructure.
FIGURE10-4 VW_SHIP_ADMINviewwithSELECT*andSELECT
columnlist
Next,weexecuteaSELECTstatementthatalsousesawildcardreferenceto
“all”thecolumns,andonlyvisiblecolumnswillbereturnedasoutput.The
invisiblecolumnisnotaccessible.EvenifweexecuteaSELECTthatnamesall
thecolumns,includinganyinvisiblecolumns,theinvisiblecolumnisnot
accessible;Figure10-4showstheresultsoftheattempt.
Eventhoughtheviewisbuiltonaquerythatusesawildcardreferenceto
“all”columnsintheSHIP_ADMINtable,onlythevisiblecolumnsareincluded.
Foroursecondview,let’sspecifytheinvisiblecolumnintheCREATEVIEW
statement’squery;seeFigure10-5.
FIGURE10-5 VW2_SHIP_ADMINviewwithSELECT*andSELECT
columnlist
Nowweseeadifferentoutcome.Thissecondviewisbasedonaquerythat
specifiesaninvisiblecolumnbyname.Inthissituation,theviewwillseethe
invisiblecolumns.Theinvisiblecolumnisreflectedintheview’sstructure.
ASELECTstatementonthissecondviewwillreturnvaluesfromthe
invisiblecolumn,whethertheSELECTstatement(ontheview)usesawildcard
referenceornot,asshowninFigure10-5.Thedifferenceistheuseofthe
wildcardinthequerythatisusedtocreatetheviewinthefirstplace.
Ifthequeryusedtocreatetheviewemploysawildcardcolumnreference,
invisiblecolumnsareignored,buttheviewwillbecreatedsuccessfully;itwill
simplyomittheinvisiblecolumn.
However,whenworkingwithatableconsistingofoneormoreinvisible
columns,itispossibletocreateaviewthatincludesthoseinvisiblecolumnsby
specifyingtheinvisiblecolumnnamesinthequeryusedtocreatetheview.The
resultisaviewwherethecolumnthatisinvisibleinthetableisvisibletothe
view,bothintheview’sstructureandininteractionswiththeviewitself,suchas
SELECTstatements.
CERTIFICATIONOBJECTIVE10.03
Create,Maintain,andUseSequences
Asequenceisanobjectthatispredominantlyusedforonepurpose:togenerate
dataforprimarykeycolumnsintables.Whilethatistheprimarypurposeofa
sequence,there’snothinginherentinthestructureofasequencetolimityouto
suchapurpose.Youcanuseasequencetogeneratenumericsequencesforany
reason.Butallasequencedoesisissuesequentiallyincreasing(ordecreasing)
numbers,accordingtotherulesyoudefinewhenyoucreatethesequence.
CreatingandDroppingSequences
Here’sasampleoftheSQLstatementtocreateasequence:
Thisexampleisacompletestatementandrepresentsthesimplestformofa
CREATESEQUENCEstatement.Thesyntaxisasfollows:
TherequiredCREATESEQUENCEkeywords
Therequirednameofthesequencethatyouspecify,accordingtothe
rulesofnamingdatabaseobjects
Notethatnothinginthecodetiesittoaparticulartableorotherdatabase
object—nothing,thatis,otherthanperhapsthechoiceofthename,whichisa
namingconventionweusebutisnotrequired.
Here’sthecompletesyntaxforasequence:
Thereareseveralsequence_optionsthatcaneachbespecified,separatedby
spaces,asdesired.Sequencescanbesettostartatanynumberandincrement—
ordecrement—byanynumber.Theycansequentiallygeneratewithoutceasing
orbegivenarangewithinwhichtheycontinuouslygeneratenewnumbers.They
canbegivenafixedseriesofnumberstogenerate,afterwhichtheycease
generatingnumbers.
Thesequenceoptionsincludethefollowing:
INCREMENTBYintegerEachnewsequencenumberrequested
willincrementbythisnumber.Anegativenumberindicatesthesequence
willdescend.Ifomitted,theincrementdefaultsto1.
STARTWITHintegerThisspecifiesthefirstnumberthatwillstart
thesequence.Ifomitted,STARTWITHdefaultstoMINVALUE(which
wewilldiscussinabit)forascendingsequencesorMAXVALUEfor
descendingsequences,unlessNOMINVALUEorNOMAXVALUEare
specifiedeitherexplicitlyorimplicitly(bydefault),inwhichcase
STARTWITHdefaultsto1.
MAXVALUEintegerThisspecifiesthemaximumnumberforthe
sequence.Ifomitted,thenNOMAXVALUEisassumed.
NOMAXVALUEThisspecifiesthatthereisnoMAXVALUE
specified.
MINVALUEintegerThisspecifiestheminimumnumberforthe
sequence.Ifomitted,NOMINVALUEisassumed,unlessaMINVALUE
isrequiredbythepresenceofCYCLE,inwhichcasethedefaultis1.
NOMINVALUEThisspecifiesthatthereisnoMINVALUE
specified.
CYCLEWhenthesequencegeneratorreachesoneendofitsrange,
restartattheotherend.Inotherwords,inanascendingsequence,once
thegeneratedvaluereachestheMAXVALUE,thenextnumbergenerated
willbetheMINVALUE.Inadescendingsequence,oncethegenerated
valuereachestheMINVALUE,thenumbergeneratedwillbethe
MAXVALUE.
NOCYCLEWhenthesequencegeneratorreachestheendofits
range,stopgeneratingnumbers.NOCYCLEisthedefault.Ifnorangeis
specified,NOCYCLEhasnoeffect.
Youcanalsodropasequence,likeso:
Here’sanotherexampleoftheCREATESEQUENCEstatement:
ThisSQLstatementperformsthesametaskastheearlierCREATE
SEQUENCEstatementyousaw.Thisexampleexplicitlyspecifiesthedefault
features.Youcanadjustthosedefaultsifyouwant,likethis:
Thisstatementwillstartwiththenumber10andincrementeachsuccessive
numberby5.
UsingSequences
Nowthatwe’vecreatedasequence,whatdowedowithit?Here’sanexample:
InthissampleINSERTstatement,weinsertarowintotheORDERStable
thatconsistsofthreevalues.ThefirstvalueisSEQ_ORDER_ID.NEXTVAL.
ThisreferenceistothesequencegeneratorSEQ_ORDER_IDalongwithits
pseudocolumnNEXTVAL,whichperformsthefollowingtwotasks:
Advancesthesequencegeneratortothenextavailablenumber
Returnsthatvalue
IfthesequencegeneratorSEQ_ORDER_IDhadjustbeencreatedandifit
wascreatedwiththedefaultvaluesfortheSTARTWITHandINCREMENT
BY,thentheinitialcalltoNEXTVALwillobtainthestartingvalueof1.Ifthe
nextcalltothesequencegeneratorisalsoacalltotheNEXTVAL
pseudocolumn,thenitwillbeadvancedagainby1toavalueof2.
Allsequencegeneratorshavetwopseudocolumns:
NEXTVALThisincrementsthesequencetothenextnumber,
accordingtothesequence’soriginalCREATESEQUENCEdirectives.It
alsoreturnsthenewlyincrementednumber.
CURRVALThisdisplaysthecurrentnumberthatthesequenceis
holding.However,thiscallisvalidonlyfromwithinasessioninwhich
theNEXTVALpseudocolumnhasalreadybeeninvoked.Youcannotuse
CURRVALinyourinitialcalltoanygivensequencegeneratorwithina
session.
TheadvantagetoCURRVALbecomesapparentwhenworkingwithasetof
tablesthatinvolvePRIMARYKEYandFOREIGNKEYrelationships.Consider
theentity-relationshipdiagram(ERD)inFigure10-6.
FIGURE10-6 ERDdiagramfortheCRUISE_CUSTOMERSand
CRUISE_ORDERStables
Let’screateacoupleofsequencegeneratorsforusewiththesetables.
Nowlet’sinsertsomenewrowsintothesetables.
Therearethreecallstooursequencegeneratorsintheprecedingcode:
Inline4wecallSEQ_CRUISE_CUSTOMER_ID.NEXTVALto
generateanewprimarykey.
Attheendofline9wecallthesamesequencegeneratorwiththe
CURRVALpseudocolumn.Thisdirectsthesequencegeneratortousethe
samevaluethatwasjustassignedintheline4call,ensuringthatour
PRIMARYKEY–FOREIGNKEYrelationshipbetweenthesetwotables
willberespected.
Atthebeginningofline9,wecall
SEQ_CRUISE_ORDER_ID.NEXTVALtogenerateanewprimarykey
fortheCRUISE_ORDERStable.
TheresultoftheseINSERTstatementsandusesofthesequencegenerators
helpstoensurethatwecanjoinourtablestoproducevalidandmeaningful
output.
Hereareafewimportantpointstokeepinmindaboutsequences:
YoucannotinvokeCURRVALinyourfirstreferencetoasequence
withinagivensession.NEXTVALmustbethefirstreference.
IfyouattempttoexecuteastatementsuchasanINSERTthat
includesthesequencereferenceNEXTVAL,thesequencegeneratorwill
advancetothenextnumbereveniftheINSERTstatementfails.
YoucannotinvokeCURRVALorNEXTVALintheDEFAULT
clauseofaCREATETABLEorALTERTABLEstatement.
YoucannotinvokeCURRVALorNEXTVALinthesubqueryofa
CREATEVIEWstatementorofaSELECT,UPDATE,orDELETE
statement.
InaSELECTstatement,youcannotcombineCURRVALor
NEXTVALwithaDISTINCToperator.
YoucannotinvokeCURRVALorNEXTVALintheWHEREclause
ofaSELECTstatement.
YoucannotuseCURRVALorNEXTVALinaCHECKconstraint.
YoucannotcombineCURRVALorNEXTVALwiththeset
operatorsUNION,INTERSECT,andMINUS.
YoucancallasequencepseudocolumnfromanywherewithinaSQL
statementthatyoucanuseanyexpression.
Thatlastpointisimportant—areferencetoasequencemustincludeits
pseudocolumn,andsuchareferenceisconsideredtobeavalidexpressionora
componentofanexpression.So,assumingyou’reworkingwithatable
PROJECTSthathasacolumnPROJECT_COST,youcouldinvokeasequence
SEQ_PROJ_COSTlikethis:
Thatisvalidsyntax.Whetherit’susefulornotisuptoyourbusinessrules.
ButSQLrecognizesthissyntaxandwillexecuteitsuccessfully.
Thebottomlineisthatreferencestothepseudocolumnsofsequencesare
validexpressions.
AnySQLstatementthatisexecutedwithacalltoasequence’s
NEXTVALpseudocolumnwilladvancethesequence,eveniftheSQL
statementfails.NotevenaROLLBACKwillresetasequence;eventhe
valueofthesequencegenerator’sCURRVALwillremainthesameafter
aROLLBACK.
CERTIFICATIONOBJECTIVE10.04
CreateandMaintainIndexesIncludingInvisible
IndexesandMultipleIndexesontheSameColumns
Anindexisanobjectyoucancreateinthedatabase,anditstoresasubsetofdata
fromatable.Theindexisitsownobject;itisstoredseparatelyfromthetable,
anditisconstantlymaintainedwitheveryINSERT,UPDATE,andDELETE
performedonthetable.Forexample,ifyouhaveatableSHIPSwithacolumn
CAPACITYandyoucreateanindexforthetableusingthecolumnCAPACITY,
thenboththetableandtheindexwillstore—separately—CAPACITYvalues.
EverytimeaDMLstatementchangesavalueintheSHIPStable’sCAPACITY
column,theindexwillalsobechangedaccordingly.
Thepurposeofanindexistosupportfasterqueriesonatable.Theindex
valuesarepresorted.Anindexcanbecreatedforonlyonetable,anditcanbe
createdononeormoreofthattable’scolumns—columnsthatyoudesignate.For
eachcolumn,theindexalsostorestheaddressofthatdatafromthesourcetable.
SQLcanthenusetheindexobjecttospeedupthequeryingofWHEREand
ORDERBYclauses.Forexample,ifaWHEREclausereferencesanyindexed
column(orcolumns),thenSQL(ormorespecifically,theoptimizer)will
automaticallyconsidertheindexasitdeterminestheoptimalquerystrategyfor
theSQLstatement.Theresultisthatqueriesmaybesignificantlyfaster,
dependingontheamountofdatainvolvedanddependingonthenumberof
indexesthatmaybeappliedtoatable.
Notethatwesaythatanindex“may”speedupperformance.SQLstatement
processingisperformedbyabuilt-infunctionknownastheOracleDatabase
optimizer.TheoptimizerdetermineshowbesttoprocessanygivenSQL
statementaccordingtoacombinationoffactors.Twoofthosefactorsarethe
presenceandstructureofindexes,butthereareotherfactorsaswell.AsSQL
developers,itisourjobtocreatethenecessaryresourcesfortheoptimizertodo
itsjob,recognizingthattheoptimizer,intheend,makesthefinaldecisionand
processesthestatement.Iwillspeakmoreabouttheoptimizerinafew
paragraphs.
YoucannotcreateanindexoncolumnsofLOBorRAWdatatypes.Given
that,youcancreateanynumberofindexes,limitedonlywithregardtocertain
aspectsofcolumnsets,whichIwillexplaininabit.However,asyouadd
indexes,you’lleventuallyreachapointofdiminishingreturns—eachindex
addedtoatablecanpotentiallyincreasetheworkloadonfutureINSERT,
UPDATE,andDELETEstatements.Butlet’sholdoffonthatdiscussionfora
bit.Fornow,wejustwanttosaythattheSQLsystemwillletyoucreateasmany
indexesasyouwant.
RememberthattheWHEREclausecanappearinaSELECT,UPDATE,or
DELETEstatement.AlsonotethataSELECTstatement,intheformofa
subquery,mayappearwithinanINSERTstatementoravarietyofstatements
thatcreateobjectssuchasTABLEorVIEW.AnINDEXobjectcanpotentially
benefitanyofthesesituations.
TheOracleDatabaseOptimizer
ThereasonwecreateanindexonatableissothattheOracleDatabaseoptimizer
canprocessSQLstatementsonthattablefaster.Butwhatistheoptimizer?
Theoptimizerisabuilt-infeatureintheOracledatabasethatiscrucialtothe
processingofeverySQLstatementissuedagainstthedatabase.EachSQL
statementhasthepotentialforgreatcomplexity,withinstructionstojoin,filter,
andtransformdatainavarietyofways.Theamountofdatatobeprocessedcan
varydramatically.Thiscomplexityintroducesahostofchallenges.The
optimizerisdesignedtohandlethosechallenges,anditperformsverywell.
Forexample,ifyouwanttoexecuteatypicalSQLstatementwithsomescalar
functionsandaWHEREclause,thenitwouldbeidealiftheWHEREclause
executesfirstandthescalarfunctionsareappliedlater.Why?Becausethe
WHEREclausecanfirstreducethenumberofrowstobeprocessed,leaving
onlythoserowsnecessaryonwhichtoapplythescalarfunctions.The
responsibilityofensuringthatsuchprioritizationisfactoredintoSQLprocessing
isbuiltintothedatabase,andtheoptimizeristhefeaturethatanalyzestheSQL
statementandestablishesanexecutionplanforprocessingthestatement.This
executionplanisaccessibletoyouviatheEXPLAINPLANstatement,whichis
notasubjectoftheexam,butisworthinvestigating.Ifyouareinterestedin
learningmoreabouttheoptimizer,lookfordocumentationontheEXPLAIN
PLANstatement,andyouwilllearnagreatdeal.
Forourpurposes,itisenoughtoknowthattheoptimizeristhebuilt-in
functionthatprocessesSQLstatementsandthat,aspartofthatprocessing,the
optimizeristhedecisionpointwherethedatabasedetermineswhetherandhow
toincorporateanindexintheexecutionofanygivenSQLstatement.
Yourgoalwhenbuildingindexesistocreateasetofusefulobjectstobe
leveragedbytheoptimizerinitsconstructionoftheoptimalexecutionplanfor
processingfutureSQLstatements,whateverthosemaybe.Yourjobasa
developeristoanticipatethetypicalusageofyourtableandthencreateindexes
thattheoptimizerwillbeabletousetobestexecutethosefutureSQL
statements.Understandinghowindexesworkisanecessarysteptoward
achievingthatgoal—andperformingwellontheexam.
Wewillrevisitthetopicoftheoptimizeraswediscussindexesinthe
followingsections.
ImplicitIndexCreation
IfyoucreateaconstraintonatablethatisoftypePRIMARYKEYorUNIQUE,
thenaspartofthecreationoftheconstraint,SQLwillautomaticallycreatean
indextosupportthatconstraintonthecolumnorcolumns,ifsuchanindexdoes
notalreadyexist.
Forexample,considerthefollowingSQLstatement:
ThisstatementwillcreatethetableSEMINARS,twoCONSTRAINTs,and
twoINDEXobjects.TheseINDEXobjectswillbenamedautomaticallybythe
SQLsystem.Laterinthissection,you’llseehowtomanuallycreatethese
indexes.Alsolater,inChapter12,you’llseehowyoucanquerythedata
dictionarytoseetheseimplicitlycreatedindexes,butfornow,here’saqueryon
thedatadictionarythatcanconfirmtheircreation:
Intheoutputofthisexample,youcanseethatthesystemassignedthenames
SYS_C009932andSYS_C009931totheindexes.
Asanalternative,youcanqueryelsewhereinthedatadictionarytoseethe
columnsthatareinvolvedintheindexes:
Intheseexamples,weappliedeachconstrainttoasinglecolumn.Hadwe
createdacompositePRIMARYKEYoracompositeUNIQUEconstraint,then
allcolumnsinvolvedintheconstraintwouldhavealsobeenindexedasa
compositeindex,andthecolumnnameswouldbelistedintheoutputofthis
secondqueryonthedatadictionary.
SingleColumn
HereisanexampleofaSQLstatementthatcreatesasingle-columnindex:
ThisSQLstatementcreatesasimpleindexcalledIX_INV_INVOICE_DATE,
onthecolumnINVOICE_DATE,inthetableINVOICES.Thiswillresultinan
objectthatsortsvaluesintheINVOICE_DATEcolumnoftheINVOICEStable.
Oncesuchanindexexists,queriesthatreferenceINVOICE_DATEinthe
WHEREclausemayreturnresultssignificantlyfaster.
Aswestatedearlier,theindexmayormaynotspeedtheperformanceofthis
SELECTstatement.Thedecisionisuptotheoptimizer.Rememberthatthe
optimizeranalyzesallSQLstatementstodeterminethebestcourseofactionfor
executingthestatement.ForanySQLstatementthatinvolvesatablesearchor
scan,suchasaquerywithaWHEREclauseoranORDERBYclause,the
optimizerwillconsiderwhetheranavailableindexonthequeriedtablewill
contributetowardfasterperformance.Theexistenceofanindexdoesnot
guaranteeitsuse;theoptimizerdetermineswhetherornottheindexwillbe
helpful.
Inourexample,theSELECTstatementagainsttheINVOICEStableincludes
aWHEREclausethatspecifiestheINVOICE_DATEcolumn.If,forexample,
alltherowsintheINVOICEStablehavethesamevalueforINVOICE_DATE,
theindexmaynotbeused—itmightcontributenoperformancebenefit.Onthe
otherhand,ifeachrowhappenstohaveauniqueINVOICE_DATEvalue,then
theindexmostlikelywillbeused.Thedifferencehastodowiththeconceptof
selectivity.Ifacolumntendstoincludedatathatislessrepetitiveandmore
unique,itissaidtohaveahigherdegreeofselectivity,andanindexonsucha
columnwouldbeattractivetotheoptimizer.Butifdatainagivencolumnis
relativelyrepetitive,itissaidtohavealowerdegreeofselectivityandwillbe
lesslikelytobeincludedinanindex.Theoptimizeristhefeaturethatmakesthat
decision.
InthesampleSELECTyoujustlookedat,iftheSQLoptimizerdeterminesto
usetheindex,andifevidenceisfoundintheindexthatarowofINVOICES
matchesthedesiredresult,theindexpointsthequerydirectlytotherow(or
rows)inthetable,andtheresultisachieved—muchfasterthanotherwisewould
haveoccurred.
Usage
TheOracleDatabaseoptimizerwillconsidertheuseofanindexinanyquery
thatspecifiesanindexedcolumnintheWHEREclauseorORDERBYclause,
dependingonhowtheindexcolumnisspecified.Therearesomeguidelinesfor
structuringyourSQLstatementsothattheoptimizerwillbemorelikelytoapply
theindex.Theguidelinesareasfollows:
Forbestresults,theindexedcolumnshouldbespecifiedina
comparisonofequality.
A“greaterthan”orsomeothercomparisonmaywork.
A“notequals”willnotinvokeanindex.
TheLIKEcomparisonmayinvokeanindexaslongasthewildcard
characterisnotintheleadingposition.Inotherwords,theexpression
LIKE'%SMITH'willnotinvokeanindex,butLIKE'SMITH%'may
invokeanindex.
Afunctiononacolumnwillpreventtheuseofanindex—unlessthe
indexisafunction-basedindex.(Function-basedindexesarenot
addressedintheexam.)
Furthermore,certaintypesofautomateddatatypeconversionswilleliminate
theindex.
Thedesignofanindexingschemeissomethingthatfallsunderthegeneral
categoryofperformancetuning.Thereisnosinglecomprehensiveapproachto
indexdesignforagivendatabaseapplication.Theapproachyoutakedepends
uponavarietyoffactors,includingtheamountandselectivityofdataexpected
andtheanticipatedfrequencyandtypesofthevariousSQLstatementsyou
intendtoexecuteonthedatabase.Asystemthatwillnotbequeriedmuchbut
willbeheavilypopulatedwithINSERTstatementswouldnotbenefitmuchfrom
indexes,sinceeachINSERTwillbeslowerasitupdatesthetablesandall
associatedINDEXobjects.Onsuchadatabase,infrequentqueriesmaynot
justifythecreationofINDEXobjectsandtheirassociatedperformancetrade-off.
Ontheotherhand,anapplicationthatinvolvesagreatdealofupdatingvia
UPDATEstatementswillbenefitfromthoughtfullydesignedindexes.
Theoptimizerwilldoeverythingitcantouseanindexforagiven
querywheretheindexisbeneficial.Itavoidsanindexonlyifitsuse
wouldbedetrimental,suchasinthecaseofatablewithalargenumber
ofrowswithanindexedcolumnthathaslowselectivity.
Anoldruleofthumbrecommendsnomorethanfiveindexesontheaverage
tableinatransaction-basedapplication.Butthat—again—dependsonintended
usage.I’veimplementedapplicationsinwhichsometableshavehadasmanyas
nineindexesapplied,andtheresultwaspositive.Thatwasasituationwhere
queriesonthetablewerenotusingprimarykeyssomuchbutinsteaduseda
varietyoftext-basedlookups.
Performancetuningisthesubjectofmanybooksandisatopicthatgoesfar
beyondthisbook—andtheexam.Fortheexam,it’simportanttounderstandthe
syntaxofcreatingindexes—bothsinglecolumnandcomposites—andtheir
intendedpurposeandgeneralusage.
Maintenance
IndexesareautomaticallymaintainedinthebackgroundbySQLandrequireno
effortonyourparttokeeptheirlookupdataconsistentwiththetable.However,
notethatthismeanseachfutureINSERT,UPDATE,andDELETEstatementyou
issuewillhavetoworkharder.EachDMLstatementthatmodifiesdatainatable
thatisindexedwillalsoperformindexmaintenanceasrequired.Inotherwords,
eachindexyouaddtoatableputsmoreworkloadoneachDMLstatementthat
affectsindexeddata.
Buildtheindexesthatcontributetoyourapplication’soverallperformance,
anddon’tbuildindexesunlesstheyarenecessary.Plantoperiodicallyreview
yourindexstructurestodeterminewhichindexesmaynolongerbeneeded;an
existingapplicationburdenedwithunnecessaryindexesmaybenefitfrom
removingindexes.
Thereareanumberofperformancetuningtoolsandtechniquestoassistwith
designingindexes.OneistheEXPLAINPLANfeature,whichrevealsthe
internalworkingsofagivenSQLstatementandprovidesinsightintohowSQL
willoptimizeagivenstatement,includingtheuseofindexesforagivenSQL
statement.It’sagreattool.Itisnotacertificationobjectivebutyoumaywant
toexploreoneoftheotherbooksintheOraclePresslinetolearnmoreabout
it.
Composite
Acompositeindexisanindexthatisbuiltontwoormorecolumnsofatable,
likethis:
Inthisexample,theresultisonesingleindexthatcombinesbothcolumns.A
compositeindexcopiesandsortsdatafrombothcolumnsintothecomposite
indexobject.Itsdataissortedfirstbythefirstpositioncolumn,secondbythe
secondpositioncolumn,andsoon,forallthecolumnsthatformthecomposite
index.
AWHEREclausethatreferencesallthecolumnsinacompositeindexwill
causetheSQLoptimizertoconsiderusingthecompositeindexforprocessing
thequery.Forexample,thisquerywouldencouragetheoptimizertousethe
compositeindexIX_INV_INVOICE_VENDOR_IDtomaximumadvantage:
NotethattheWHEREclauseintheprecedingexamplereferencesthe
columnsthatmakeupthecompositeINDEXobject.Next,considerthisquery:
Thisquery,whichreferencesthefirstcolumninthecompositeindex,also
invokestheindex.Thereasonisthatthecompositeindexinternallysortsdataby
thefirstcolumnfirstandthesecondcolumnsecond.Giventhat,theinternally
copiedandsorteddatafromtheindexedtableiscomparableinstructuretoa
single-columnindexbasedon—inthisexample—theVENDOR_IDcolumn.
Butnowconsiderthisquery:
Thisqueryreferencesthesecondcolumninthecompositequery,butnotthe
first.Thecompositeindexstructureisprimarilysortedonthefirstcolumnofits
structure,whichintheexamplewe’reworkingwith,isVENDOR_ID.Butthis
querydoesnotreferenceVENDOR_ID.Nevertheless,theSQLoptimizermay
stillconsiderapplyingtheindexbecauseofafeatureknownasskipscanning.
SkipScanning
Thankstoskipscanning,aWHEREclausethatreferencesanycolumnswithina
compositeindexmayinvoketheindexinitsprocessing.However,the
performancebenefitisnotidentical.Inskipscanning,SQLtreatsacomposite
indexasacombinationofseveralindexes.Howmany?Thatdependsonthe
levelofselectivitythatresultsintheindexingofthefirst(orleading)columnof
theINDEXobject.Ifthefirstcolumncontainsonlyafewuniquevalueswithina
largenumberofrows,theindex—ifused—maybeappliedarelativelyfew
numberoftimes.Ontheotherhand,iftheleadingcolumncontainsdatathatis
relativelyuniqueacrosstherows,thentheindex—ifused—maybereviewed
frequently.Inotherwords,askipscanwilldoanindexscanonceforeach
uniquevalueinthefirstcolumn.Thisisn’tquiteasbeneficialasasimpleone-
columnindex,anditsbenefitvaries,dependingontheuniquenessofvaluesin
thefirstcolumn.ButtheWHEREclausegainssomebenefitanyway.
ThepointisthataWHEREclausethatreferencessome,butnotall,ofthe
columnsinacompositeindexmayinvoketheindex,eveniftheleadingcolumn
isnotreferencedintheWHEREclause.However,includingtheleadingcolumn
mayresultinamoreefficientapplicationofthecompositeindexand,therefore,
afasterresulttothequery.
Unique
Auniqueindexisonethathelpsensurethatacolumninatablewillcontain
uniqueinformation.Thesyntaxforcreatingauniqueindexisasfollows:
ThisSQLstatementcreatesanindexthatwillensurethatdataenteredintothe
SSNcolumnofthetableEMPLOYEESisunique.
ThisisdifferentfromtheUNIQUEconstraintthatyoucanapplytoacolumn
onatable.However,notethatifyoucreateaPRIMARYKEYorUNIQUE
constraintonatable,auniqueindexwillautomaticallybecreatedalongwiththe
constraint.NotethattheUNIQUEconstraintismoreself-documentingwithin
thedatabase.Thatbeingsaid,OracleCorporationformallyrecommendscreating
uniqueindexestoenforceuniquenessinacolumnforbetterresultsinquery
performance.
Inpractice,avoidusingSocialSecuritynumbersas“unique”values.Inthe
realworld,itturnsoutthatSocialSecuritynumbers,whichareissuedbythe
U.S.federalgovernment,arenotnecessarilyunique,somethingthatmany
databaseprofessionalshavelearnedthehardway.OnceanSSNisnolonger
needed,itcanbere-issuedtosomeoneelse.Therearemanyclassicstoriesout
thereaboutapplicationdatabasesthatstartedemployingSSNsasprimarykeys
onatable,onlyfortheproductiondatabasetoencounterreal-worlddata
wheremorethanonepersonhasbeenissuedthesameSSN.It’sagreat
argumentforalwaysmakingyourprimarykeyswithsequence-generated
valuesandalessonthatSSNsintherealworldaren’treallyunique.Anddon’t
evengetmestartedontheissueofsecurityandthelawwithregardtoSSNs.
Unlessyouaresupportingagovernment-mandatedrequirementtoreport
somethingwithregardtoSocialSecuritytaxesorpayments,itisbesttoavoid
storingtheSSNatall—forsecurity,iffornootherreason.
Dropping
YoucandropanindexwiththeDROPINDEXstatement.Forexample,let’s
dropourIX_INV_INVOICE_DATEindex:
Notethatifyoudropatableuponwhichanindexisbased,theindexis
automaticallydropped.Ifyoure-createthetable,youneedtore-createtheindex.
VisibleandInvisibleIndexes
Anindexcanbemadetobevisibleorinvisibletotheoptimizer.Onlyavisible
indexisrecognizedbytheoptimizerand,therefore,availablefortheoptimizerto
useintheprocessingofaSQLstatement.Ifanindexismadetobeinvisible,the
optimizerwillomittheindexfromconsiderationwhencreatingtheexecution
planfortheSQLstatement.
Anindexisvisiblebydefault.Youmustexplicitlydeclareanindextobe
invisibleifthatisyourpreference.
(Thereisaninitializationparameter
OPTIMIZER_USER_INVISIBLE_INDEXESthatcanbesettoTRUEatthe
systemorsessionlevel.IfTRUE,theoptimizerwillconsiderallindexes
regardlessofvisibility—orinvisibility.However,initializationparametersand
thestatementstosetthemarenotthesubjectoftheexam.)
WhyUseanInvisibleIndex?
So,whywouldyoucreateanindexwhosesolepurposeinlifeistospeed
processingandthenrenderitinvisiblesothatitcannotbeusedtospeed
processing?Thefollowingsectionshighlightsomereasons.
IndexTestingonaTableMatureapplicationsmayhaveanumberofdifferent
indexesappliedtoatable.Alloftheseindexesrequiremaintenance.Thatmeans
everytimeanINSERT,UDPATE,orDELETEisexecutedonthetable,allof
thattable’sindexesalsohavetobeupdated(or“maintained”)withthesamedata
forconsistency.Therequisiteprocessingcarriesapriceintermsofperformance
andstorage.Isthisoverheadworthit?Theanswerdependsonwhetherthe
indexesareuseful.Onewaytofindoutistotemporarilychangeanindexto
invisibleandthenrunyourqueries.Theinvisibleindexwillbeignoredbythe
optimizer,givingyouanopportunitytoassesstheimpactofomittingtheindex
withouthavingtodropitaltogether.Isperformancedegradedwhenthe
optimizerignorestheindex?Ifnot,thentheindexisnotimprovingperformance.
YoucouldthenchoosetodroptheindexaltogetherandreducetheDML
maintenancecostassociatedwithitsexistence.
VISIBLE,INVISIBLE
ThekeywordsVISIBLEandINVISIBLEspecifythevisibilityofanindexinthe
CREATEINDEXstatement.Forexample,consideratablePORTS.
ThefollowingcodecreatesaninvisibleindexonthePORT_NAMEcolumn:
Alternatively,hereishowtocreatethesameindexasavisibleindex:
VISIBLEisthedefault.IfaCREATEINDEXstatementomitsthekeywords
VISIBLEorINVISIBLE,avisibleindexiswhatwillbecreated.
Iftheindexexistsandyouwanttoalterittobeinvisible,usethis:
Toalteranindexandmakeitvisible,usethis:
Iftheindexisalreadyinvisible(orvisible)andyousubmitanALTER
statementto“change”ittowhatitalreadyhappenstobe,thestatementwill
executesuccessfullywithnocomplaintorindicationthattheALTERwas
unnecessary.
ThedatadictionaryviewUSER_INDEXESincludesacolumnVISIBILITY
thatreportswhetheranindexiscurrentlyvisibleorinvisible.
Rememberthatanindexisvisiblebydefault,soifyouomittheVISIBLE
keyword,youstillgetavisibleindexatthetimeofindexcreation.
Thedatadictionaryusesuppercaseletterstorecordthenamesofall
tables,columns,views,andotherobjectsyoucreate,unlessyouenclose
thenameindoublequoteswhenyoucreatetheobject.
IndexAlternativesontheSameColumnSet
Youcancreateanumberofindexesonagiventable.However,foragiventable,
youarelimitedwhencreatingmultipleindexesonaparticularcolumnset,and
by“set,”wemeanasetofoneormorecolumnsforthattable.Tocreatemultiple
indexesonagivencolumnset,theindexesmustdifferwithregardtooneofaset
ofspecificcharacteristics.However,whileyoucancreatemultipleindexes
withintheselimitations,onlyoneofthoseindexobjectsmaybevisibleatany
pointintime.
Tocreatemultipleindexesonagivencolumnset,theindexesmustvarywith
regardtooneofthefollowingcharacteristics:
DifferentuniquenessYoucancreateauniqueindexonacolumnset
andanonuniqueindexonthesamecolumnset.
DifferenttypesTheindexeswehavelookedatsofarhavebeen,by
default,B-treeindexes.Youmayalsocreateabitmapindexbyadding
thekeywordBITMAPpriortothewordINDEX,asinCREATE
BITMAPINDEX,followedbytheappropriatekeywordstocompletethe
indexspecification.AB-treeindexisidealfortransactionalapplications
wherethefullsetofDMLstatementswillbecommonlyutilized.A
bitmapindexisoftenusedmoreinapplicationswhereheavieruseof
SELECTstatementsisanticipated.Forourimmediatepurposes,thepoint
isthatyoucancreateindexesonthesamecolumnsetiftheydifferwith
regardtoindextype.
DifferentpartitioningMultipleindexesmayexistonthesame
columnsetprovidedthatcertainpartitioningcharacteristicsaredifferent:
Partitioningtype(hashorrange)
Localversusglobalpartitioning
Partitioningversusnonpartitioning
Forthepurposeoftheexam,thepointyouneedtorememberisthatwhile
thesemultipleindexesonagivencolumnsetmayexistsimultaneously,onlyone
maybevisibleinthedatabaseatanygivenpointintime.Forexample,when
creatingmultipleindexesonagivencolumnset,anypreexistingindexesonthe
samecolumnsetmustalreadybeinvisible,orelsetheattempttocreateanew
visibleindexonthesamecolumnsetwillfail.
Onereasonfortogglingindexesbetweenvisibilityandinvisibilityistotune
applicationperformanceforvariouspurposes.Rememberthattheexistenceof
anindexdoesnotguaranteetheoptimizerwillutilizetheindex.However,
makinganindexinvisibleguaranteestheoptimizerwillignoretheindex.
Considerthesectionwejustreviewed.Youmightfinditadvantageoustotry
differenttypesofindexesonagiventypetooptimizeperformancefor
transaction-basedapplicationsversesheavyqueryingandanalytics.Thedetails
ofsuchconsiderationsarebeyondthescopeoftheexam;forourpurposes,itis
helpfultorecognizethatapplicationtuningisausefulreasontoemployinvisible
indexes.
Butrememberthatevenifanindexisinvisible,itisstillmaintained.Any
INSERT,UPDATE,orDELETEstatementprocessedonthetablewillalso
updatetheindex,whichisaperformancecost.Thisistruewhetheranindexis
visibleorinvisible.
CERTIFICATIONOBJECTIVE10.05
PerformFlashbackOperations
Oracle’sFlashbackoperationsconsistofanumberoffeaturesthatenableaccess
todatabasedataandobjectsintheirpaststate,includingobjectsthathave
alreadybeendropped.ThesefeatureshavenameslikeFlashbackTable,
FlashbackDrop,FlashbackQuery,andmore.ThetopicofOracle’sFlashback
operationsisquiteinvolved.Developingacompleteunderstandingofallofwhat
OracleofferswithFlashbackoperationsrequiresmorestudythanwhatis
requiredtopasstheexam.We’llprovidesomebackgroundinformationtogive
youanideaofwhatwearetalkingabout,andthenwe’lldiscussthespecific
Flashbackoperationsthatarerelevanttotheexamandtothischapter’sfocus,
whichistheoverallsubjectofmanagingschemaobjects.Thisbookwillpresent
whatyouneedtoknowfortheexam,butyoumaywanttocontinueyourstudy
ofFlashbackoperationsbeyondwhatisrequiredfortheexam.
Oneimportantnote:OracleFlashbackoperationsincludesomefeaturesthat
areavailableonlyintheOracleEnterpriseEdition.IfyouareusingtheStandard
Edition,youcanperformFlashbackQuery,butsomeofthefeaturesdescribedin
thissectionrequireEnterpriseEdition—suchasFlashbackTable.
Overview
Oracle’sFlashbackoperationsincludeavarietyofstatementsyoucanuseto
recoverobjectsand/orthedatacontainedwiththem,aswellasdependent
objectsanddata.ThesortoftasksyoucanaccomplishwithFlashback
operationsinclude
Recoveringcompletetablesyoumayhaveinadvertentlydropped
Recoveringdatachangeswithinoneormoretablesresultingfroma
seriesofDMLstatements
Performingdataanalysisondatathat’sbeenchangedoverperiodsof
time
Comparingdatathatexistedatonepointintimewithdatathat
existedatanotherpointintime
Performingqueriesasofapriortimeperiod
Flashbackoperationscansupportmultipleusersessionsgainingaccessto
historicaldatadynamically,onanytable(includingthesametables)atthesame
time,witheachusersessionpotentiallyaccessingdifferentpointsinthehistory
ofthetablesimultaneously,allwhilethedatabaseisupandrunninginfull
operationalmode.
SomeFlashbackoperationsrequirevariousconfigurationsteps;someofthose
configurationscanbeinvolvedandmightrequireinterventionbythedatabase
administrator.Theconfigurationstepsinvolvedcanaffectsystemparameters,
tableclauses,andafeatureofthedatabaseknownastheundosegments,which
haveapurposethatgoesbeyondFlashback.
RecoverDroppedTables
Inthischapter,we’refocusingonlyonmanagingschemaobjects.Withintheset
ofavailableFlashbackoperations,thefeaturethataffectsschemaobjectsasa
wholeistheFLASHBACKTABLEstatement.Thisstatementcanrecovera
previouslydroppedtableyouspecifyfromahistoricalpointintimethatyou
specify.However,therearelimitations.Forexample,youcannotflashbacktoa
pointpriortowhenthetable’sstructuremayhavebeenaltered.
Youcanidentifyapointintimeinavarietyofways:
Immediatelypriortowhenatablewasdropped
AspecifictimeidentifiedbyavalueofdatatypeTIMESTAMP
Aspecifictransactionidentifiedbythesystemchangenumber
(SCN)
Apredeterminedeventidentifiedbyadatabaseobjectknownasthe
RESTOREPOINT
Whenusedtorestoreatable,FLASHBACKTABLErestoresthedropped
tablewitheitheritsoriginalnameoranewnameyouprovidewiththestatement.
Italsorecoversanyindexesonthetableotherthanbitmapjoinindexes.All
constraintsarerecovered,exceptforreferentialintegrityconstraintsthat
referenceothertables—inotherwords,foreignkeyconstraints.Granted
privilegesarealsorecovered.
Note:FLASHBACKTABLEisnotcurrentlyavailableinOracleDatabase
StandardEdition.
ThebeginningsyntaxofaFLASHBACKTABLEstatementisasfollows:
TherequiredkeywordsFLASHBACKTABLE
Oneormoretablenames,separatedbycommas
TherequiredkeywordTO
Inotherwords:
Morethanonetablecanbeincludedinthelist.Additionaltablenamesmust
beseparatedbycommas:
That’sthebeginning.Thereareseveralwaystocompletethisstatement.Here
ishowyoucompleteitifyouwanttorecoveradroppedtable:
TherequiredkeywordsBEFOREDROP
TheoptionalkeywordsRENAMETO,followedbyanewnamefor
thetableifyouwanttorecoverthedroppedtableintoanobjectwitha
differentname
HereisanexampleofaSQLsessionwherewecreateatable,dropit,and
thenuseFLASHBACKTABLEtorestorethedroppedtable:
NotetheFLASHBACKTABLEstatementonline5.Itcombinesthe
beginning:
YoucannotrollbackaFLASHBACKTABLEstatement.
withthefollowing:
BEFOREDROP
ItomitstheoptionalRENAMETOandthenewname.
TheRecycleBin
TheFlashbackDropfeaturerecoverscompletetablesthatarestillretainedinthe
“recyclebin,”anditcandosoinspiteofthefactthatsuchachangeresultsfrom
theDROPTABLEstatement,which,bydefinition,isaDDLstatementand
thereforeinvolvesanimpliedCOMMIT.Inspiteofthis,wecanrecoverthetable
ifitisstillintherecyclebin.
TablesareputintotherecyclebinautomaticallybySQLwheneveraDROP
TABLEstatementisissued.Atable’sdependentobjects,suchasindexes,are
alsoplacedintotherecyclebin,alongwiththetable’sconstraints.
Therecyclebinisnotcountedasspacethatisusedbyagivenuseraccount.
Auseraccount’sdroppedobjectsareretainedinaseparaterecyclebinfor
eachuser.Youcaninspectthecontentsofyourownrecyclebinwiththe
followingquery:
Thatqueryisidenticaltothisone:
RECYCLEBINisasynonymforUSER_RECYCLEBIN.Inotherwords,the
precedingtwoqueriesareidentical.
ThereisaDBA_RECYCLEBIN,whichallowsuseraccountswithdatabase
administrator(DBA)privilegestoseealldroppedobjectsinthedatabase.
Ifyouruseraccounthasprivilegesonanobject,thenyouruseraccountwill
beabletoseetheobjectintherecyclebinintheeventitisdropped.
Youdon’tneedtoinspecttherecyclebinbeforeissuingaFlashback
statement.Butyoumightfindithelpful.
Therecyclebinisaffectedbythe“recyclebin”initializationparameterand
canbeturnedonoroffaccordinglywiththefollowingALTERSESSION
statements:
Bothofthesestatementstakeeffectimmediately.Theinitialstateofthe
recyclebinisdependentonthesettingforrecyclebinintheinitialization
parameterfile,whichiscontrolledbytheDBA.
SettingrecyclebintoONorOFFdetermineswhetheritwillbeused.Any
objectsalreadyintherecyclebinwillremaineitherway.Toremovethem,use
PURGE,whichisexplainedlaterinthischapter.
DependentObjects
Whenatableisrecovered,anyassociateddependentobjectsarealsorecovered,
includingthefollowing:
Indexes,exceptforbitmapjoinindexes
Constraints,butwithlimitations—forexample,restoringdropped
tablesdoesnotrecoverreferentialconstraints,meaningFOREIGNKEY
constraints
Otherobjectsthatwedon’tdiscussinthisbookandthatarenota
subjectoftheexam,suchastriggers
Objectsthathavethesamenamethataredroppedcanallberetrievedwith
Flashbackoperations.Forexample,ifatableVENDORSwasdroppedandthen
re-createdanddropped,therewillbetwoVENDORStablesintherecyclebin.
Thelastonedroppedwillbethefirstoneretrieved.
Objectssuchasindexeswillberecoveredwithsystem-assignednames,not
thenamestheywereoriginallygiven.Youcanrenameeachretrievedobjectwith
theRENAMETOclauseoftheFLASHBACKTABLEstatementasitis
retrieved.Asofthiswriting,renamingretrievedobjectsisbeyondthescopeof
theexam.
StatementExecution
TheFLASHBACKTABLEstatementoperatesasasinglestatement.Ifitfails,
nothinginthestatementsucceeds.Inotherwords,ifthere’sanattempttorestore
threetablesinasinglestatementandthethirdattemptiserroneousforwhatever
reason,noneofthetableswillberestored.
PURGE
ThePURGEstatementpermanentlyremovesthelatestversionofagivenitem
fromtherecyclebin—forexample,topermanentlyremovetheHOUDINItable
fromtherecyclebinsothatitcannotberecovered:
PURGETABLEHOUDINI;
Afterexecutingthisstatement,thetableHOUDINIcannotberecoveredwith
theFLASHBACKTABLEstatementweusedearlier.
NotethatthetablemusthavefirstbeendroppedforPURGEtoexecute
successfully.PurgingmaybeperformedautomaticallybytheOracledatabase’s
ownautomaticspacereclamationoperations.Ifthathappens,thetableisnotin
therecyclebinandcannotberecoveredwithFlashbackoperations.
Youcanalsochoosetopurgetheschema’srecyclebinentirely.
PURGERECYCLEBIN;
Theresultwillbetopurgeallobjectsintheschema’srecyclebin.Topurge
therecyclebinoftheentiredatabase,usethis:
Thepreviousstatementwillexecutesuccessfullyiftheschemahasthe
SYSDBAprivilege.YoucanalsoDESCRIBEandSELECT*fromthe
RECYCLEBINandDBA_RECYCLEBIN.
RecoveringDataWithinExistingTablesoverTime
ThissectiondiscussessomeadditionalwaystocompletetheFLASHBACK
TABLEstatement.
InadditiontoperformingaFlashbackoperationtorestoreadroppedtable,
youcanflashbackanexistingtabletoaspecificpointintime,showingitsstate
priortoanycommittedchangesthatmayhavebeentransactedsincethepointin
timeofinterest.
Thesyntaxcantakeanyofthesethreeforms:
Therecommendedformofthesethreeisthefirst:thesystemchangenumber.
ThisisthemechanismthatisrecommendedbyOracleforidentifyingpointsin
timeinthedatabase.Forexample,let’srevisitourtableHOUDINI.
Let’sreviewtheprecedingcode:
Line3:Wecommitourchangetothetable.
Line4:Thisisastatementthatsuspendsprocessingfor15seconds.
Thechoiceof15secondsisarbitrary;theintenthereistoallowsome
timetopass.
Line6:Wecommitthedeletionofonerow.
Line8andline9:Thisstatementattemptstorestorethetableto
whereitwas20secondsearlier.Notethatline9containsnothingmore
thananexpressionoftheTIMESTAMPdatatype,whichinthiscaseisa
calltotheSYSTIMESTAMPfunctionminusa20-secondinterval.The
SYSTIMESTAMPfunctionreturnsthecurrenttimeasdefinedbythe
Oracledatabaseserver’soperatingsystem.Followingthecalltothe
functionisthesymbolforsubtraction—theminussign—followedbya
literalvaluerepresentingatimeintervalof20seconds.
So,whatistheresultofthisseriesofstatements?Hereitis:
Whatiswronghere?TheproblemisthatthecapabilitytoperformFlashback
operationstorestoreanexistingtabletoanolderstateisnotacapabilitythat
existsbydefault.ItonlyworksontableswheretheROWMOVEMENTfeature
hasbeenenabled.Here’showtocreatethetablewithROWMOVEMENT
enabled:
ToenableROWMOVEMENTonatablethat’salreadybeencreated,usethis:
IfweweretogobackandredoourearlierseriesofstatementswithROW
MOVEMENTenabledonthetable,ourFLASHBACKTABLEstatementwould
workperfectly,andwe’drestoreourtabletoitsoriginalstate.Onceit’srestored,
wecouldquerythetableandseeallthedatainthattableasitexistedatthetime
wespecifiedinourFLASHBACKTABLEstatement.
Datarestorationis“permanent.”ItinvokesanimplicitCOMMITsothatthe
restoreddataiscommitted.NotethatROWMOVEMENTisn'trequiredwith
flashbackTOBEFOREDROP.
Limitations
YoucannotusetheFLASHBACKTABLEstatementtorestoreolderdatatoan
existingtableifthetablehasbeenstructurallyalteredwiththeALTERTABLE
statementinsuchawaythatitcan’tacceptthefulldefinitionofolderdata.For
example,ifacolumnhasbeendroppedoracolumn’sdatatypechanged,the
FLASHBACKTABLEstatementwon’tsuccessfullyrestoretheolderdata.
MarkingTime
Thereareseveralwaystoidentifythepointatwhichyouwanttorestoredatain
thedatabase.Yousawthreeintheprevioussection,andI’lldiscussthemabit
morehere.
SCN
Thesystemchangenumberisanumericstampthatthedatabaseautomatically
incrementsforeverycommittedtransactionthatoccursinthedatabase.This
includesbothexplicitandimplicitcommits,forallexternalorinternal
transactions.TheSCNisautomaticallymanagedbythedatabaseinrealtime.
EverycommittedtransactionisassignedanSCN.
IfyouwanttodeterminethecurrentSCNatanygivenmomentinthe
database,usethefunction
DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBER.Here’san
example:
Thisexampleshowstherequestandtheanswer.Inthiscase,theSCNis
5896167.Ifyouweretohesitateafewsecondsandrunthesamestatementin
line1again,youmightgetadifferentvaluereturnedforSCN.
TheSCNcanalsobefoundwiththequerySELECTCURRENT_SCNFROM
V$DATABASE,whichisaqueryofthedatadictionary.We’lldiscussthedata
dictionaryinChapter12,butfornow,notethatOracleofficiallyrecommends
thatifyourgoalistoobtainanSCNfromwithinanapplicationorany
comparablecode,thenyoushouldusetheDBMS_FLASHBACK
.GET_SYSTEM_CHANGE_NUMBERfunctionthatwedemonstratedearlier.
Thisrecommendationimpliesthatyoushouldsteerawayfromtappingthe
V$DATABASEviewfortheSCNnumber.The
DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBERfunctionisa
functionwritteninthePL/SQLlanguage,anditispartofthe
DBMS_FLASHBACKpackage.SeeOracle’sreferencemanualonPL/SQL
packagesifyouwanttolearnmore—butyoudon’tneedtodothatforthe
exam.
Eachtimeatransactioniscommittedinthedatabase,theSCNisincremented
andstoredwitheachrowineachtable.
TheSCNforagivenrowcanbefoundinthepseudocolumn
ORA_ROWSCN.Asisthecasewithanypseudocolumn,itcanbeincludedas
anexpressioninanySELECTstatement.Forexample,thefollowing:
returnseachrowinthetableHOUDINI,alongwiththevaluesintheVOILA
column,aswellastheassignedSCNnumberforeachrow.
Timestamp
ATIMESTAMPvaluespecifiesapointintime.TheTIMESTAMPdatatype
storestheyear,month,day,hour,minute,second,andfractionalseconds.A
literalvaluemaybeconvertedtotheTIMESTAMPdatatypewiththe
TO_TIMESTAMPfunction,likethis:
ThisexampleshowstheTO_TIMESTAMPfunction,aliteralvalue,anda
formatmaskthatdefinesthelocationwithintheliteralvalueofeachcomponent
thatformsavalidTIMESTAMPvalue.Notetheuseoffractionalseconds,where
morethantwodigitsareaccepted(uptosix).AlsorecallthatMIistheformat
maskforminutes—notMM,whichistheformatmaskformonths.
TheFLASHBACK_TABLEfunctioncanuseaTIMESTAMPvalueto
specifyapointintimeinthedatabasetowithinthreesecondsofaccuracy.
Ifaspecificpointinthedatabaseisneeded,don’tuseTIMESTAMP—use
SCNinstead.
Ifyouattempttoflashbacktoapointintimeatwhichthedatabasedidnot
exist,you’llgetanerrorindicating“invalidtimestampspecified.”
Ifthetimeyou’rereferencingcloselyalignswithatimeatwhichtheobjector
datadidn’texist,andtheSCN/timestampcorrelationmissesyourtargetand
overshootsintoatimeframeinwhichtheobjectordatadidn’texist,youmay
getanOracleerror.
Youcanuseacombinationofoneormoreconversionfunctionstoaddress
thisdiscrepancy,aswediscussinthenextsection.
ConversionFunctions
SCNnumberscanbeconvertedintotheirequivalentTIMESTAMPvalues,and
viceversa.Theconversionsarenotexact,however,becausetheSCNand
TIMESTAMPvaluesdonotrepresentmomentsintimethatareprecisely
identical.
Theconversionfunctionsare
SCN_TO_TIMESTAMP(s1)TakesanSCNexpressionasinput;
returnsaTIMESTAMPvalueroughlycorrespondingtowhentheSCN
wasset
TIMESTAMP_TO_SCN(t)TakesaTIMESTAMPexpression
representingavalidpastorpresenttimestampasinput;returnsanSCN
valueroughlycorrespondingtowhentheTIMESTAMPoccurred
Forexample,let’sperformtwoseparateconversionsoftimestampvaluesto
SCNvalues:
Inthisexample,weconvertthecurrenttimestampvalue,asdefinedby
SYSTIMESTAMP,toitsSCNequivalent.Wealsoconvertadateinthepastto
itsSCNequivalent.Thefirstcolumn’saliasisNOW;thesecondcolumn’salias
isNOT_NOW.
Notethatanytimereferencedmustbewithinarangethatisrelevanttothe
database.Inotherwords,thefunctionrecognizestimesthatapplytowhenever
thedatabaseinstallationhasbeeninexistence.
Thereisnotadirectone-to-onerelationshipbetweentimestampsandSCN
values.Forexample,supposeyoutakeavalidSCNvalueandconvertit.
Notewhathappenshere:oneSCNgoesin,andaslightlydifferentSCNis
ultimatelyreturned.
Foranyworkeffortinwhichyourequireprecisioninspecifyingtiming,
OraclerecommendsusingSCNnumbersandobtainingthemwiththe
DBMS_FLASHBACKpackagedfunction
GET_SYSTEM_CHANGE_NUMBER,whichwereviewedearlier.Alsonote
thatifyouwanttouseFLASHBACKtorestoretoaspecificpoint,itis
importantthatyouobtainthatpointprecisely.Onewaytodothatisthe
RESTOREPOINTobject,whichwediscussnext.
RESTOREPOINT
Arestorepointisanobjectinthedatabaseyoucreatetorepresentagiven
momentinthedatabase.ThatmomentcanbeidentifiedbyaTIMESTAMPvalue
oranSCN.
Here’sanexampleoftheCREATERESTOREPOINTstatement:
Onceexecuted,youcanusethisasarestorepointrepresentingthemomentat
whichtheCREATERESTOREPOINTstatementwasexecuted.Youcanreferto
therestorepointeitherlaterinthecurrentsessionorinalatersession:
ThisstatementrestorestheHOUDINItabletothepointintimethatcorrelates
tothe“balance_acct_01”restorepoint.
WhenyounolongerneedtheRESTOREPOINT,youcandropit:
Youcanfindexistingrestorepointswiththedatadictionaryview
V$RESTORE_POINT.Notethatusersdonot“own”RESTOREPOINTobjects;
theirscopeistheentiredatabase.Theyexistuntiltheyaredroppedorageoutof
thecontrolfile.
NewtoOracle12cistheabilitytocreateamultitenantcloudarchitecturethat
includescontainerdatabasesandpluggabledatabases,butthosetopicsare
beyondthescopeoftheexam.Itisnotpossibletocreatearestorepointfrom
withinapluggabledatabase.Butyoucancreatearestorepointinacontainer
database.Also,rememberthattheexecutionofaDDLstatementincludesan
impliedCOMMIT.CREATERESTOREPOINTisnoexception.ItisDDL,
andthereforeitsexecutionresultsinaCOMMITtothedatabase.
CERTIFICATIONSUMMARY
Tablesstoreallthedatainadatabase.ViewsarenamedSELECTstatements.
Indexesactjustlikeanindexinabook;theyprovideaseparatelystoredsorted
summaryofthecolumndatathatisbeingindexed,alongwithaddressing
informationthatpointsbacktothesourcetable.Sequencesprovideamechanism
tocountoffprimarykeyvalues.
Viewsareobjectsthatnameaqueryandstorethequeryinthedatabase.
Viewsdonotstoredata.Theylookandactliketables.Viewsmaybebuiltwith
simpleorcomplexSELECTstatements.GROUPBY,HAVING,joinqueries,
andmoreareallpossibleinaVIEWobject’sSELECTstatement.
ASELECTstatementcanbeusedtoqueryaviewjustasitwouldbeusedto
queryatable.ButINSERT,UPDATE,andDELETEstatementswillworkonly
withcertainviews,notallofthem—itdependsonwhethertheview’sstructure
allowsappropriateaccesstothetableortablesuponwhichtheviewisbased.
AnyDMLstatementwillworkwithaviewbasedonasingletable,providedthat
therequiredcolumnsareallincludedintheselectlistoftheSELECTstatement
usedtocreatetheview,thattherowsoftheviewarenotaggregaterows,and
thatallofthetable’sconstraintsarehonored.Aviewisnotnecessarilyrequired
toincludecolumnsthatarerequiredbytheview’sunderlyingtable,butifthe
viewomitssuchcolumns,thenanINSERTstatementcannotaddtotheviewa
valuethatisrequiredbytheunderlyingtable;inaddition,theconstraintsonthe
underlyingtablewillrejecttheINSERT,anditwon’tworkforthatview.
AnySELECTstatementusedtocreateaviewmusthaveclearlydefined
columnnames.Complexexpressionsmustbeassignedacolumnalias;thiswill
becomethenameofthecolumnintheresultingviewobject.
Aninlineviewisavariationonasubquery,inwhichaSELECTstatement
replacesatablereferenceinaFROMclauseofanyDMLstatement.Aninline
viewmustbeenclosedinitsownsetofparentheses.Onceincorporatedina
DMLstatement,theinlineviewbehavesjustlikeaviewobjectwouldbehave.
Iftheunderlyingtableismodified,theviewmayrequirerecompilationusing
theALTERVIEW...COMPILEstatement.
Aviewisbuiltwithaquery,andthatquerymayspecifythenamesof
invisiblecolumnsinatable,assumingthattableconsistsofinvisiblecolumns.
Anyinvisiblecolumnsinthequeriedtablethatarespecifiedintheview’squery
willbeaccessibletoDMLstatementsexecutedagainsttheview.
Viewscanbeusedtohidecomplexityinqueries.Theyarebeneficialfor
creatingaseriesofqueries,onebuiltonanother.Bycreatingaqueryasaview
andthenpublishingaccesstothatview,thedevelopercanretaintheabilityto
laterchangethatqueryonwhichtheviewisbuiltsothatthechangeisreflected
intheview.
Sequenceobjectsarecounters.Theydispensenumbersaccordingtothe
parametersestablishedwhenthesequenceisfirstcreated.
SQLautomaticallydefinespseudocolumnsforeachsequence.The
NEXTVALpseudocolumnincrementsthesequencetothenextavailablenumber
asdefinedinthesequence’sparametersdefinedatthetimethesequenceis
created.TheCURRVALpseudocolumnreferstothelastNEXTVALreference
producedinagivensession.Inanysessionwithasequence,theNEXTVAL
pseudocolumnmustbereferencedbeforetheCURRVALpseudocolumncanbe
referenced.Areferencetoasequencepseudocolumnisavalidexpressionand
canbeinvokedinmanyplaceswhereexpressionsareallowed,withcertain
restrictions.
Anindexisanobjectthatstoresasubsetofpresortedinformationfroma
tableandmaybereferencedautomaticallybySQLtospeeduptheprocessingof
agivenSQLstatement,dependingonhowthatSQLstatementisstructuredand
howtheOracleDatabaseoptimizerchoosestobuilditsexecutionplan.Anindex
canbebuiltononeormorecolumnsinatable.Oncecreated,ifaSQL
statement’sWHEREorORDERBYclausereferencestheindexedcolumn(or
setofcolumns),theoptimizermayusetheindexinitsexecutionplantospeed
uptheprocessingofthestatement.Anindexthatisbuiltonmultiplecolumnsis
knownasacompositeindex.AUNIQUEINDEXcanbeusedtoenforcea
uniqueruleonacolumn.Anindexcanberenderedinvisibletopreventthe
optimizerfromincludingtheindexforconsiderationwhenformingthe
executionplan.
Indexobjectssupportapplicationperformancetuning.Indexescanbebuilton
oneormorecolumnsofatable;multicolumnindexobjectsareknownas
compositeindexes.WhenaqueryreferencesindexedcolumnsinitsWHERE
clause,SQLwillconsiderusingtheindexaspartofitsprocessingstrategy,and
theresultsmaybereturnedmorequickly.
Flashbackoperationscanrestoredatatoapreviouspointintime,withsome
limitations.Thepointtowhichyourestoredatacanbeidentifiedusingvaluesof
datatypeTIMESTAMP,SCN,orRESTOREPOINT.Tablesthathavebeen
droppedbutthatarestillintherecyclebincanberecovered.Anytablethat’s
beenpurgedfromtherecyclebinisgoneforgood.Datathat’sbeenchangedin
existingtablescanberestoredtosomepreviouspointintime,providedthatthe
table’sstructurehasn’tbeenchangedinsuchawaythatthetableisnolonger
abletoreceivetherestoreddata,suchasperhapshavinghadacolumndropped.
✓TWO-MINUTEDRILL
DescribeHowSchemaObjectsWork
Tablesstoreallthedatainadatabase.
ViewsarenamedSELECTstatements.
YoucanselectfromaviewwithSELECT.
Youmaybeabletoinsert,update,anddeletefromaview,
dependingontheview’sstructure.
Anindexspeedsqueriesonatablebycreatingapresortedlookup
listforthetable’sindexedcolumns,alongwithanaddresspointerback
totheindexedtable.
Sequenceskeeptrackofnumbercounterstomakethejobofadding
primarykeysandotheruniquevalueseasier.
CreateSimpleandComplexViewswithVisible/InvisibleColumns
AVIEWisaSELECTstatementthatisstoredinthedatabaseand
assignedaname.
ThecolumnsandexpressionsoftheSELECTstatementusedto
createaviewbecomethecolumnsoftheVIEW.
YoucanuseSELECTstatementsonviewsjustasyouwoulda
table.
YoucanuseINSERT,UPDATE,and/orDELETEstatementson
someviews,dependingontheconstraintsoftheview’sunderlyingtable
ortables,aswellasotherissuessuchaswhethertheview’sSELECT
statementincludesaggregatefunctions.
Aninlineviewisasubquerythatreplacesatablereferenceina
FROMclauseofaDMLstatement.
TheVIEWcanbetreatedlikeatable,withsomelimitations.
AVIEWbasedonatablethatissubsequentlyalteredmayrequire
recompilationwiththeALTERVIEW...COMPILEstatement.
AVIEWcanbebasedonatableconsistingofoneormoreinvisible
columns.
AVIEWcanincludeatable’sinvisiblecolumnsinitsstructureby
namingtheinvisiblecolumnsintheVIEW’squery.
Create,Maintain,andUseSequences
ASEQUENCEisanobjectthatdispensesnumbersaccordingtothe
rulesestablishedbythesequence.
ASEQUENCEspecifiesthestartingnumber,theincrement(which
canbepositiveornegative),andanoptionalrangeofvalueswithin
whichthesequencecangeneratevalues.
Thestartingpointcanbewithintherangeoratoneendofthe
range.
SEQUENCESareidealforpopulatingprimarykeyvalues.
TheNEXTVALpseudocolumnofasequencereturnsthenext
availablenumberinthesequenceandmustbethefirstreferencetothe
sequenceinanygivenloginsession.
TheCURRVALpseudocolumncanreturntheexistingvalueas
alreadydefinedbyNEXTVAL;itcanbereferencedinasessiononly
aftertheNEXTVALreferencehasoccurred.
Apseudocolumnreferencetoasequenceisavalidexpressionand
canbereferencedanywherethatavalidexpressionisallowed.
IfavalidsequencereferencetoNEXTVALoccurswithinaDML
statementthatfails,thesequencestilladvances.
CreateandMaintainIndexesIncludingInvisibleIndexesand
MultipleIndexesontheSameColumns
AnINDEXobjectisbuiltononeormorecolumnsinatable.
TheINDEXstoresdatafromitstable’scolumnsonwhichitisbuilt
andpresortsthatdatainordertospeedfuturequeries.
WhentheDMLstatementsINSERT,UPDATE,andDELETEare
executedonanindexedtablesothattheindexeddataischanged,the
indexisautomaticallyupdatedbyOracle,thusaddingtotheworkloadof
theDMLstatements.
INDEXobjectsarebuiltononeormorecolumns.Multiple-column
indexesarecompositeindexes.
YouusethekeywordsVISIBLEandINVISIBLEtospecifythe
visibilityofanINDEX.ThedefaultisVISIBLE.Youcanspecifythe
visibilityofanindexinCREATEINDEXandALTERINDEX
statements.
PerformFlashbackOperations
FLASHBACKTABLEcanbeusedtorestoreatablethathasbeen
dropped.
Ifatablehasbeendropped,itgoesintotherecyclebin.
Youcaninvestigatethecontentsoftherecyclebintodetermine
whatobjectsareavailableforusebyFlashbackoperations.
Onceanobjecthasbeendropped,ifitisalsopurgedwiththe
PURGEstatement,itisnolongerabletoberecoveredwith
FLASHBACKTABLE.
Inadditiontorestoringadroppedtable,theFLASHBACKTABLE
statementcanbeusedtorestoredatawithinthetableasofaparticular
timeinthedatabase.
Timeinthedatabaseismarkedbyeitherasystemchangenumber,a
RESTOREPOINT,oratimestamp.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
DescribeHowSchemaObjectsWork
1.Thedatabaseobjectthatstoreslookupinformationtospeedup
queryingintablesis:
A.ROWID
B.INDEX
C.VIEW
D.LOOKUP
2.ASEQUENCEis
A.Partofatable
B.Usedexclusivelytocreateprimarykeyvalues
C.Istheonlywaytopopulateprimarykeyvalues
D.Noneoftheabove.
3.Alldatabasedataisstoredin:
A.TABLES
B.TABLESandVIEWS
C.TABLES,VIEWS,andSEQUENCES
D.Noneoftheabove
CreateSimpleandComplexViewswithVisible/InvisibleColumns
4.WhichofthefollowingSQLstatementscanalwaysbeexecutedon
anyVIEWobject?(Chooseallthatapply.)
A.SELECT
B.INSERT
C.DELETE
D.UPDATE
5.Reviewthefollowingillustration:
NowreviewthefollowingSQLcode:
WhatwillresultfromanattempttoexecutethisSQLcode?
A.Thestatementwillfailbecauseofanerrorinline3.
B.Thestatementwillfailbecauseofanerrorinline6.
C.Thestatementwillfailbecauseofanerrorinline7.
D.Thestatementwillexecute,andtheviewwillbesuccessfully
created.
6.Reviewtheillustrationfromquestion5andthefollowingSQLcode:
Whatcanbesaidofthiscode?
A.Aftertheviewiscreated,avalidSELECTstatementwillwork
onthePROJECTS_ROLLUPview,butanINSERTwillnot.
B.Aftertheviewiscreated,avalidSELECTandvalidINSERT
statementwillworkonthePROJECTS_ROLLUPview.
C.Theattempttocreatetheviewwillfailbecauseyoucannot
createaVIEWwithaSELECTstatementthatusesaGROUPBY
clause.
D.Theattempttocreatetheviewwillfailbecauseyoucannot
createaVIEWwithaSELECTstatementthatisajoin.
7.Reviewtheillustrationfromquestion5andthefollowingSQLcode:
WhatwillresultfromanattempttoexecutethesetwoSQLstatements?
A.TheCREATEstatementwillfailbecauseitomitsthePURPOSE
columnfromthePROJECTStable.
B.TheINSERTstatementwillfailbecauseofanerroronlines9
and10.
C.TheINSERTstatementwillfailbecausethePROJECT_COST
valuebeinginsertedisnotconsistentwiththeWHEREclauseonline
4.
D.TheCREATEandINSERTstatementswillsuccessfullyexecute.
Create,Maintain,andUseSequences
8.WhichofthefollowingkeywordscannotbeusedwiththeCREATE
SEQUENCEstatement?
A.CYCLE
B.MAXVALUE
C.INCREMENT
D.JOIN
9.Reviewthiscode:
NotethatthefirstINSERTstatementisattemptingtoenterastring
literalof'NOTANUMBER'intoacolumndeclaredwithanumericdata
type.Giventhat,whatwillbetheresultoftheseSQLstatements?
A.OnerowaddedtotheSHIPStable,withaSHIP_IDvalueof1.
B.OnerowaddedtotheSHIPStable,withaSHIP_IDvalueof5.
C.TworowsaddedtotheSHIPStable.ThefirstSHIP_IDis1;the
secondis5.
D.TworowsaddedtotheSHIPStable.ThefirstSHIP_IDis
NULL;thesecondis5.
10.Reviewthiscode:
WhatwillresultfromtheseSQLstatements?
A.TheSELECTstatementwillfailbecausethesequencecanbe
referencedonlyinanINSERTstatement.
B.TheSELECTstatementwillfailbecauseyoucannotreference
theCURRVALpseudocolumnofasequenceuntilafteryouhave
referencedNEXTVALforthesequenceinasession.
C.TheSELECTstatementwilldisplayavalueof1.
D.TheSELECTstatementwilldisplayavalueof3.
CreateandMaintainIndexesIncludingInvisibleIndexesand
MultipleIndexesontheSameColumns
11.Choosethebestanswerfromthechoicesbelow.Anindex:
A.Storesallthedatafromallthecolumnsinanygiventableina
separateobjectandsortsthedataforfasterlookups
B.MayimprovetheperformanceofanUPDATEstatementthat
usesaWHEREclause,iftheWHEREclauseperformsanequality
comparisononanindexedcolumninatable
C.RequiresaseparateINSERTstatementeachtimeyouadddatato
atable—onetimetoaddanewrowtothetable,anothertimetoadd
thecorrespondingandnecessarydatarequiredbytheindex
D.OnlybenefitsaSELECTstatementiftheSELECTreturnsdata
thatisindexed
12.ReviewthefollowingseriesofSQLstatements:
Assumingtherearenoobjectsalreadyinexistencenamed
SUPPLIES_01orSUPPLIES_02priortotheexecutionofthepreceding
statements,whatdatabaseobjectswillresultfromthesestatements?
A.AtablecalledSUPPLIES_02andnothingelse
B.AtablecalledSUPPLIES_02andanindexcalledIX_SU_02
C.AtablecalledSUPPLIES_02andtwoindexescalledIX_SU_01
andIX_SU_02
D.Noneoftheabove
13.Aninvisibleindexisanindexononeormorecolumnsinatable:
A.Whereatleastoneofthecolumnsmustbeinvisible
B.Whereallthecolumnsmustbeinvisible
C.AndisupdatedforanyDELETEstatementsperformedonthe
table
D.AndisupdatedforanySELECTstatementsperformedonthe
table
PerformFlashbackOperations
14.ReviewthefollowingSQLcode:
Whichofthefollowingstatementscouldbeaddedasline11andrecover
thedeletedrowsfromthePO_BOXEStable?
A.FLASHBACKTABLEPO_BOXESTOTIMESTAMP
SYSTIMESTAMP—INTERVAL‘000:00:45’DAYTOSECOND;
B.FLASHBACKTABLEPO_BOXESTOSYSTIMESTAMP—
INTERVAL‘000:00:45’DAYTOSECOND;
C.FLASHBACKTABLEPO_BOXESINTERVAL‘000:00:45’
DAYTOSECOND;
D.FLASHBACKTABLEPO_BOXESTOTIMESTAMP
INTERVAL‘000:00:45’DAYTOSECOND;
15.ReviewthefollowingSQLcode:
WhatstatementwillrecoverthePO_BOXEStableafterthesestatements
areexecuted?
A.FLASHBACKTABLEPO_BOXESTOBEFOREDROP;
B.FLASHBACKTABLEPO_BOXESTOTIMESTAMP
SYSTIMESTAMP—INTERVAL‘000:00:03’DAYTOSECOND;
C.FLASHBACKTABLEPO_BOXESTOBEFORECOMMIT;
D.Noneoftheabove—thetablecannotberecovered.
SELFTESTANSWERS
DescribeHowSchemaObjectsWork
1. B.TheINDEXstoresdataforspeedingupquerying.
A,C,andDareincorrect.ROWIDisapseudocolumn,notadatabase
object.AVIEWnamesaSELECTstatement.LOOKUPissomethingmade
up;it’snotareservedwordinOracle.
2. D.Noneoftheabove.ASEQUENCEisacounterthatisusefulfor
populatingprimarykeysbutcanbeusedforanypurposethedeveloper
wishes,ornot.
A,B,andCareincorrect.ASEQUENCEisastandaloneobjectandis
notpartofatable.Itmaybeusedtopopulateprimarykeysoranyother
purposeforwhichthedeveloperchooses;itismerelyanumbercounter.
Primarykeysmaybepopulatedinanyway,providethevaluesentered
conformtotheparticularprimarykey'sspecifiedconstraints,whichare
usuallythatthekeybeuniqueandNOTNULL.
3. A.Alldataisstoredintables.Evendataaboutthetablesyoucreate
isstoredautomaticallybyOracleSQLinasetofsystem-definedand
system-maintainedtables.
B,C,andDareincorrect.
CreateSimpleandComplexViewswithVisible/InvisibleColumns
4. A.TheSELECTstatementcanbeusedagainstanyview.
B,C,andDareincorrect.TherearemanyreasonswhyanygivenVIEW
mayrejectattemptstoexecutetheINSERT,UPDATE,orDELETE
statement.Forexample,iftheVIEWobjectdoesnotcontainsufficient
accesstoitsunderlyingtables,thenitmightnotprovideallthecolumn
accessrequiredtosatisfytheunderlyingconstraintrestrictionsthatmay
existforanyINSERT,UPDATE,orDELETEstatement.Whilemanyviews
allowalloftheseSQLstatementstowork,it’sentirelypossibletocreatea
VIEWthatdoesnot.
5. A.Theerroronline3isthefailuretogivetheexpressionacolumn
alias.TheVIEWdoesnotassignanametothesecondcolumn,sothe
attempttocreatetheviewfails.
B,C,andDareincorrect.Thesearenoterrors.Line6isfine;theuseof
USINGworkswellhere.Line7isfine;theexpressionthatcalculatesthe
resultofPROJECT_COSTtimes2isfine,andexpressionsinWHERE
clauseshavenorestrictionsinaCREATEVIEWstatement.
6. A.Thesyntaxforcreatingtheviewiscorrect,andanyviewcan—at
aminimum—workwithaSELECTstatement.ButanINSERTwillnot
workwiththisviewsinceitconsistsofaggregaterows,asdefinedbythe
GROUPBYclauseintheview’sSELECTstatement.
B,C,andDareincorrect.TheviewwillnotworkwithanINSERT
becauseoftheGROUPBY.Inotherwords,thereisnowaytoaddsingle-
rowvaluesthroughtheviewsincetheview’saccesstothetablesis,by
definition,attheaggregatelevel.Also,theGROUPBYandJOIN
conditionsfortheSELECTarefine.Youcanmostcertainlycreateviews
withthoseclausesintheSELECTstatement—theyjusthavetheeffectof
limitingthecapabilitiesoftheresultingview,aswe’veseen.Suchviews
won’tacceptINSERTorUPDATEstatements.
7. D.TheCREATEandINSERTstatementswillsuccessfullyexecute.
A,B,andCareincorrect.ThePURPOSEcolumnisnotrequiredto
createtheview—thesubqueryinline2throughline4isavalidSELECT
statement.Thecodeonlines9and10specifiesscalarsubqueriesandis
correct.ThelowerPROJECT_COSTvaluewillnotpreventtheINSERT
statementfromworking;however,itwillpreventtherowfromeverbeing
seenthroughtheMAJOR_PROJECTSview.ASELECTstatementthat
attemptstodisplaythisrowinthefuturecoulddosobyqueryingthe
originaltablePROJECTS,butnottheviewMAJOR_PROJECTS,which
onlyseesrowswithaPROJECT_COSTgreaterthan10000butcertainly
allowsthemtobeinsertedthroughtheviewintotheunderlyingtable.
Create,Maintain,andUseSequences
8. D.JOINisusedinaSELECTstatementthatconnectstwoormore
tables.ButitisnotusedinaCREATESEQUENCEstatement,eventhough
itsultimatepurposemaybetosupporttheintegrityofjoins.
A,B,andCareincorrect.CYCLEspecifieswhetherthesequencewill
repeatarangeonceitreachestheendoftherange.MAXVALUEspecifies
oneendoftherange.INCREMENTspecifiesthenumberbywhichthe
sequencewillincrement.
9. B.Therewillbeonerowinthetable.Thereasonisthatthefirst
INSERTwillfailbecauseoftheattempttoenteracharacterstringintoa
numericcolumn.InthefirstfailedINSERTstatement,thePROJ_ID_SEQ#
sequencegeneratorwillbeinvoked,andtheNEXTVALreferencewilluse
upthefirstnumberinthesequence,whichwillbe1.ThesecondINSERT
willsucceedandgrabthesecondnumberinthesequence,whichwillbe5.
A,C,andDareincorrect.
10. B.Sincethesequencewasjustcreated,NEXTVALmustbereferenced
beforeCURRVAL.Thisisalsotrueifyouweretologoffandendthe
sessionandthenlogbackintorestartthesession—thefirstreferencefor
existingsequencesmustbeNEXTVAL.
A,C,andDareincorrect.Youareallowedtoreferencesequence
generatorsinanySQLstatementwhereexpressionsareallowed.If
CURRVALwerereplacedwithNEXTVAL,thecorrectanswertothis
questionwouldhavebeenC,meaningthattheSELECTstatementwould
havedisplayedavalueof1.
CreateandMaintainIndexesIncludingInvisibleIndexesand
MultipleIndexesontheSameColumns
11. B.AnindexcanpotentiallyspeeduptheWHEREclauseofanyDML
statement,includingtheUPDATEstatement.Comparisonsofequalityare
ideal.
A,C,andDareincorrect.Anindexdoesnotstoreallthedatafromall
therowsofanindexedtablebutinsteadstoresonlythatdatathatis
containedwithintheindexedcolumnorcolumns.Itdoesnotrequirea
separateINSERTstatement;instead,anyfutureINSERTswillperform
automaticindexmaintenanceasrequiredwithoutanyextraeffortfromyou.
TheSELECTstatementdoesnotneedtoreturnindexedinformationforthe
indextobeuseful.
12. B.Whileallthestatementswillexecutesuccessfully,thefirstDROP
statementwilldropthetableSUPPLIES_01,whichwillcausetheindex
IX_SU_01tobedroppedaswell.Inotherwords,theDROPTABLE
SUPPLIES_01statementhastheeffectofdroppingthetable
SUPPLIES_01aswellastheindexIX_SU_01.ThetablesSUPPLIES_02
andIX_SU_02willremainattheend.
A,C,andDareincorrect.
13. C.TheindexisupdatedforanyDELETEstatementsperformedonthe
table.Invisibleindexesarestillmaintained,eventhoughtheyareinvisible.
A,B,andDareincorrect.Aninvisibleindexhasnothingtodowith
invisiblecolumnsinthetable.TheuseofaSELECTstatementnever
resultsinamaintenanceactionofanindex,regardlessofthevisibilityof
theindex.
PerformFlashbackOperations
14. A.Thisisthecorrectsyntax—theTOTIMESTAMPclausewiththe
expressionthatstartswiththecurrentdateandtimeandsubtractsan
intervalof45seconds.
B,C,andDareincorrect.OptionBismissingthekeyword
TIMESTAMP.OptionCismissingthekeywordsTOTIMESTAMPand
includesanincompleteexpressionthatonlyrepresentsatimeintervalof45
seconds.OptionDhasthekeywordTIMESTAMPbutalsohasthe
incompleteexpressionthatonlyincludestheintervalvalueandnothing
more.
15. D.Noneoftheabove.ThePURGEstatementonline8preventsany
recoveryfrombeingpossible.PURGEcleansouttherecyclebinofthe
objectsspecifiedinthePURGEstatement,fromwhichFLASHBACK
TABLErecoversobjects.
A,B,andCareincorrect.WereitnotforthePURGE,optionAwould
becorrect.OptionBissyntacticallycorrect,exceptforthePURGE
statementinthecodesample.ThereisnoBEFORECOMMIToptionfor
FLASHBACKTABLE.
11
T
UsingtheSetOperators
CERTIFICATIONOBJECTIVES
11.01DescribeSetOperators
11.02UseaSetOperatortoCombineMultipleQueriesintoaSingleQuery
11.03ControltheOrderofRowsReturned
✓Two-MinuteDrill
Q&ASelfTest
hischapterdescribesthesetoperatorsinSQL.Setoperatorsworkwithsets
ofoutputdatafromtwoormoreSELECTstatements.Theycombine
standaloneSELECTstatementsinwaysthatcannotbedonewithjoinsorother
conventionalmethodsinSQL.
SetoperatorsareidealforavarietyofsituationswhereaSELECTstatement’s
outputcanbecombinedwithotherdatathatisn’tnecessarilyrelatedthrougha
structuredkeyrelationshipbutcanstillbeblendedintoonecompleteoutputdata
set.AseriesofSELECTstatementscombinedwithsetoperatorsmayincludea
singleORDERBYclauseattheendoftheseriesofSELECTstatements.Set
operatorsshouldnotbeconfusedwiththereservedwordSETthatisusedwith
SQLstatementslikeUPDATE.Thesetoperatorshavenothingtodowiththe
keywordSETanddon’tusetheSETvariable_nameclause.
CERTIFICATIONOBJECTIVE11.01
DescribeSetOperators
Therearefoursetoperators:UNION,UNIONALL,INTERSECT,andMINUS.
SetoperatorscombinetwoormoreseparateSELECTstatementssothattheir
outputismergedinsomemanner.Eachsetoperatormergesthedataina
differentway.ThesetoperatorsaredescribedinTable11-1andsummarizedin
Figure11-1.
TABLE11-1 TheSetOperators
FIGURE11-1 Thesetoperatorsinaction
TheUNIONoperatormergestheresultingrowsetsofoneSELECTstatement
withtheresultingrowsetsofanothersothatalltherowsfrombothSELECT
statementsareincludedinthefinaloutput.UNIONalsoeliminatesanyduplicate
recordsthatmightresultinthecombinedoutput.
UNIONALLdoesthesamethingasUNION,exceptitdoesnoteliminate
duplicaterows.
INTERSECTcombinesbothsetsofrowssothatonlythoserowsthatwere
presentinbothSELECTstatementsappearinthefinalresult.
MINUSstartswiththefirstsetofrowsandthenusesthesecondSELECT
statement’srowsettoseewhetheranyduplicatesoccur.Iftheydo,those
duplicatesarecompletelyremoved,leavingonlythoserowsthatuniquelyexist
inthefirstSELECTstatement’srowset.
TheonlyrulesforensuringthattheSELECTstatementswillcombine
successfullywithanyofthesetoperatorsareasfollows:
Thenumberofexpressionsselectedintheselectlistsmustbe
identicalineachSELECTstatement.
ThedatatypesofeachexpressionmustmatchsothateachSELECT
statement’sfirstexpressionsharesthesamedatatypegroupwiththe
otherfirstexpressions,eachsecondexpressionsharesthesamedatatype
groupwiththeothersecondexpressions,andsoon.Bydatatypegroup,
wemeandatatypesthateitherareidenticalorcanbemadetobe
identicalbySQLthroughautomaticdatatypeconversion.
LargedatatypessuchasBLOBandCLOBcannotbeused.
TheORDERBYclausecannotbeincludedintheSELECT
statements—exceptafterthelastSELECTstatement.
YoucancombinecomplexSELECTstatementswiththesetoperators.
ExamplesincludeSELECTstatementsthatinvolvemultitablejoins,
subqueries,aggregatefunctions,and/orGROUPBYclauses.
TheSELECTstatementsarenotrequiredtohaveanysortofPRIMARYKEY
/FOREIGNKEYrelationships.Theirtablesandcolumnsdon’thavetobe
identicalinanyotherway.Forinstance,theydon’thavetobenamedwiththe
samenames—noneofthatapplies.EachindividualSELECTstatementcanbea
complete,standalonestatement(butwithoutanORDERBYclauseunlessitis
afterthefinalSELECTstatementintheset),withallthecomplexitiesofany
SELECTstatement,includingGROUPBYclauses,subqueries,andeverything
thatformsacompleteSELECTstatement.Aslongasthenumbersofcolumns
areidentical,andtherespectivedatatypegroupsmatchup,thesetoperatorswill
performasintended(subjecttotherestrictionswejustidentified).
CERTIFICATIONOBJECTIVE11.02
UseaSetOperatortoCombineMultipleQueriesinto
aSingleQuery
Let’slookatthesyntaxforthesetoperators.Eachissimple—eachsetoperator
connectstwoSELECTstatements,causingthemtobehaveasone.
UNION
TodemonstratetheuseofUNION,we’lllookatanexerciseinwhichweare
tryingtocombinee-mailaddressesfromdifferenttables.First,we’lllookatone
ofthetwotablesshowninFigure11-2,theCONTACT_EMAILStable.
FIGURE11-2 DiagramoftheCRUISE_CUSTOMERSand
CONTACT_EMAILStables
NoticethecolumnEMAIL_ADDRESSintheCONTACT_EMAILStable.
Let’sgetadatalisting:
Next,let’slookatanothertablecalledONLINE_SUBSCRIBERS,shownin
Figure11-3.YoucanseethatithasacolumncalledsimplyEMAIL.Let’sgeta
datalistingforthattableaswell:
FIGURE11-3 DiagramoftheONLINE_SUBSCRIBERStable
TodemonstratethesetoperatorUNION,we’llcreatetwoSELECT
statementswithsimilarselectlists—butbysimilar,wemeanonlythattheselect
listsareidenticalinthenumberofexpressionsinthelistandtheirrespective
datatypegroups.ThefirstSELECTwillincludeaWHEREclausetolimitour
rowsto'Valid'data.Let’sgiveitatry(linenumbersadded):
Noticehowwe’vestructuredthisUNIONquery:
BothSELECTstatementshavetwoexpressionsintheirselectlists
(line1andline5).
Thedatatypesofeachlist’sfirstexpressionarethesame:
CONTACT_EMAIL_ID(line1)andONLINE_SUBSCRIBER_ID(line
5).Inthiscase,theyarebothnumeric.
Thedatatypesofeachlist’ssecondexpressionarethesame:
EMAIL_ADDRESS(line1)andEMAIL(line5).Inthiscase,theyare
bothcharacterstrings.
Here’stheoutputfromourUNION:
NoticethefirstcolumnofoutputundertheheadingCONTACT_EMAIL_ID.
TheoutputshownincludesdatafrombothSELECTstatements,whichmeans
you’reseeingvaluesfromthecolumnCONTACT_EMAIL_IDofthefirst
SELECTstatementandfromthecolumnONLINE_SUBSCRIBER_IDofthe
secondSELECTstatement.
Logically,though,there’saproblem:thevaluesforCONTACT_EMAIL_ID
andONLINE_SUBSCRIBER_IDdon’treallyrepresentthesameinformation.
Bothareprimarykeyvaluesbutfordifferenttables,andtheydon’treallybelong
inthesamecolumn—theyrepresenttotallydifferentvalues.Theevidenceofthis
problemispresentinthelistofe-mailaddresses—weonlywantedasinglelist
ofuniquevalues,butinsteadwehaveaduplicationofatleastonee-mail
address.ThereasonisthatUNIONlooksattheentirerowofoutputfromeach
SELECTandshowsuniqueoccurrencesofthecombinedsetofcolumnsinthe
row.Thefirstoccurrenceofthee-mailaddress“watcher@foursigma.org”hasa
firstcolumnvalueof2,andthesecondhasafirstcolumnvalueof3,soasfaras
theUNIONisconcerned,theseareuniquerowsofdata.
Let’sremovetheillogicalreferencestothefirstcolumninthisexampleand
producesomethingthatmakesmoresense:
Here’stheresult:
TheresultofUNION(line4)isacombinationoftheoriginalrows,withany
duplicatevaluesremoved.Inthiscase,thereweretworowsforthee-mail
address“watcher@foursigma.org,”butonlyoneisshowninourfinalresult.
NoticethattheoutputcolumnheadingsdisplaythefirstSELECTstatement’s
expressions(line1).We’llhavemoretosayaboutthatwhenwediscussORDER
BYandcolumnreferences.Fornow,let’smoveontotheUNIONALLset
operator.
UNIONALL
TheonlydifferencebetweenUNIONandUNIONALListhatduplicatevalues
aren’tremovedfromUNIONALL.IfweweretoexecutethesameSQL
statementfromthepreviousexamplewiththeUNIONALLsetoperator,it
wouldlooklikethis:
Herearetheresults:
Noticethattheduplicateentryisincluded.Thevaluefor
"watcher@foursigma.org"appearsinbothtables,soitappearstwiceinthe
outputofourUNIONALLuseoftheSELECTstatement.
Noticealsothattheorderingoftherowsistotallydifferent—rememberthat
withoutanexplicitORDERBYclause,youcanneverguaranteetheorderingof
rowsinanySELECTstatement.We’lllookathowtouseORDERBYlaterin
thischapter.First—let’slookatanothersetoperator.
INTERSECT
ThesetoperatorINTERSECTlooksforcommonvaluesamongtherowsofthe
SELECTstatement.Let’schangeourexampletouseINTERSECT:
Herearetheresults:
JustonerowwascommonbetweenthetwoSELECTstatements.
INTERSECTwilleliminateduplicaterows.IfoneorbothSELECTstatement
rowsetscontainduplicateswithinitsownsetofrows,theresultingoutputfrom
INTERSECTwilleliminatethoseduplicates.
MINUS
ThefinalsetoperatorisMINUS.Uptonow,theresultsofthesetoperators
wouldbethesameregardlessofwhichSELECTstatementwasplacedfirst
beforethesetoperator.That’snotthecasewithMINUS,however.MINUSwill
startwiththefirstSELECTstatementandremoveanyrowsfromthatSELECT’s
outputthatmighthappentoappearinthesecondSELECT’soutput.Theresults
maydiffer,dependingonwhichSELECTisplacedfirstandwhichisplaced
second.
Usingoursameexample,hereistheSELECTfromCONTACT_EMAILS
first:
Herearetheresults:
Butnowlet’sreversetheplacementoftheSELECTstatements:
Herearetheresults:
Noticethattheresultsarecompletelydifferent.Noticealsothatthecolumn
headingisdifferent—thecolumnhastakentheheadingofthefirstSELECT
statement,asitalwaysdoes,butnowthefirstSELECTstatementisdifferent,
andalongwithit(inthisexample)soistheheading.
Combinations
Thesetoperatorsmaybeusedinmultiplecombinations,suchas
Suchcombinationscanbecontinuedindefinitely.
Setoperatorshaveequalprecedenceamongthemselves,meaningthatthey
willallexecutefromstarttofinishintheorderthattheyappearintheSELECT
statement.Tochangetheorderofexecution,useparentheses,likethis:
Justbesuretousetheparenthesessothat:
Thecodeenclosedisastandalonequeryanddoesnotincludean
ORDERBYclause.
Theenclosedcodeisplacedintotheouterqueryasthoughitwerea
single,standaloneSELECTstatement,withouttheORDERBYclause.
IfanORDERBYisdesired,itmustbethefinalclauseintheentire
seriesofstatements.
Followthoserules,andyoucanconnectasmanySELECTstatements
togetherasrequired.
Thesetoperatorsareusefulforrequirementstocombinethedataoftwotables
intooneoutputresultsetwhenthetwotableshavenoprimarykey/foreignkey
relationshipwitheachother.
CERTIFICATIONOBJECTIVE11.03
ControltheOrderofRowsReturned
AswithanySELECTstatement,theORDERBYclauseistheonlywayto
determinetheorderingofrowsthatappearinoutput.Aswealreadyknow,the
ORDERBYclausedetermineshowtosortrowsbyidentifyingaseriesofoneor
moreexpressionsthathavesomethingtodowiththetable—ortables—thatare
involvedwiththeSELECTstatement.Oftentheexpressionissimplyacolumn
withineachrow,butORDERBYalsoacceptscomplexexpressions.These
expressionsmayinvolveoneormorecolumnsandperformsomesortof
transformationonthedata.
However,whensetoperatorsareinvolved,there’sabitofanissue.Howdo
youidentifydataintherowswhentherearemultipletablesusingdifferent
columnnames?
TheansweristhattheORDERBYclauseisabitrestrictedinthissituation.
Theclauseisrestrictedtoidentifyingcommonexpressionitemsintheselectlist,
andnothingmore.Therearetwowaystoidentifythem,andwe’veseenthese
earlier—byreferenceandbyposition.Thefollowingsectionsshowexamplesof
theseapproacheswiththesetoperators.
ORDERBY—ByPosition
OnewaytosortrowsofoutputthatresultfromaseriesofSELECTstatements
combinedwithsetoperatorsistousethe“byposition”approach.Here’san
example:
Theprecedingexamplecombinesrowsfromtwotables.Thefirstqueryhas
twoexpressions:
Astringliteral,'Individual'
Aconcatenationoftwocolumns,LAST_NAMEand
FIRST_NAME,separatedbyacommaandaspace
ThesecondSELECTstatementhastwoexpressions:
ThecolumnCATEGORY
ThecolumnVENDOR_NAME
Herearetheresults:
WecansorttherowswithanORDERBYthatidentifiesthepositionwithin
theselectlistoftheexpressionwewanttosortby,likethis:
Hereistheresult:
Remember,whenusingORDERBYwithaseriesofSELECTstatements
connectedwithsetoperators,youcanuseORDERBYonlyonce,attheend.
ORDERBY—ByReference
ThereisanotherwaytouseORDERBYwithsetoperators.ORDERBY
referenceiswhenyounameoneofthecolumnsintheSELECTstatement’s
expressionlist.Whenusingsetoperators,thecolumnnamesusedinthefirst
SELECTstatementareinforce.Usingourearlierexample,let’saddcolumn
aliasestoourfirstSELECTstatement,andwe’llbeabletouseORDERBY:
NotethecolumnaliasPOINT_OF_CONTACTthatisspecifiedattheendofline
2andusedintheORDERBYinline8.Herearetheresults:
So,eitherthe“byposition”or“byreference”approachworkswithORDER
BY.JustbesureyoumakeitthelastclauseoftheentireseriesofSELECT
statements.
IfyoucombineaseriesoftwoormoreSELECTstatementswithset
operators,yourORDERBYclausemustbethefinalclauseandcan
specifycolumnsbynameonlyifitusesthecolumnnamesfromthefirst
SELECTstatement,regardlessofhowmanySELECTstatementsmight
beconnectedwithsetoperators.
CERTIFICATIONSUMMARY
EachsetoperatorcombinesrowsfromtwoindependentSELECTstatements.Set
operatorsallowyoutocombinerowswithoutajoinbymergingentiresetsof
rowsbasedsolelyonensuringthatthenumberofexpressionsanddatatypes
involvedmatchup.
ThesetoperatorsincludeUNION,UNIONALL,INTERSECT,andMINUS.
EachdiffersinhowitreturnsrowsthatappearinoneSELECTstatementthat
mightalsoappearintheotherSELECTstatement.
UNIONcombinesrowsfromtheSELECTstatementsandpresentsone
uniquesetofrowsfromthecombinedSELECTstatements.Iteliminates
duplicaterowsthatmightappearasaresultofthecombination.UNIONALL
combinesbothsetsofrowsandincludesanyduplicatesthatmightoccurasa
resultofthecombinationoftherowsets;thatis,itdoesnoteliminateany
duplicaterows.INTERSECTlooksonlyforrowsthatarepresentinbothsetsof
rowsreturnedbytheSELECTstatements.Onlytheduplicatesbecomethe
outputfromtheSELECTstatement.MINUStakesthesetofrowsfromthefirst
SELECTandremovesanyforwhichduplicatesexistinthesecondset.
YoucancombineseveralSELECTstatementswithasmanysetoperatorsas
youwant.Theywillexecuteoneaftertheother,unlessyouchoosetooverride
thatbehaviorusingparentheses.
EachSELECTstatementcanbeacomplexquery,withmultiplejoins,
subqueries,andGROUPBYclauses.However,onlyoneORDERBYclauseis
allowed,anditmustbeattheendoftheseriesofSELECTstatementsandset
operators.
ORDERBYwithsetoperatorscansortrowsbypositionorreference.Ifby
reference,thefirstSELECTstatement’sexpressionnamesareineffectforthe
entireseriesofSELECTstatements.Youcanusecolumnaliasesinthefirst(or
any)SELECTstatementifyouwant,butitisnotrequired.
✓TWO-MINUTEDRILL
DescribeSetOperators
UNIONcombinestheoutputoftwoSELECTstatements,
eliminatinganyduplicaterowsthatmightexist.
INTERSECTcombinestheoutputoftwoSELECTstatements,
showingonlytheuniqueoccurrencesofdatapresentinbothrowsets
andignoringanythingthatdoesn’tappearinbothsets.
MINUStakesthefirstSELECTstatement’soutputandsubtracts
anyoccurrencesofidenticalrowsthatmightexistwithinthesecond
SELECTstatement’soutput.
UNIONALLdoesthesamethingasUNIONbutdoesnoteliminate
duplicaterows.
UseaSetOperatortoCombineMultipleQueriesintoaSingle
Query
ThesetoperatorsareplacedbetweentwoSELECTstatements.
ThetwoSELECTstatementscanbesimpleorcomplexandcan
includetheirownGROUPBYclauses,WHEREclauses,subqueries,and
more.
TheORDERBYclause,ifused,mustbethefinalclauseofthe
combinedSELECTstatements.
YoucanconnectmultipleSELECTstatementswithmultipleset
operators.
Thesetoperatorshaveequalprecedence.
Youcanuseparenthesestooverridesetoperatorprecedence.
ControltheOrderofRowsReturned
IfanORDERBYclauseisused,itmustbeplacedattheendofthe
SQLstatements.
MultipleSELECTsthatareconnectedwithsetoperatorsmaybe
sortedbypositionorreference.
WhenusingORDERBYreference,thecolumnnameinforceis
whatevercolumnnameexistsinthefirstSELECTstatement.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
DescribeSetOperators
1.Thesetoperatorsdonotincludewhichoneofthefollowingkeywords?
A.ALL
B.SET
C.MINUS
D.UNION
2.Youaretaskedwithcleaningupadatabaseapplication.Therearetwo
tablesinthedatabase:ORDERScontainscompletedORDERS,and
ORDER_RETURNScontainsduplicateinformationforallORDERSthat
werelaterreturned.Yourgoalistofindoutwhetheranyrowsin
ORDER_RETURNSexistthatwereneverintheORDERStabletobegin
with.Whichofthefollowingsetoperatorsshouldyouuse?
A.ALL
B.SET
C.MINUS
D.UNION
3.Reviewthefollowingillustrations:
Next,reviewthefollowingSQLcode:
WhatwillresultfromanattempttoexecutethisSQLstatement?
A.ItwillfailwithasyntaxerrorbecauseoftheTO_CHAR
conversionfunctiononline1.
B.Itwillfailbecauseofthetablealiasinlines1and2,which
cannotbeusedinthiscontext.
C.Itwillfailwithasyntaxerroronline3becauseyoucannotuse
anORDERBYinthiscontext.
D.Itwillexecutesuccessfully.
4.WhencombiningtwoSELECTstatements,whichofthefollowingset
operatorswillproduceadifferentresult,dependingonwhichSELECT
statementprecedesorfollowstheoperator?
A.MINUS
B.UNIONALL
C.INTERSECT
D.UNION
5.Whichofthefollowingstatementsaboutsetoperatorsistrue?Choose
thebestanswer.
A.IfyouaddthereservedwordALLtotheendofanysetoperator,
itwillchangethebehaviorofthesetoperatorbyremovingduplicate
rows.
B.SetoperatorscanbeusedtocombineINSERTstatements.
C.YoucanconnecttwoSELECTstatementswithonesetoperator.
D.TheUNIONsetoperatorhasprecedenceovertheothers.
UseaSetOperatortoCombineMultipleQueriesintoaSingle
Query
6.Reviewthefirsttwoillustrationsfromquestion3,andthenreviewthis
SQLcode
Howmanyrowswillresultfromthisquery?
A.0
B.1
C.3
D.6
7.Reviewthefirsttwoillustrationsfromquestion3,andthenreviewthis
SQLcode:
Howmanyrowswillresultfromthisquery?
A.0
B.4
C.6
D.Itwillnotexecutebecauseitwillfailwithasyntaxerror.
8.Reviewthefirsttwoillustrationsfromquestion3,andthenreviewthis
SQLcode:
Howmanyrowswillresultfromthiscode?
A.1
B.2
C.4
D.6
9.Reviewthefirsttwoillustrationsfromquestion3,aswellasthe
ONLINE_SUBSCRIBERStableinFigure11-3,andthenreviewthisSQL
code:
WhatwillhappenwhenthisSQLstatementisexecuted?
A.Itwillfailwithasyntaxerrorbecauseyoucannotusean
aggregatefunctionlikeCOUNT(*)inline1inthiscontext.
B.Itwillfailwithasyntaxerrorstartingatline4.
C.Itwillexecute,butitwillnotperformasintendedbecausethe
secondSELECTstatementwithinthesubqueryonline6willnot
execute;onlythefirstSELECTinthesubqueryonline4willexecute.
D.Itwillexecutesuccessfully.
10.Reviewthefirsttwoillustrationsfromquestion3,aswellasthe
ONLINE_SUBSCRIBERStableinFigure11-3,andthenreviewthisSQL
code:
WhatwillhappenwhenthisSQLstatementisexecuted?
A.Itwillfailwithanexecutionerroronline1.
B.Itwillexecute,buttheUNIONwillnotworkasexpected.
C.Itwillexecuteanddisplayonecolumnunderthe“DateAdded”
heading.
D.Itwillexecuteanddisplayonecolumnunderthe
“LAST_ORDER”heading.
11.Reviewthefirsttwoillustrationsfromquestion3,aswellasthe
ONLINE_SUBSCRIBERStableinFigure11-3,andthenreviewthisSQL
code:
WhatwillhappenwhenthisSQLstatementisexecuted?
A.Itwillfailwithageneralsyntaxerror.
B.Itwillfailwithanexecutionerror.
C.Itwillexecute,buttheINTERSECTwillnotworkcorrectly.
D.Itwillexecuteandrepeatthevalue'Towel'foreachrowofthe
ONLINE_SUBSCRIBERStable.
12.Reviewthefirsttwoillustrationsfromquestion3,aswellasthe
ONLINE_SUBSCRIBERStableinFigure11-3,andthenreviewthisSQL
code:
WhichofthefollowingaretrueaboutthisSQLstatement?(Choose
two.)
A.TheGROUPBYclauseonline7isnotallowedhere.
B.TheB.LAST_ORDERreferenceattheendofline6refersto
dataincludedintheADDEDcolumnreferredtoinline5.
C.TheJOINattheendofline2isnotallowedinthiscontext.
D.Thestatementissyntacticallycorrectandwillexecute
successfully.
ControltheOrderofRowsReturned
13.Reviewthefirsttwoillustrationsfromquestion3,aswellasthe
ONLINE_SUBSCRIBERStableinFigure11-3,andthenreviewthisSQL
code:
WherecanyouaddanORDERBYtothiscode?(Choosetwo.)
A.Attheendofline5beforetherightparenthesis
B.Betweenlines5and6
C.Afterline7
D.Nowhere
14.TheORDERBYclausecanbeincludedinaSELECTwithsetoperatorsif:
A.ItfollowsthefirstSELECTstatement.
B.ItfollowsthefinalSELECTstatement.
C.ItisusedineachSELECTstatementanditsORDERBY
expressionsmatchindatatype.
D.TheORDERBYclausecannotbeusedinaSELECTwithset
operators.
15.Reviewthefirsttwoillustrationsfromquestion3;thenreviewthisSQL
code:
WhichofthefollowingarevalidORDERBYclausesforthisquery?
(Choosetwo.)
A.ORDERBYAISLE
B.ORDERBY"LastOrder"
C.ORDERBYSECTION
D.ORDERBY1
SELFTESTANSWERS
DescribeSetOperators
1. B.ThekeywordSETisnotusedwiththesetoperators.
A,C,andDareincorrect.ALLispartoftheUNIONALLclause.
MINUSandUNIONarebothsetoperators.
2. C.MINUSiswhatyouwoulduse.Thatisthesetoperatorwith
whichyoucanremoverowsfromonetablethatarealsopresentinthe
secondtable,resultinginoutputthatshowsrowsfromthefirsttablethatare
notpresentinthesecond.
A,B,andDareincorrect.ALLisnotafullsetoperator;itworkswith
UNIONALLbutisnotasetoperatoronitsown.SETisnotasetoperator.
UNIONwouldcombinerecordsfrombothtables,whichisnotwhatis
desiredhere.
3. C.TheORDERBYofthefirstSELECTstatementinline3is
incorrectandcausesthestatementtofail.
A,B,andDareincorrect.TheTO_CHARconversionfunctioninline1
iscorrectsyntax.ItensuresthatthedatatypesforLAST_ORDERand
ADDEDcorrespondtoeachother.Thetablealiasonlines1and2isfine.
Buttheentirestatementwillnotexecuteforthereasonexplainedforthe
correctanswer.
4. A.Theonlysetoperatorthatchangesitsendresultbasedonwhich
SELECTstatementprecedesorfollowsthesetoperatorisMINUS.
B,C,andDareincorrect.
5. C.YoucanconnecttwoSELECTstatementswithonesetoperator.
A,B,andDareincorrect.ThereservedwordALLworksonlywith
UNION.SetoperatorscancombineonlySELECTstatements,notother
SQLstatements.Allsetoperatorshaveequalprecedence;onlyparentheses
canbeusedtooverridesetoperatorprecedence.
UseaSetOperatortoCombineMultipleQueriesintoaSingle
Query
6. A.Norowswillresult.Thereasonisthatwe’retryingtointersect
rows,whichmeanstoshowonlythoserowsthatarecommonbetweenthe
tworowsets.Whilebothtablesshareavalueof'Towel',theSELECT
statementsareincludingtheNUMandCAT#columnsfromthetwotables.
InthetworowsforTowel,thevaluesforNUMandCAT#don’tmatch.The
resultisthatneitherrowthatincludes'Towel'isacompletematch.
B,C,andDareincorrect.
7. B.Thefirstselectwillproduceonerow.Thesecondwillproduce
threerows.TheUNIONALLsetoperatorwillcombinetheresultsand
returnfourrows.
A,C,andDareincorrect.Thesyntaxisfineandthestatementwill
execute.
8. A.Onlyonerowwillresult,asexplainednext.
B,C,andDareincorrect.ItmightbetemptingtohavechosenoptionB,
sincethefirstandsecondSELECTstatementcombinationswiththe
UNIONALLwillproducetworowscontainingthevalue'Towel',andso
willthesecondUNIONALL.ButtheINTERSECTwilleliminateduplicate
rowsandreturnonerowfor'Towel'.
9. D.Itwillexecutesuccessfully.Setoperatorsareperfectlyacceptable
inasubquery.
A,B,andCareincorrect.
10. A.SinceweknowfromthedatalistingsthattheresultsoftheSELECT
statementswiththesetoperatorUNIONwillproducemultiplerows,the
statementwillfail,sinceascalarsubqueryiswhatisexpectedherebythe
outerquery.
B,C,andDareincorrect.UNIONisfine,buttheendresultcauseda
problemforreasonsunrelatedtotheUNION.Thecolumnheadingissues
don’tapply,butifthesubqueryhadnotproducedtheexecutionerror,
optionsCandDwouldstillbeincorrect—theheadingwouldbea
concatenatedversionoftheentirestringofcharactersformingthe
subquery.
11. D.Wecantellfromthedatalistingthatthesubquerywillreturnonevalue
representingtheINTERSECTofbothqueries.That,andthefactthatthe
subquerywillreturnjustonecolumninthatonerow,makesthisascalar
subquery,albeitariskyone,sincethere’snoguaranteethatitwillalways
executeasascalarsubquery.Butitwillworkgiventhedatalistings,and
thesubquerywillperformasthoughitwerealiteralvaluewithintheouter
SELECT,returningthesameresultforeachrowofthe
ONLINE_SUBSCRIBERStable.
A,B,andCareincorrect.Thereisnothingwrongsyntacticallywiththe
SQLstatement,andaswediscussindescribingthecorrectchoice,because
ofthedatalistingsweareprovidedwith,wecantellthattherewillbeno
executionerrorseither.TheINTERSECTwillperformjustfine.
12. BandD.ThisisavalidSQLstatementthatwillexecutesuccessfully.The
subqueryonlines3through5isthecompleteUNIONandistreatedasan
inlineviewinthiscontext.Assuch,itbehaveslikeanyotherinlineview
andisperfectlyfineinthiscontext.Attheendofline5isatablealiasB
thatisgiventotheinlineview,andthattablealiasisusedinline6to
identifythecolumnoftheinlineviewcalledLAST_ORDER,which
representsthefirstcolumnofthecombinedSELECTstatements,including
theADDEDcolumn.
AandCareincorrect.GROUPBYisallowed,asistheJOIN,for
reasonsexplainedunderthecorrectchoice.
ControltheOrderofRowsReturned
13. AandC.TheORDERBYcangoattheendoftheinlinevieworatthe
endoftheentireSQLstatement.
BandDareincorrect.
14. B.TheORDERBYisoptional,butifused,itmustbethelastclauseinthe
entireseriesofSELECTstatements.
A,C,andDareincorrect.ORDERBYcannotbeusedinanySELECT
statementswithinaseriesofSELECTstatementsconnectedbyset
operators.Itcanbeplacedattheendonly,followingthefinalSELECT
statement.
15. CandD.AnyORDERBYthatusesthe“byreference”techniquemust
referencecolumnnamesofthefirstSELECTstatement.So,ORDERBY
SECTIONisvalid.Also,the“byposition”isaccepted,soORDERBY1is
good.
AandBareincorrect.TheAISLEcolumnnameisn’trecognized,since
itisn’tacolumninthefirstSELECTstatement.Thesameistrueforthe
“LastOrder”columnalias.
12
T
ManagingObjectswithDataDictionary
Views
CERTIFICATIONOBJECTIVES
12.01QueryVariousDataDictionaryViews
✓Two-MinuteDrill
Q&ASelfTest
hischapterdescribesavaluabletoolthatallOracleprofessionalsshould
understand.ThedatadictionaryisOracle’sbuilt-inreal-timereferencesource
forallinformationabouttheapplicationsthatyoubuildinyourdatabase.Armed
withthefullcapabilitiesofthedatadictionary,youcanobtaininformationonthe
databaseobjectsthathavebeencreatedwithinyourdatabase,whocreatedthem,
when,andmuchmore.
CERTIFICATIONOBJECTIVE12.01
QueryVariousDataDictionaryViews
Thedatadictionaryisacollectionofdatabasetablesandviews.Itis
automaticallybuiltandpopulatedbytheOracledatabase.Theinformationstored
inthedatadictionaryincludesthefulldescriptionofallthedatabaseobjectsyou
createaspartofyourapplication,includingtables,views,indexes,constraints,
sequences,andmore.Inotherwords,theresultofeachDataDefinition
Language(DDL)statementyou’vestudiedinthisbookisrecordedinthe
dictionary,andtheinformationisautomaticallymaintainedbytheOraclesystem
inrealtimeasyouchangedatabaseobjectsandtheirstructures.
Theinformationstoredinthedatadictionaryincludes(butisnotlimitedto):
Thenamesofdatabaseobjects,theirowners,andwhentheywere
created
Thenamesofeachtable’scolumns,alongwithdatatypes,precision,
andscale
Anyconstraints
Views,indexes,andsequences
Thischapterwillexplorehowthedatadictionaryisstructuredandwhatsort
ofinformationiscontainedwithinit.We’llgothroughsomeexamplesofhowto
extractvaluableinformationandusethedatadictionarytoassistyouasyou
buildyourapplications.
Thedatadictionaryisoftenreferredtoasmetadata,whichmeans“dataabout
data.”Thatiswhatthedatadictionaryis—it’sacomprehensivedetaileddatabase
thattrackseverythingthereistoknowaboutthedatabaseapplicationsyoucreate
withintheOraclesystem.Everytimeyoucreateadatabaseobject,theOracle
Databaseworksinthebackgroundtorecordthatobject’snameandstructureand
makesthatinformationavailabletoyoubywayofthedatadictionary.Every
objectcreatedbyeveryuserisdocumentedwithinthedatadictionary.
Structure
Thedatadictionaryconsistsoftablesandviewsthatareownedbytheuser
accountSYS.Asowner,SYShasfullprivilegesoverthesetablesandviews.No
usershouldeveralterdataownedbySYSorelsetheintegrityofthedatabase
maybecompromised.
TheSYSaccountisoneofafewpowerfulaccountsthatcomeswithevery
implementationoftheOracledatabase.TheSYSaccountissomethingofa
“superuser”account,withmasterprivilegestovirtuallyeverythinginthe
database.Generally,nodeveloperusestheSYSaccountforanythingother
thandatabasesystemmaintenance,andoftenit’sthedatabase
administrator(DBA)whopossessesexclusiveaccesstotheSYSaccount.
Alldatadictionaryinformationisstoredintables,butmuchofthatdatais
presentedtousersthroughviews.Inotherwords,usersgenerallydon’tgetdirect
accesstothetablesofthedatadictionary;theygetaccesstotheviews,which
providesomewhatlimitedaccessinordertoprotecttheintegrityofthedata
dictionary.
Inaddition,manydatadictionaryobjectsarerenamedviapublicsynonyms,
andthosearethenamesbywhichyouknowthedata.Inotherwords,thereare
multiplelevelsofabstractionthatseparateusersfromtheunderlyingdata.No
matter—theabilitytoreadtheinformationinthedatadictionaryisagreatasset
toallSQLprofessionals.
EveryDDLstatementthatisissuedthroughoutthedatabasecausesan
automaticupdatetothedatadictionary.ThatupdateishandledbytheOracle
systemandappliedtothebasetablesthatformthefoundationofthedata
dictionary.Usersdonotexplicitlyupdateanyinformationinthedictionary.
(Note:Thereisoneexceptiontothis.Usersmayoptionallychoosetoadd
comments,whichyou’llexplorelaterinthischapter.)
Asofthiswriting,therearemorethan2,000viewsinthedatadictionary.One
inparticularisagoodstartingpoint:DICTIONARY.Thisviewcontains
informationabouttheviewsthatcomposethedatadictionary.Itincludesthe
nameofeachview,alongwithabriefexplanationofeachview.You’lllookatit
abitlater.
TheUSER_TABLESviewcontainsinformationaboutthetablesownedby
thecurrentuseraccount.Inotherwords,nomatterwhichaccountyouloginto,
youcanquerytheUSER_TABLESviewandgetdetailedinformationaboutthe
tablesownedbywhateveraccountyouareloggedinwith.
AfulldescriptionoftheUSER_TABLESviewwouldshowthatitconsistsof
over50columns.Someofthecolumnsinclude
TABLE_NAMEThenameofthetable.
STATUSIndicateswhetherthetableiscurrentlyvalidandtherefore
availableforuse.
ROW_MOVEMENTIndicateswhetherROWMOVEMENThas
beenenabledforthetable.(SeeourdiscussioninChapter10aboutthe
FLASHBACKTABLEstatementformoreinformationaboutenabling
anddisablingROW_MOVEMENT.)
AVG_ROW_LENTheaveragelengthoftherowscurrentlystored
inthetable.
Thesearejustsomeoftheseveraldozencolumnsthatareinthe
USER_TABLESview.
Whatifyouwanttoseeinformationabouttablesotherthanyourown?Well,
itjustsohappenstherearetwootherviewsinthedatadictionarythathave
almosttheidenticalsetofcolumnsasUSER_TABLES.
ALL_TABLESShowsallthesametableinformationbutfortables
towhichthecurrentuserhasprivileges,regardlessofowner
DBA_TABLESShowsallthesametableinformationbutforallthe
tablesintheentiredatabase,regardlessofownerortableprivileges
Theseothertwoviewsalsohaveanadditionalcolumn:
OWNERTheownerofthetableinquestion
Andthatmakessense—thereisnoneedforOWNERintheUSER_TABLES
viewsincethatviewshowsinformationaboutonlyoneowner,namely,the
currentowner.
Thisnamingpatternofusingoneofthesethreeprefixes(USER_,ALL_,
DBA_)isapatternthatisusedthroughoutthedatadictionary.Manyofthedata
dictionaryviewsthatstoreinformationaboutobjectsinthedatabasehavenames
thatstartwithoneofthesethreeprefixes.Anoverviewofthesedatadictionary
viewsispresentedinTable12-1.Asyoucanseefromthetable,thevastmajority
ofdatadictionaryviewshaveaprefixofUSER_,ALL_,orDBA_.Asetofthree
viewsthathavetheUSER_,ALL_,andDBA_prefixandsharethesamesuffix,
suchasTABLES,drawtheirdatafromasingledatadictionarytable.For
example,USER_CONSTRAINTS,ALL_CONSTRAINTS,and
DBA_CONSTRAINTSsharethesamedatadictionarytable.Table12-2shows
themostcommonUSER_viewsyou'lluseonaregularbasis.
TABLE12-1 PrefixesofSomeoftheDataDictionaryViews
TABLE12-2 SelectedDataDictionaryViewsShowingObjectsOwnedby
theCurrentUser
NotethatpublicsynonymsarenotlistedintheUSER_SYNONYMSview,
whichshowsonlyprivatesynonyms.Evenifyou’reloggedintoauseraccount
thatcreatedaparticularpublicsynonymobject,you’llstillnotfinditlistedin
theUSER_SYNONYMSview.Instead,you’llfinditinALL_SYNONYMSand
DBA_SYNONYMS.
DynamicPerformanceViews
Table12-1includesreferencestoasetofviewsthatbeginwiththeprefixesV_$
andGV_$.Thesearedefinedasthedynamicperformanceviewsandtheglobal
dynamicperformanceviews.
Dynamicperformanceviewsdisplayinformationaboutcurrentdatabase
activityinrealtime.Theyreceivedatadynamicallyfromthedatabasethrough
mechanismsthatgobeyondthescopeofthisbook.Forourpurposes,it’s
importanttoknowthattheyaremaintainedautomaticallybythesystemandare
availableforquerying—withsomelimitations.
ThedynamicperformanceviewsstartwiththeprefixV_$.Therearepublic
synonymscreatedforeachoftheviews,andtheyhavesimilarnamesbutbegin
withtheprefixV$.
Simplequeriesondynamicperformanceviewsareaccepted,butcomplex
queries,withorwithoutjoins,requiresomespecialattention.Oracleformally
recommendsthatthedynamicnatureoftheseviewsdoesnotguaranteeread
consistencyforanythingotherthanthesimplestofsingle-viewqueries,soit’s
advisedthatyouperformcomplexjoinsand/orqueriesby
Creatingasetoftemporarytablestomirrortheviews
Copyingthedataoutoftheviewsandintoasetoftemporarytables
Performingthejoinonthetemporarytables
Thisway,you’llavoidgettingbadresultscausedbyalackofreadconsistency.
Someofthedynamicperformancesynonyms(whichpointtoviewsthatpoint
totables)includethefollowing:
V$DATABASEIncludesinformationaboutthedatabaseitself,
includingthedatabasename,thedatecreated,thecurrentoperating
systemplatform,andmuchmore
V$INSTANCEIncludestheinstancename,thehostname,the
startuptime,andmuchmore
V$PARAMETERThecurrentsettingsforsystemparameters,such
asNLS_LANGUAGE,NLS_DATE_LANGUAGE,NLS_CURRENCY,
NLS_TIME_FORMAT,NLS_TIME_TZ_FORMAT,
NLS_TIMESTAMP_TZ_FORMAT,SQL_TRACE,andmuchmore
Remember,onlysimplequeriesarerecommendedwhenqueryingthe
V$(v-dollar)viewsdirectly.
V$SESSIONManycurrentsettingsforeachindividualusersession,
showingactiveconnections,logintimes,machinenamesthatusersare
loggedinto,thecurrentstateoftransactions,andmuchmore
V$RESERVED_WORDSCurrentlistofreservedwords,including
informationindicatingwhetherthekeywordisalwaysreserved,andif
not,underwhatcircumstancesitisreserved
V$OBJECT_USAGEUsefulformonitoringtheusageofINDEX
objects
V$TIMEZONE_NAMESIncludestwocolumns:TZNAME,which
istimezoneregion,andTZABBREV,whichisthetimezone
abbreviation
ReadingComments
Thedatadictionaryisrichwithcommentsthathelpdescribetheintentofthe
variousviewsofthedatadictionaryandthecolumnswithinthem.Inadditionto
thecommentsthatareprovidedintheDICTIONARYviewforeachofthe
individualdatadictionaryviews,youcanviewcommentsaboutthecolumns
withinthoseviewsoraboutanyobjectstoredanywhereinthedatabase:
ALL_TAB_COMMENTSDisplayscommentsforallobjectsinthe
database
ALL_COL_COMMENTSDisplayscommentsforallcolumnsof
alltablesandviewsinthedatabase
Sayyou’relookingatadatadictionaryviewlikeUSER_SYNONYMSand
youwanttolearnmoreaboutitscolumns.Here’saquerythatwillhelpyou:
That’sthequery;herearetheresults:
Asyoucansee,we’reusingthedatadictionarytostudythedatadictionary.
Theright-sidelistingunderCOMMENTSishelpfulindescribingthecontentsof
theviewinthedatadictionary.Youcanusethistechniquetoinspectallofthe
contentsofthedatadictionary.
AddingComments
Youcanaddyourowncommentstothedatadictionarytoaddnotesand
descriptionsaboutthetablesandcolumnsyoucreate.TheCOMMENT
statementiswhatweusetoaddcommentstothedatadictionaryforaparticular
databaseobject.Itssyntaxisasfollows:
where:
objectTypeisoneofthekeywordsTABLE,COLUMN,orsome
otherobjectsthatarenotsubjectsofthecertificationexam,suchas
INDEXTYPE,OPERATOR,MATERIALIZEDVIEW,andothers.
fullObjectNameisthenameoftheobjectforwhichyouwanttoadd
acomment.Ifit’saTABLE,namethetable.Butifit’sacolumn,usethe
TABLE.COLUMNsyntax.
c1isthefulltextofthecommentyouwanttoadd.
Whenyouaddacommenttothetable,thecommentwillbedisplayedinthe
datadictionaryviewsUSER_TAB_COMMENTS,ALL_TAB_COMMENTS,
andDBA_TAB_COMMENTS.
Whenyouaddacommenttoacolumninatable,thecommentwillbe
displayedinthedatadictionaryviewsUSER_COL_COMMENTS,
ALL_COL_COMMENTS,andDBA_COL_COMMENTS.
Forexample,let’ssaywewanttoaddacommenttothedatadictionaryabout
thePORTStable.Here’sanexample:
Toseetheresults,youcouldusethisquery:
Here’sanexampleofaddingacommenttoatable’scolumn:
Youcan’treallydropacommentfromthedatadictionary.Instead,you
changeittoablank,likethis:
Let’stakealookatsomeusefulexamplesofthedatadictionaryinaction.
DICTIONARY
TheDICTIONARYviewisagreatstartingpointforanyinvestigationofthe
datadictionary.IfweDESCRIBEtheview,wegetthefollowing:
TherearejusttwocolumnsintheDICTIONARYview,butnotethatthe
secondcolumncanpotentiallyholdagreatdealofinformation.
InourcurrentinstallationoftheOracledatabase(usingacontainerdatabase),
we’reshowing3,228entriesinthisview.Youcanrunasimplequerytolistallof
itscontentsinyourownuseraccount.
Theoutputistoomuchtolisthere,andit’sgenerallythesamehereasitwill
beonyourownOracledatabaseimplementation,dependingonwhichversion
you’reusing.Youmightwanttorunthisqueryinyourownuseraccountand
reviewitsoutput.Ifyou’relookingforsomethingspecific,suchasanythingthat
addressesindexobjects,youmighttryaquerylikethis:
ThatquerywilllocateanythingintheDICTIONARYtablethatmentions
“index”inthecomments.Theresultwillincludethenameofthedatadictionary
viewthatlistsalloftheindexes,theonethatlistsallofthecolumnsuponwhich
anindexisbased,andsoon.
Then,ifyoulocateaparticularentryinthedictionaryyouwanttoknowmore
about—forexample,USER_DEPENDENCIES—youcanrunthefollowing
querytogetcommentsonthatparticularviewanditscolumns:
Thosequeriesshouldhelptozeroinonhelpfulinformationinthedata
dictionary.
IdentifyingaUser’sOwnedObjects
Thereareavarietyofdatadictionaryviewsfromwhichyoumightgatherdata
aboutyourownuseraccount’sobjects.Twoviewsinparticularareagood
startingpoint:USER_CATALOGandUSER_OBJECTS.
USER_CATALOG
TheUSER_CATALOGviewdisplaysasummarylistingoftables,views,
synonyms,andsequencesownedbytheuser.SeeFigure12-1foradescription
oftheview.
FIGURE12-1 DescriptionoftheUSER_CATALOGdatadictionaryview
Here’sasamplequerytogetaquickoverviewofwhataparticularuser
accountmayown:
ThereareonlytwocolumnsinUSER_CATALOG;theyareTABLE_TYPE
andTABLE_NAME,whereTABLE_NAMEisactuallythenameofthetable,
view,sequence,orsynonymobject.
AsynonymforUSER_CATALOGisCAT.
Besureyouhaveatleastabasicworkingknowledgeofeachofthe
datadictionaryviewsthattrackthebasicobjectsinthedatabase—tables,
views,sequences,synonyms,sequences,constraints—andthedifference
foreachwithregardtotheUSER_,DBA_,andALL_prefixes.
USER_OBJECTS
TheUSER_OBJECTSviewcontainsinformationaboutallobjectsownedbythe
user.AsynonymforUSER_OBJECTSisOBJ.SeeFigure12-2fora
description.
FIGURE12-2 DescriptionoftheUSER_OBJECTSdatadictionaryview
InspectingTablesandColumns
TheUSER_TABLEStable(synonymTABS)ishelpfulforinspectingtable
metadata,asisitscompanionUSER_TAB_COLUMNS(synonymCOLS).This
sectionwilllookatUSER_TAB_COLUMNSinparticular.
Let’sgetcolumninformationforthetableshowninFigure12-3.
FIGURE12-3 DiagramoftheINVOICEStable
HereisaSELECTstatementthatwillpullinformationfromthedata
dictionaryaboutthecolumnsofINVOICES:
Here’stheoutput:
Note:Fortherecord,theprecedingSELECTstatementisn’ttotallyperfect.It
onlyaddressesdatatypesofDATE,NUMBER,andVARCHAR2,andinthe
eventaNUMBERdatatypehasaprecisionbutnoscale,theformattingwon’t
comeoutlookingquiteright.Thepointhereistoillustratethesortofqueryyou
mightwanttodoinordertoextractdatadictionaryinformationfromthe
database.
CompilingViews
Oneofthemanyusefultasksyoucanaccomplishwiththedatadictionaryisto
checkforthestatusofaviewthatyou’vecreated.RememberfromChapter10
thataviewisanamedquerybasedonatableandthataftertheviewhasbeen
created,ifthetableisalteredforanyreason,youmayhavetorecompilethe
view.Forexample,ifatable’sstructureisaltered,suchasbyachangetoa
column’sdatatypeorperhapsifacolumnisdroppedfromthetablealtogether(a
columnthatisusedbytheview),thenitmaychangethestatusoftheviewto
INVALID.
Youcancheckthedatadictionary’sUSER_OBJECTSviewtodeterminethe
statusofanyofyourviews,likethis:
Inourcase,hereistheoutput:
Sonowweknowweneedtorecompiletheseviews.SeeChapter10fordetails
abouthowtorecompileaview.
Thedatadictionarycontainsalotofinformationaboutviews,includingthe
queryuponwhichtheviewisbased,whichcanbefoundintheUSER_VIEWS
viewanditsTEXTcolumn.Here’saqueryonthedatadictionarythatasksfor
thequerythatwasusedtocreatetheviewVW_EMPLOYEES:
Hereistheoutput:
Insummary,allthemetadataforyourdatabaseisstoredinthedatadictionary
andisavailablefordisplayandinspection.
CheckingPrivileges
PrivilegesarediscussedinChapter14,whenwediscussuseraccess.Fornow,
notethatprivilegescanbeinspectedusingthefollowingviews:
USER_SYS_PRIVSSystemprivilegesgrantedtothecurrentuser
USER_TAB_PRIVSGrantedprivilegesonobjectsforwhichthe
useristheowner,grantor,orgrantee
USER_ROLE_PRIVSRolesgrantedtothecurrentuser
DBA_SYS_PRIVSSystemprivilegesgrantedtousersandroles
DBA_TAB_PRIVSAllgrantsonobjectsinthedatabase
DBA_ROLE_PRIVSRolesgrantedtousersandroles
ROLE_SYS_PRIVSSystemprivilegesgrantedtoroles
ROLE_TAB_PRIVSTableprivilegesgrantedtoroles
SESSION_PRIVSSessionprivilegesthattheusercurrentlyhasset
Eachcanbeinspectedbytheusertodeterminethecurrentstateofprivileges
androles.SeeChapter14forafulldiscussionofuseraccess,privileges,and
roles,includingsamplequeriesofthesedatadictionaryviews.
InspectingConstraints
TheUSER_CONSTRAINTSviewisoneofthemoreusefulviews.Here’sa
queryyoumightruntocheckthecurrentstateofconstraintsonatable
CRUISES:
Hereisanexampleoftheoutput:
TheoutputlistsalltheconstraintsontheCRUISEStable.We’reseeingfour:
oneprimarykeyandthreeforeignkeys.
HowdoyouknowwhichconstraintisaPRIMARYKEYandwhichisa
FOREIGNKEY?TheanswerisbytheCONSTRAINT_TYPEcolumn.Someof
thepossibleentriesintheCONSTRAINT_TYPEcolumnare
P=PRIMARYKEY
R=FOREIGNKEY(theRisfor“referentialintegrity”)
U=UNIQUE
C=CHECKorNOTNULLconstraint
Note:Thereareadditionalconstraints;thesearebeyondthescopeofthe
exam.
TheDELETE_RULEcolumnshowswhetheraforeignkeyconstraintwas
createdwithONDELETECASCADEorONDELETESETNULL.
TheSEARCH_CONDITIONcolumnisparticularlyusefulforinspecting
CHECKconstraintcriteria.Here’sanexample:
Takenoteoftheconstraintswithunexpectedvaluesfor
CONSTRAINT_TYPE:RforFOREIGNKEY,andCforNOTNULLas
wellasforCHECK.
Thedatadictionaryprovidesadditionalinformationaboutconstraintsinthe
USER_CONS_COLUMNSdatadictionaryview.Thatviewcontainsallthe
informationaboutwhichcolumnsinCRUISESareconstrainedandwhatthe
namesareofthereferencedtablesandcolumnsthatmakeuptheFOREIGN
KEYconstraints.
FindingColumns
HereisonetypeofdatadictionaryqueryIfinduseful:
That’saquerythatlooksforalltablesinthecurrentuseraccountthathappen
tohaveaparticularcolumn—inthiscase,onenamedEMPLOYEE_ID.Ifindit
helpfultosearchforparticularcolumnnamesacrossalltablesorviewsina
givenuseraccount(i.e.,aschema).
Therearemanyhelpfulsoftwaretoolsavailablethatwillextractdata
dictionaryinformation—suchascomments—andprovideanicepoint-and-
clickinterfacetomakeiteasytonavigate.That’sallveryhelpful.But
sometimesyou’llfindyourselfinasituationwhereyousimplydon’thave
accesstothosetools.Youmightevenrealizethataparticularapplication
you’redevelopingcouldbenefitbyprogrammaticallyaccessingdatadictionary
informationbywayofSQLstatementstodrawdataintoyourapplicationfor
someprojectrequirement.Thepointisthatthedatadictionaryisa
certificationexamobjectiveforagoodreason;acomfortableunderstandingof
itsinformationandanabilitytonavigateiteasilyisimportantforanyserious
SQLprofessional.
CERTIFICATIONSUMMARY
Thedatadictionaryisapowerfultool.Itconsistsofaseriesoftablesandviews
thatareautomaticallymaintainedbytheOraclesystemtodocumentthestateof
everyobjectinthedatabase.WheneveraDDLstatementisexecuted,thedata
dictionaryisupdatedinsomefashion.
Thedatadictionaryisoftenreferredtoasmetadata,atermthatmeans“data
aboutdata.”Thedatadictionarycontainsinformationaboutthedatabaseobjects
youcreate—theirstructures,names,status,andmore.
TheSYSaccountownsthedatadictionary’sbasetables,whichcannotbe
changeddirectlybyusers.Instead,allofthetableshaveviewsand,insome
cases,publicsynonymsthathavebeencreated,anditisthesetheuseraccesses
inaread-onlymode.
Manyofthedatadictionaryviewsfollowaprefixpatternthatindicatesthe
contentsoftheview.ViewswithaprefixofUSER_showdataaboutobjects
ownedbytheuseraccessingtheview.ALL_istheprefixforobjectsthatexist
anywhereinthedatabasetowhichthecurrentuserhasaccess.DBA_isthe
prefixforviewsthatshowdataaboutallobjectsinthedatabase,regardlessof
whoownsthemorwhatprivilegesmaybegrantedtothem.
Informationinthedatadictionaryincludesthenamesoftablesandtheir
columns,includingeachcolumn’sdatatype,alongwithitsprecision,scale,
and/orlengthwhereapplicable.Allofthedatabaseobjectsarelistedinthedata
dictionary,includingalltables,views,indexes,sequences,constraints,andmore.
ViewsthathaveaprefixofV$orsomevariationaredynamicperformance
viewsandshowreal-timedatabaseperformanceinformation.Oraclecannot
guaranteethereadconsistencyoftheseviews,soit’srecommendedthatfor
dynamicperformanceviewsyoulimityouraccesstosingle-tablequeries.If
morecomplexqueriesand/orjoinsarerequired,youareadvisedtofirstcopy
dataoutoftheviewsintoyourowntemporarytablesandthenquerythosetables
forbetterresultsanddataintegrity.
Youcanaddcommentstotheentriesinthedatadictionaryforyourown
tablesandcolumnsusingtheCOMMENTstatement.Youcannotdelete
commentsbutinsteadupdatecommentswithablankstring.
Thedatadictionarycanbeusedtoperformavarietyofusefultasks,suchas
obtaininginformationabouttimezones,determiningwhetheraviewrequires
recompilation,identifyinganyprivilegesthatarecurrentlygranted,andmuch
more.
✓TWO-MINUTEDRILL
QueryVariousDataDictionaryViews
Thedatadictionaryismadeoftablesthatstoredataaboutthe
database.
Thedatadictionarycontainsthemetadataforyourdatabase.
Itcontainsinformationabouttables,views,constraints,indexes,
sequences,roles,privileges,andanyandallotherobjectsyoumight
createinthedatabase.
Itkeepstrackofalltheusersinthedatabaseandwhichuser
accountownswhichobjects,whohasprivilegesonwhichobject,the
statusofeachobject,andmore.
Oracleautomaticallyupdatesandmaintainsthedatadictionary
viewswitheachDDLstatementexecutedthroughoutthedatabase.
ThedatadictionaryviewsthatbeginwiththeprefixUSER_contain
informationaboutobjectsownedbytheuseraccessingtheview.
TheALL_prefixindicatesadatadictionaryviewthatcontains
informationaboutobjectsthatmightbeownedbyanyuserinthe
databasebuttowhichtheaccessinguserhasprivileges.
TheDBA_prefixisaffixedtoallviewsthatcontaindataaboutall
objectsinthedatabase.
TheV$orGV$prefixidentifiesviewsthatarepartofthesetof
dynamicperformancetablesandviews,whichshowreal-time
performancedataaboutthedatabase.
Most(butnotall)ofthedatadictionaryviewsarestoredwith
commentsthatprovidebriefdescriptionsabouteachviewandwhatit
contains;manyofthecolumnsoftheviewsalsohavecomments.
Youcanaddcommentsofyourownalongsidethedatadictionary
recordforyourownobjectsthatyou’vecreated.
TheCOMMENTstatementishowyoustoreacommentinthedata
dictionaryforanytableyouownandforitsassociatedcolumns.
TheDICTIONARYviewisagreatstartingpointforfindingwhat
youmightbelookingforinthedatadictionary.
TheUSER_CATALOGviewcontainsasummaryofinformation
aboutsomeofthemajorobjectsownedbyyouruseraccount.
TheUSER_OBJECTSviewissimilartoUSER_CATALOGbut
withmuchmoreinformation.
Youcangetafulllistingfromthedatadictionaryforyourtables;
theircolumns;andassociateddatatypes,lengths,precision,andscale.
Thestatusofobjectsisalsostored;forexample,thedatadictionary
flagsviewsthatareinvalidandmightneedrecompilation.
Allrolesandprivilegesofallusersonallobjectsarestored
somewhereinthedatadictionary.
Ifyouhavethenameofacolumnandaren’tsurewhichtableit
mightbepartof,usetheALL_TAB_COLUMNSdatadictionaryview.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
QueryVariousDataDictionaryViews
1.Oneplacetogetamasterlistofalltheviewsthatformthedata
dictionaryis:
A.DICTIONARY
B.DATA_DICTIONARY
C.CATALOG
D.USER_CATALOG
2.Youaretaskedwithqueryingthedatadictionaryviewthatlistsonly
thosesequencestowhichyoucurrentlyhaveprivilegesbutdon’t
necessarilyown.Todothis,youlogintoyourownuseraccountandquery
thedatadictionaryviewcalled:
A.ALL_SEQUENCES
B.DBA_SEQUENCES
C.USER_SEQUENCES
D.USER_PRIV_SEQUENCES
3.Whichofthefollowingactionswillnotcausethecontentsofthedata
dictionarytobechangedinsomeway?
A.Createanewtable
B.Modifythedatatypeofanexistingcolumn
C.ExecuteavalidCOMMENTstatement
D.Noneoftheabove
4.Thedatadictionaryisownedby:
A.PUBLIC
B.SYS
C.SYSTEM
D.Eachindividualuser
5.Youcanaddyourowncommentstothedatadictionarywiththe
COMMENTstatementusingwhichofthefollowing?(Choosetwo.)
A.INDEX
B.COLUMN
C.SEQUENCE
D.TABLE
6.Youneedtogetinformationaboutcolumnsinatableyoudonotown,
nordoyouhaveprivilegestoit.Whichviewcanyouquerytogetthis
information?
A.DBA_TAB_COLUMNS
B.ALL_TAB_COLUMNS
C.ALL_COLUMNS
D.Can’tbedone
7.Whichamongthefollowingisconsideredanacceptablequerywith
V$DATAFILE?
A.Ajoinwithtwootherobjectsinthedatadictionary
B.AcomplexGROUPBYwithmultiplelevelsofaggregation
C.Aquerythatdisplaysrowsfromthetablewithnojoins
D.Alloftheabove
8.Youaretaskedwiththejobofaddingacommenttothedatadictionary
toaccompanythecolumnPIERinthetableMARINA.Whichofthe
followingwillexecutesuccessfully?
A.COMMENTONCOLUMN(MARINA.PIER)IS'Numberof
piers';
B.COMMENTONCOLUMNMARINA.PIERIS'Numberof
piers';
C.COMMENTONCOLUMNMARINA(PIER)IS'Numberof
piers';
D.COMMENTONTABLECOLUMNMARINA.PIERIS
'Numberofpiers';
9.NowyouhavechangedthepurposeofthePIERcolumninthe
MARINAtableandwanttoremovethecommentyoujustcreatedinthe
previousquestion.Whichofthefollowingstatementswillremovethe
comment?
A.COMMENTONCOLUMNMARINA.PIERDROP;
B.COMMENTONCOLUMNMARINA.PIERISNULL;
C.COMMENTONCOLUMNMARINA.PIERSETUNUSED;
D.COMMENTONCOLUMNMARINA.PIERIS‘’;
10.Whenyou’relookingforaparticularbitofdataandyou’renotsurewherein
thedatadictionaryitmightbe,agoodstartingpointis:(Choosethebest
answer.)
A.SELECT*FROMV$DATABASE;
B.SELECT*FROMGV_$START_HERE;
C.SELECT*FROMDICTIONARY;
D.SELECT*FROMV$RESERVED_WORDS;
11.TheUSER_CONSTRAINTSviewinthedatadictionarylistsFOREIGN
KEYconstraintsintheCONSTRAINT_TYPEcolumnwithwhichofthe
followingsingle-letterabbreviations?
A.K
B.R
C.F
D.G
12.Youaretaskedtoworkwithaview.Theview’sunderlyingtablehasbeen
altered.Whatinformationcanthedatadictionaryprovideatthispoint?
(Chooseallcorrectanswers.)
A.Thestatusoftheviewsothatyoucandeterminewhetherthe
viewrequiresrecompilation
B.Thecurrentstateofthetable
C.Thequerythatwasusedtocreatetheview
D.Thenamesofcolumnsintheunderlyingtable
13.Thetermmetadatameans:
A.Dataaboutdata
B.Globaldatathatisaccessiblethroughoutthedatabase
C.Datathatisautomaticallyupdatedandmaintainedbythe
databasesystem
D.Distributeddata
14.WhichofthefollowingdatadictionaryviewsdoesnothaveanOWNER
column?
A.USER_TABLES
B.ALL_INDEXES
C.DBA_CONS_COLUMNS
D.Alloftheabove
15.IfanALTERTABLE...DROPCOLUMNstatementisexecutedagainstan
underlyingtableuponwhichaviewisbased,thestatusofthatviewinthe
datadictionarychangesto:
A.COMPILE
B.INVALID
C.ALTERED
D.FLAG
SELFTESTANSWERS
QueryVariousDataDictionaryViews
1. A.DICTIONARY.YoucanruntheDESCDICTIONARYcommand
toseethetwocolumnsthatformDICTIONARYandthenqueryitfor
additionalinformation.
B,C,andDareincorrect.Thereisnosystemviewcalled
DATA_DICTIONARY.CATALOGisalsoincorrect;thereisaCATALOG
viewincludedwithOracleforbackwardcompatibilitywithversion5,but
Oracleofficiallydiscouragesitsuse.Ontheotherhand,thereisaviewin
thedatadictionarycalledUSER_CATALOG;it’sarecommendedresource
forfindinginformationabouttables,views,andotherdatabaseobjectsthe
currentuserowns.
2. A.ALL_SEQUENCESwilllistanysequencesinthedatabase,
regardlessofowner,towhichyouraccounthasbeengrantedaccess.
B,C,andDareincorrect.DBA_SEQUENCESwilllistallsequencesin
thedatabase,regardlessofwhoownsthemandregardlessofwhohas
privilegesonthem.USER_SEQUENCESwilllistonlythosesequencesthat
youruseraccountcurrentlyowns.Thereisnoviewcalled
USER_PRIV_SEQUENCES.
3. D.Noneoftheabove.
A,B,andCareincorrect.Allofthesewillenactsomesortofchangeto
theinformationinthedatadictionary.AnyDDLthatcreatesormodifies
objectswillupdatetheobjectlistingsinthedatadictionary.The
COMMENTstatementaddstothedatadictionaryacommentabouta
particularobject.
4. B.SYSistheownerofthedatadictionary.
A,C,andDareincorrect.NeitherPUBLICnorSYSTEMownsthedata
dictionary,althoughbotharevalidusersinthesystem.
5. BandD.TABLEandCOLUMNobjectsaresupportedbythe
COMMENTstatement.
AandCareincorrect.Youcannotaddcommentsofyourowntothedata
dictionaryforanINDEXorSEQUENCEobject.
6. A.DBA_TAB_COLUMNSistheviewthatcontainsinformation
aboutcolumnsintables,andbecauseoftheDBA_prefix,youknowit
containsinformationabouttablesandcolumnsthatexistanywhereinthe
database,regardlessofownerorprivilegesgranted.
A,C,andDareincorrect.ALL_TAB_COLUMNSwouldbecorrectif
youwerelimitingyoursearchtotablesandcolumnstowhichyou’vebeen
grantedprivilegesbecausethatiswhattheALL_prefixindicates.Thereis
noALL_COLUMNSviewinthedatadictionary.
7. C.TheV$prefixindicatesthatV$DATAFILEisapublicsynonym
foradynamicperformanceview,forwhichOracleCorporationdoesnot
guaranteereadconsistency.Therefore,youarerecommendedtolimityour
directaccessofV$objectstosimplequeries.
A,B,andDareincorrect.OracleCorporationofficiallyadvisesagainst
usinganyoftheV$objectsincomplexqueriesand/orjoins.
8. B.ThecorrectsyntaxistousethekeywordsCOMMENTON
COLUMN,followedbythetablenameandcolumnname,separatedbya
period,andthekeywordIS,followedbythestring.
A,C,andDareincorrect.ParenthesesarenotpartoftheCOMMENT
statement.ThekeywordTABLEisusedonlywhenaddingacommenttoa
table.
9. D.Therereallyisn’tastatementtoexplicitlydropacommentor
deleteit.Thepracticeistooverwritetheoldcommentwithanemptystring.
A,B,andCareincorrect.Noneoftheseoptionsisavalidstatement.
Theycontainbitsandpiecesofvalidreservedwordsfromotherstatements
butdonotapplytoCOMMENT.
10. C.TheDICTIONARYviewsummarizesthenamesoftablesandviewsin
thedatadictionary,alongwithdetailedcommentsabouteachone.
A,B,andDareincorrect.TheV$DATABASEand
V$RESERVED_WORDSobjectsarevalidpublicsynonymsfordata
dictionaryviews,butthesearepartofthesetofdynamicperformance
tablesandnotgoodforgettinganoverviewofthedictionaryasastarting
point.ThereisnosuchobjectintheOracledatadictionarycalled
GV_$START_HERE.
11. B.Ristheanswer.Rstandsfor“referentialintegrity”andindicatesthe
presenceofaFOREIGNKEYconstraintintheCONSTRAINT_TYPE
columnoftheUSER_CONSTRAINTSdatadictionaryview.
A,C,andDareincorrect.It’snotKorG.Andyou’dthinkitwouldbeF,
butit’snot.Rmakessense,though,whenyouthinkaboutit.
12. A,B,C,andD.Thedatadictionarycanassistwithalloftheanswers
listed.
Noneareincorrect.
13. A.Metadatais“dataaboutdata.”
B,CandDareincorrect.
14. A.USER_TABLESdoesnothaveorneedanOWNERcolumnsincethe
viewonlypresentsasetoftablesownedbytheuseraccessingthem.
B,C,andDareincorrect.Evenifyouhaven’tlookedindetailatthese
views,youcanrelyonthefactthatviewsthatstartwithALL_andDBA_
haveacolumnshowingOWNERinformationsincetheycontain,by
definition,objectsownedby—potentially—morethanoneuser.
15. B.ItchangestoINVALID.Recompilingtheviewcouldrestorethestatus
oftheviewtoVALID.
A,C,andDareincorrect.
13
ManipulatingLargeDataSets
T
CERTIFICATIONOBJECTIVES
13.01DescribetheFeaturesofMultitableINSERTs
13.02MergeRowsintoaTable
✓Two-MinuteDrill
Q&ASelfTest
hischapterlooksatfeaturesandoperationsthatareusefulforworkingwith
largegroupsofdata.Wecovertwooperationsinparticular.Thefirstconsists
ofadditionalfeaturestotheINSERTstatementthatenableyoutouseone
INSERTstatementtoaddmultiplerowsofdatatoagiventableortoseveral
tables,withandwithoutconditionallogic.Laterinthechapterwe’llcoverthe
SQLstatementMERGE,whichisapowerfulstatementthatenablesyouto
combinethefeaturesofmultipleDataManipulationLanguage(DML)
statementsintoasingleSQLstatement.
CERTIFICATIONOBJECTIVE13.01
DescribetheFeaturesofMultitableINSERTs
ThemultitableINSERTstatementisavariationontheINSERTstatementsyntax
you’vealreadyseen.AmultitableINSERTstatementrepeatstheINTOclauseof
theINSERTstatementtoinsertdataintomorethanonetable.EachINTOclause
appliestojustonetable,butbyrepeatingtheINTOclause,youcanadddatato
multipletables.ThemultitableINSERTmusthaveasubquerytoselectrowsfor
inserting.
MultitableINSERTstatementscanaccomplishavarietyoftasks,including
thefollowing:
Querydatafromonetableandinsertthedataintomultipletables
withconditionallogic,suchastransformingdataintoaseriesofarchive
tables.
Exchangedatabetweentwosimilarsystemsofdifferent
requirements—perhapsbetweenatransaction-basedapplicationanda
datawarehouseoptimizedforanalysis.
Supportlogicalarchivingatanylevelofdetailwithlogicaldecision
pointsembeddedintheINSERTstatements.
IntegratecomplexquerieswithGROUPBY,HAVING,setoperators,
andmore,allwhilemovinganynumberofrowsdynamically,
distributingoutputintomultipledatatargets,andprogramminglogical
decisionpointstocontroldatadistribution.
Transformdatathatisstoredinrowsandlevelsintoacross-
tabulationoutput,thetypeyouwouldtypicallyseeinaspreadsheet
application.
TherearetwogeneraltypesofmultitableINSERTstatements:unconditional
andconditional.
UnconditionalmultitableINSERTstatementsprocesseachofthe
INSERTstatement’soneormoreINTOclauses,withoutcondition,forall
rowsreturnedbythesubquery.
ConditionalmultitableINSERTstatementsuseWHENconditions
beforeINTOclausestodeterminewhetherthegivenINTOclause(or
clauses)willexecuteforagivenrowreturnedbythesubquery.Inother
words,foreachrowreturnedbytheINSERTstatement’ssubquery,each
WHENcondition’sexpressionisconsideredandevaluatestoeitheratrue
orfalsecondition.Iftrue,theassociatedINTOclause(orclauses)will
execute.Iffalse,itwillnot.Finally,anoptionalELSEclausecaninclude
analternativeINTOclausethatcanbeexecutedifnoneoftheWHEN
conditionsistrue.
Let’slookattheoverallsyntaxforthemultitableINSERTstatement.First,
we’llexamineanunconditionalmultitableINSERTstatement.Thesyntax
repeatstheINTOstatementfromonetomanytimesasrequired.
TheunconditionalmultitableINSERTstatementsyntaxjustshownassumes
thefollowing:
ThekeywordALLisrequiredinanunconditionalmultitable
INSERT.Note,however,thatwhilethepresenceofthekeywordALLis
indicativeofamultitableINSERT,itdoesn’tnecessarilyindicatethe
unconditionalmultitableINSERT,asyou’llseeinthenextsection.
FollowingthekeywordALL,theremustbeatleastoneINTO
clause.
YoucanincludemultipleINTOclauses.
EachINTOmayhaveitsownVALUESclause.
EachVALUESlistisoptional;ifomitted,theselectlistfromthe
subquerywillbeused.
ThesubqueryisaSELECTstatementthatcanstandalone.
TheconditionalmultitableINSERTstatementsyntaxissimilarbutaddsthe
WHENcondition,likethis:
Foreachrowreturnedbythesubquery,eachWHENconditionisevaluated
anddeterminedtobeeithertrueorfalse.Iftrue,thentheWHENcondition’s
associatedsetofoneormoreINTOclausesisexecuted;otherwise,processing
skipsovertheINTOclausestothenextWHENcondition.IfnoneoftheWHEN
conditionsevaluatestotrue,theELSEclauseisprocessed,anditsassociatedset
ofoneormoreINTOclausesisexecuted.
TheconditionalmultitableINSERTstatementsyntaxjustshownisusedas
follows:
Theoptionisoneoftwokeywords:ALLorFIRST.
ALListhedefaultandmaybeomitted.
FIRSTisthealternativekeyword;itindicatesthattheonlysetof
INTOclausesthatwillexecutearethosethatfollowthefirstWHEN
clausethatevaluatestotrue.
YoucanincludemultipleWHENconditions.
EachWHENconditionisfollowedbyoneormoreINTOclauses.
EachINTOmayhaveitsownVALUESclause;ifomitted,the
subquery’sselectlistmustmatchthenumberanddatatypesoftheINTO
table’scolumns.
Eachexpressionevaluatestotrueorfalseandshouldinvolveoneor
morecolumnsfromthesubquery.
Thetabandcol_listarethecomponentsoftheINSERTstatement
thatwillexecuteiftheWHENexpressionevaluatestotrue.
TheoptionalELSE...INTOclause,ifincluded,mustbelast.
ThesubqueryisrequiredandmustbeavalidSELECTstatement.
AconditionalmultitableINSERTstatementwillprocesseachrowreturnedby
thesubquery.
ThemultitableINSERTstatementalwaysusesasubquery.Asyouknow,a
subquerymayreturnanywherefromzerotomanyrows.Foreachrowreturned
byasubquery,processingdoesapassthroughthesetofWHILE…INTO
clauses.ButthewayitprocessestheWHILE…INTOclausesdiffersbasedon
whetherthekeywordALLorFIRSTisused.
IfthekeywordALLisspecified,thenalltheWHENconditionswillbe
evaluatedforeachrowreturnedbythesubquery.ForeachWHENconditionthat
evaluatestotrue,thecorrespondingINTOclause(orclauses)thatfollowthe
WHENwillbeexecuted.ForeachWHENconditionthatevaluatestofalse,the
correspondingINTOclause(orclauses)willnotbeexecuted.AlltheWHEN
conditionsareevaluatedifthekeywordALLisspecifiedatthebeginningofthe
multitableINSERTstatement.
Ontheotherhand,ifthekeywordFIRSTisused,thenforeachrowreturned
bythesubquery,WHENconditionsareevaluateduntilthefirsttrueconditionis
encountered.AssoonasaWHENconditionisdeterminedtobetrue,the
correspondingsetofoneormoreINTOclausesthatfollowstheWHENwillbe
executed.ProcessingwillthenskipovertheremainingWHENconditionsfor
thatrowofthesubquery.
Ineithersituation—INSERTFIRSTorINSERTALL—ifnoWHEN
conditionwasfoundtobetrueandiftheoptionalELSEclauseispresent,then
theELSEclause’sINTOclausewillbeexecutedfortherow.Thenprocessing
movesontothenextrowreturnedbythesubquery.
NotethatfortheconditionalmultitableINSERTstatement—whichistosay
anymultitableINSERTwithaWHENcondition—ALListhedefaultkeyword.
IfnoWHENconditionisused,thenthemultitableINSERTisunconditional,and
theALLkeywordmustbepresent.
Inotherwords,youmaynotomitthekeywordinanunconditionalmultitable
INSERT,likethis:
TheprecedingstatementshowsincorrectsyntaxsinceitomitstheALLoption
andyethasnoWHENcondition.Therefore,itissyntacticallyincorrect.
However,youmaydosomethinglikethis:
TheprecedingunconditionalmultitableINSERTcorrectlyshowstheALL
keyword.
TheconditionalmultitableINSERTallowsyoutoomitthekeyword,likethis:
MultitableINSERTstatementsrequireasubquery.
ThedefaultkeywordisALL.InallformsofthemultitableINSERT,the
subqueryisrequired;itisnotoptional.Andasisalwaysthecasewithany
INSERTthatusesasubquery,theINSERTstatementwillexecuteonceforeach
rowreturnedbythesubquery.
NotethatifanyoneINTOclausefailswithanexecutionerrorforanyone
rowreturnedbythesubquery,thentheentirestatementfailsforallrowsofthe
subquery,andnodatachangeresults.
UsetheFollowingTypesofMultitableINSERTS:
UnconditionalandConditional
Let’slookatsomeexamplesofthemultitableINSERTstatementinaction.First
upareunconditionalmultitableINSERTs,followedbyconditionalexamples.
Thenwe’llconsidertheuniqueandusefulapproachtoperformtheequivalentof
aspreadsheetpivot,acommonuseofthemultitableINSERT.
Unconditional
Aswediscussed,theunconditionalmultitableINSERTstatementomits
conditionallogic,inotherwords,theWHENclause.Forexample,considerthe
CRUISE_ORDERStable,asshowninFigure13-1.
FIGURE13-1 DiagramfortheCRUISE_ORDERStable
InadditiontotheCRUISE_ORDERStable,ourexampleusesthree
identicallystructuredtablesnamedCO_2018,CO_ELCARO,and
CO_ARCHIVED,eachwiththesamecolumnsasthetableCRUISE_ORDERS.
Thethreeidenticallystructuredtablesareusedforarchivingandanalyzingthe
CRUISE_ORDERStabledata.
HereisanexampleofavalidSQLstatementthatqueriesthe
CRUISE_ORDERStableandinsertstheoutputintoeachofourthreearchive
tables(linenumbersadded):
NotethatwehavethreeINTOclauseshere.Ifthesubqueryreturns,for
example,threerows,thentheresultofthisINSERTstatementwillbetoinsert
ninerows:threeintotheCO_2018table(line2),threeintotheCO_ELCARO
table(line6),andthreeintotheCO_ARCHIVEDtable(line10).
Asweseeintheprecedingexample,theunconditionalINSERTstatement
usesthekeywordALL(line1),followedbyoneormoreINTOclauses(lines2,
6,and10),eachofwhichspecifiesatableandthecolumnsintowhichweare
insertingdata,followedbytheVALUESlist.
TheVALUESlistcanspecifyexpressionsfoundinthesubquery’sselectlist.
Inourexample,inline4wespecifyCRUISE_ORDER_IDasthefirst
expressionintheVALUESlisttobeinsertedintotheCO_2018table.This
correspondstotheCRUISE_ORDER_IDcolumninthesubqueryselectlistin
line14.TheotherVALUESliststhatrefertoCRUISE_ORDER_ID(line8and
line12)arespecifyingthatsamecolumn.EachVALUESlistinamultitable
INSERTcanspecifyanycolumnnamesorexpressionsthatareinthesubquery
selectlist.
Ontheotherhand,thecolumnreferenceswithineachINTOlist(eachstarting
atlines2,6,and10)specifythecolumnsofthetablesnamedfortheINTO
clause.Inourexample,line2namestheCO_2018table,andtheINTOlistthat
followsonline2andline3specifiescolumnsintheCO_2018table.
You’llrecallthatinastandardINSERTstatement,thelistofvaluesinthe
VALUESexpressionlistmustmatchinnumberandindatatype(orbeabletobe
automaticallyconvertedtoamatchingdatatype)withthecolumnsspecifiedin
theINTOclause.ThesameistruehereforeachpairofINTOandVALUES
lists.
EachVALUESexpressionlistmayuseanycomplexexpressioninspecifying
thevaluetobeinsertedintoitscorrespondingtableandcolumn.Here’san
example:
Inthisexample,wearechoosingtoinsertsomevaluesthataredifferentfrom
whatthesubqueryisreturning.FortheCO_2018table,inlines2through4,we
aredefiningtheORDER_DATEvalueforallrowstobeSYSDATE,the
CRUISE_CUSTOMER_IDvaluetobetheliteralvalueof14,andtheSHIP_ID
valuetobealiteralvalueof1.FortheCO_ELCAROtable,inlines5through7,
wearegivingeachrowanORDER_DATEvaluethatis30daysbeyondthe
incomingvalueinthesubquery,andwe’reassigningthenumber15toeach
CRUISE_CUSTOMER_IDandassigning1toeachSHIP_ID.Forthe
CO_ARCHIVEDtable,inlines8through11,wearechoosingtopassthrough
valuesfromthesubqueryunchanged.
Astheexampleshows,theVALUESlistcanspecifycolumnnamesand
expressionsfromthesubquery’sselectlist,butmayalsodefineanyvalidSQL
expression.TheINTOcolumnlistmustspecifycolumnsinthetableintowhich
theINTOstatementisinsertingdata.
IftheVALUESlistisomitted,thecolumnsofthesubquerybecomethede
factoVALUESlistandthereforemustmatchthecolumnsofthecorresponding
INTOclause.By“match,”wemeanthattheymustmatchinnumberandindata
type,orbeofsuchdatatypesthatanautomaticdatatypeconversionmaybe
performed.
IfthereisnocolumnlistintheINTOclause,thesubquery’sselectlistmust
matchthecolumnsinthetableoftheINTOclause.
Conditional
ConditionalmultitableINSERTstatementsuseconditionallogictodetermine
whichINTOclauseorclausestoprocess.Eachrowthatisreturnedbythe
subqueryisprocessedthroughaseriesofoneormoreWHENconditions.Each
WHENconditionisfollowedbyasetofoneormoreINTOclauses.
Foreachrowreturnedbythesubquery,eachWHENconditionisevaluatedto
beeithertrueorfalse.Iftrue,thefollowingsetofoneormoreINTOclausesis
executed.Iffalse,thesetofoneormoreINTOclausesisskipped,andthenext
WHENconditionisevaluated.
AnELSEclausemayoptionallybeincludedintheconditionalmultitable
INSERTstatement.Ifpresent,itmustdefineitsownsetofoneormoreINTO
clauses,andtheELSE/INTOclausesmustfollowallWHENconditions/INTO
clausecombinations.IfallWHENconditionsareskippedforanygivenrow,
thentheELSEclause’sINTOwillbeprocessed.Otherwise,itwillbeskippedfor
thatrow.
Eachrowreturnedbythesubqueryisprocessedaccordingtotheseruleswe
havejustreviewed.
Let’slookagainatourtableINVOICESandthearchivetable
INVOICES_ARCHIVED,inwhichwestoredinvoicerecordsthataremorethan
ayearold.SeeFigure13-1fortheINVOICEStable,andseeFigure13-2forthe
INVOICES_ARCHIVEDtable.
FIGURE13-2 DiagramfortheINVOICES_ARCHIVEDtable
Let’ssayourorganizationisengagedinamergerandwearetaskedwiththe
jobofintegratingdatafromanotherapplication.Thenewlyacquiredcompany
hasprovideduswiththetableWO_INV,asshowninFigure13-3.
FIGURE13-3 DiagramfortheWO_INVtable
WeneedtocreateanINSERTstatementthatwill
PulldatafromtheWO_INVtable
InsertWO_INV’sinvoiceinformationfromwithinthepastyearinto
ourINVOICEStable
InsertWO_INV’sinvoiceinformationthatismorethanayearold
intoourINVOICES_ARCHIVEDtable
It’saperfecttaskforaconditionalmultitableINSERTstatement,asfollows:
Inthisstatement,weseethefollowing:
Asubqueryonlines10through11.Notethesubqueryincludesa
columnDATE_SHIPPED.
Line2comparestheDATE_SHIPPEDvalueinaWHENcondition.
Ifline2evaluatestotrueforagivenrowfromthesubquery,the
INSERTstatementwilltakethatrow’sdataandinsertitintothe
INVOICES_ARCHIVEDtable,asspecifiedonline3.Thecolumnsin
theINVOICES_ARCHIVEDtablearespecifiedinlines3and4.
Line5definesthevaluesfromthesubquerythatwillbeinsertedif
theWHENclauseonline2istrue.Forexample,thesubquery’scolumn
INV_NO(line5)willbeinsertedintothetargettable’scolumn
INVOICE_ID(line3).
Line6isanELSEclausethatwillexecuteforeachrowthatdoesnot
satisfytheWHENconditioninline2.
Intheexamplewejustreviewed,therewasoneWHENconditionandone
ELSEcondition.Let’slookatanexamplewithmultipleWHENconditions.
Let’ssayyouhadthreearchivetables,namedINVOICES_THRU_2019,
INVOICES_THRU_2018,andINVOICES_THRU_2017,andwantedtoinsert
rowsfromtheincomingtableintoeacharchivedtablebasedontheyearofthe
DATE_SHIPPEDvalue.Notethateachtableisnotmutuallyexclusive;for
example,theINVOICES_THRU_2019tablewillcontaininvoicesfrom2019,
2018,and2017,aswellasearlier.Onerowreturnedbythesubquerymightbe
insertedintoallthreetables.
Toaccomplishthistask,youcouldusethefollowingINSERTstatement:
NoticethatthereisnokeywordFIRSTorALLinthisexample.Therefore,the
statementwilldefaulttoALL.SincetherearethreeWHENconditions,each
withanassociatedINTOclause,eachandeveryWHENconditionthatevaluates
totruewillexecute.Also,thisexampleomitstheELSEclause,soifanyrow
fromthesubquerydoesnotsatisfyaWHENcondition,thennoactionwillbe
takenforthatparticularrowreturnedbythesubquery.
AfteranyWHENcondition,youmayincludemorethanoneINTOclause.
Forexample,let’ssaywehaveatableINVOICES_CLOSEDthattakesany
invoicerowsthatshippedpriorto2018.Wemightmodifyourexamplelikethis:
NotethenewINTOclause,lines10through12.ThisINTOissubjecttothe
WHENconditioninline6.Inotherwords,ifDATE_SHIPPEDisintheyear
2018orbefore,theINSERTstatementwilladdthecandidaterowtoboththe
INVOICES_THRU_2018tableandtheINVOICES_CLOSEDtable.One
WHENconditionisthegatewaytobothINTOclauses.
WhatthisexampleshowsusisthatanyWHENconditioncanhavemultiple
INTOclausesthatfollowit.IftheWHENconditionevaluatestotrue,allofits
INTOclauseswillexecute.IftheWHENconditionevaluatestofalse,execution
willskipovertheINTOclausesandmoveondirectlytoeitherthenextWHEN
condition,anELSEifitispresent,orthenextrowinthesubquery.
TheINSERTALLwillevaluateeachandeveryWHENconditionandprocess
allINTOclausesforallWHENconditionsthatevaluatetotrue.Therefore,the
INSERTALLmayresultinasinglerowbeingaddedtomorethanonetable.
TheINSERTFIRSTwillevaluateeveryWHENconditionuntiloneofthem
evaluatestotrue.ItwillthenprocessthatWHENcondition’sINTOandskipthe
remainingWHENconditions.TheINSERTFIRSTwillprocessonlyzeroorone
WHENcondition;however,itmayalsoresultinasinglerowbeingaddedto
morethanonetable,butonlyifthefirsttrueWHENconditionhasmorethan
oneINTOclause.
TablealiasesinthesubqueryofamultitableINSERTarenotrecognizedin
therestoftheINSERT.Forexample,youcan’treferencethemfromwithina
WHENconditionorINTOstatement.Ifasubquery’scolumnreferencedepends
onatablealias,besuretouseacolumnaliasforthecolumnandthenreference
thecolumnaliasifyouwanttoreferencethatcolumnfromelsewherewithinthe
INSERTstatement—outsideofthesubquery.Forexample,seeFigure13-4.
FIGURE13-4 DiagramofthePOSITIONSandSALARY_CHARTtables
InaquerythatqueriesrowsfromthePOSITIONStableandconditionally
insertsthemintotheSALARY_CHARTtable,wecannotusethisquery:
Thisstatementwillnotwork.Hereistheresult:
Noticehowthesubqueryisaself-joinandusestablealiasestoidentifyeach
tableandcolumnreference.Thesetablealiasesareperfectlyfineinthesubquery
butarenotrecognizedbeyondthesubquery.Inotherwords,theattemptsto
referenceeachtablealiasfromwithintheWHENconditionorVALUESclause
areinvalid.
So,whatdowedo?Thesolutionistospecifyacolumnaliastoanycolumn
nameswithinthesubquerythatuseatablealiasandthenreferencethecolumn
aliasfromtherestoftheconditionalINSERTstatement,likewedointhe
followinglines5and6:
Notethatthisversionhasdonemorethanisrequired;itappliescolumn
aliasestoeachcolumninthesubqueryandthenreferencesthosecolumnaliases
fromtheWHENandVALUESclauses.Weonlyneededcolumnaliaseson
A.POSITIONandB.POSITIONinlines5and6,sowecanreferencethecolumn
aliasesinline4.Eitherway,thisversionoftheconditionalINSERTis
syntacticallycorrect.
YoucannotexecuteamultitableINSERTonaview;itcanbeusedonlywith
atable.
SequencegeneratorsdonotbehaveconsistentlyinamultitableINSERT
statement.Ifyoutrytouseasequencegeneratorwithinthesubquery,you’llget
asyntaxerror.IfyoutrytoincludeonewithintheexpressionlistoftheINTO
statement,youmayormaynotgetthefunctionalityyouwant—theNEXTVAL
functionwillnotadvanceasyoumightexpect.Thereasonisthatamultitable
insertistreatedasasingleSQLstatement.Therefore,ifyoureference
NEXTVALwithasequencegenerator,Oracle’sdocumentationwarnsthat
NEXTVALwillbeincrementedonceinaccordancewiththesequence
generator’sparametersandstaythatwayforthedurationofapassthroughthe
multitableinsert.Inotherwords,aconditionalINSERTwithasingleINTO,one
thatinvokesasinglesequencegeneratoroncewithaNEXTVAL,willincrement
thesequenceonceforeachrowreturnedbythesubquery—regardlessofwhether
theWHENconditionistrue.Considerthisexample:
Remember,atablealiasdefinedinasubqueryofamultitableINSERT
isnotrecognizedthroughouttherestoftheINSERTstatement.Also,ifa
multitableINSERTstatementfailsforanyreason,theentirestatementis
rolledback,andnorowsareinsertedinanyofthetables.
Thesequencegeneratorinline4willincrementforeachrowreturnedbythe
subquery,regardlessofwhethertheWHENconditionistrue.Forthisexample,
assumethesequencegeneratorhasjustbeencreatedandhasneverbeenused
andthatithasthedefaultsettingsofaninitialvalueof1andanincrementof1.
Giventhat,ifthesubqueryreturnstenrowsandif,forinstance,thefinalrow
alonecausestheWHENconditioninline2tobetrue,thentheonerowinserted
intotheINVOICES_ARCHIVEDtablewillbeassignedavalueof10forthe
INVOICE_IDcolumn.
Ifthisstatementcontainedadditionalcallstothesamesequencegeneratorin
additionalINTOclauses,theywouldnotcausethesequencegeneratorto
increment.Thesequencegeneratorincrementswitheachrowofthesubquery
returned—nomore,noless—regardlessofadditionalcallstoNEXTVAL.
Oracle’sdocumentationwarnsthat“youcannotspecifyasequenceinanypart
ofamultitableinsertstatement.”Theonlyplaceyou’llgetthesyntaxerrorisin
thesubquery,butknowthatattemptstoinvokeasequencegeneratorfromthe
WHENorINTOclauseoftheINSERTmayproduceundesirableresults.
UsingMultitableINSERTtoPerformaPivot
YoucanuseaconditionalmultitableINSERTstatementtotransformdatafroma
spreadsheetstructuretoarows-and-columnsstructure.Thissectiondescribesthe
technique.
First,let’sstartwiththefollowingdatalisting:
Thisisthesortofdatayoumightfindinatypicalspreadsheetdisplay.Let’s
saythisspreadsheethasbeenstoredinanexternaltable.Figure13-5showsthe
table’sstructure.
FIGURE13-5 DiagramoftheSHIP_CABIN_GRIDtable
Next,you’regiventhetaskofmovingthisdataintothetable,asshownin
Figure13-6.
FIGURE13-6 DiagramoftheSHIP_CABIN_STATISTICStable
Thisisn’tastraightforwardrow-for-rowinsertwithasubquery.Thisdata
mustbetransformedsothateachcolumnfromthespreadsheetistransformed
intoanindividualrowinthenewtable.
Thefollowingquerywillaccomplishthetask:
Notehoweachrowofthesubqueryisconsideredthreetimes.Foragivenrow
returnedbythesubquery,eachofthreecolumnsoftherowisindividually
considered.IfanyoneofthethreecolumnsOCEAN,BALCONY,and
NO_WINDOWisnotNULL,thenarowisinsertedintothetargettable.It’s
possiblethatsomeindividualrowsreturnedbythesubquerywillresultinthree
newrowsbeingaddedtothetargettableSHIP_CABIN_STATISTICS.
Let’stakealookattheresults:
Inthisexample,theconditionalmultitableINSERTtransformedincoming
datafromaspreadsheetsummarystyleintoarow-by-rowstructure,allwithina
singleSQLstatement.Inthisway,theconditionalmultitableINSERTstatement
“pivots”thedatabychangingcolumnsintorows.
NotethatthispivottechniqueisdifferentfromSQLoperationsthatusethe
keywordPIVOTorUNPIVOT.Whatwe’vedescribedhereisatechniquethat
usestheconditionalmultitableINSERTtopivotdata.ThekeywordPIVOT,
whilesomewhatsimilarinfunction,isaseparatefeature.NotethatOracle’s
publishedmaterial,includingdocumentspublishedinconnectionSQL
certificationexams,havedescribedthismultitableINSERTstyleasapivotand
makesadistinctionbetweenthispivotapproachandthePIVOTkeyword.
CERTIFICATIONOBJECTIVE13.02
MergeRowsintoaTable
TheMERGEstatementisaSQLDMLstatementthatcancombinethe
functionalityofINSERT,UPDATE,andDELETE,allintoasingleSQL
statement.Thereisn’tanythingyoucandowithMERGEthatyoucannotalready
dowithsomecombinationofthosethreeDMLstatements.However,ifit’s
possibletouseMERGEasanalternativetoexecutingtwoormoreDML
statements,thenMERGEispreferablesinceitcombinesmultipleDMLactions
intoasingleSQLstatement,resultinginasinglepassthroughthedatabase.In
otherwords,itwillperformmoreefficiently.Inmanysituations,suchas
applicationsbuiltwithdistributedarchitectures,MERGEmaybeaninvaluable
weaponinyourarsenaltobuildoptimallyefficientprofessionalapplications.
ThesyntaxofMERGEfollows:
Notethefollowing:
Line1INTOspecifiesthetargetintowhichyouareeitherinserting
orupdatingrows;itcanbeatableoranupdatableview.Thislineis
required.
Line2USINGidentifiesthesourceofthedata,whichcanbeatable,
view,orsubquery.Thislineisrequired.
Line3TheONconditionforMERGEbehavesessentiallylikea
WHEREclause.ItdetermineshowtocompareeachrowintheUSING
datasourcewitheachrowintheMERGEINTOdatatarget.TheON
conditioncanuseBooleanoperatorsandexpressionstoformcomplex
comparisons.Inpractice,theONconditionisoftenlimitedtocomparing
primarykeyvalues,butthisisnotrequired.Thislineisrequired.
Lines4through6Theselinesareconsideredthe“updateclause”
andidentifythelogicbywhichtheMERGEwillupdatetargetrows;it
cannotupdateacolumnintheONcondition.
Lines7through9Theselinesareconsideredthe“insertclause”and
identifythelogicbywhichtheMERGEwillinsertrowsintothetarget
table.
Asyoucansee,it’saninvolvedstatement.Let’slookatanexampleinaction.
Let’ssayyouareresponsibleforanapplicationthatusestheWWA_INVOICES
table(seeFigure13-7)andyouhavebeentaskedtobringindatafromanoutside
table,ONTARIO_ORDERS(seeFigure13-8).
FIGURE13-7 DiagramoftheWWA_INVOICEStable
FIGURE13-8 DiagramoftheONTARIO_ORDERStable
ThedatalistingfortheWWA_INVOICEStablefollows:
ThedatalistingfortheONTARIO_ORDERStablefollows:
Let’suseMERGEtobringthedatafromONTARIO_ORDERSintothe
WWA_INVOICEStable.
TheprecedingMERGEstatementincludesthefollowingfeatures:
Line1Herewespecifythatwearegoingtomergerowsintothe
tableWWA_INVOICES.Also,weassignatablealiasWWAtothetable
WWA_INVOICES.
Line2HerewespecifytheONTARIO_ORDERStableasthedata
sourceandgivethattableanaliasofONT.
Line3HerewedefinetheONcondition,indicatingthatthecolumns
CUST_POandPO_NUMarewherethecommoninformationexiststhat
will“join”therowslogicallyinordertoassociatethemwitheachother
forthemerge.
Lines4through5Theselinesarethe“updateclause.”
Lines6through10Theselinesarethe“insertclause.”
Line11ThislineistheWHEREclausefortheMERGE,filtering
outrowsfromtheUSINGdatasource—inthiscase,
ONTARIO_ORDERS.
TheresultofourMERGEistomergerowsfromONTARIO_ORDERSinto
WWA_INVOICES.IfwequerytheWWA_INVOICEStable,herearethe
results,aftertheMERGE:
Noticethefollowing:
WeupdatedtherowwhereCUST_POequalsWWA-001.
WeaddedtherowwhereCUST_POequalsWWA_017.
OurMERGEstatement’sWHEREclausecorrectlyignoredtherow
wherethePO_NUMwasNBC-201.
MERGEisausefulandefficientDMLstatement.Inthisexample,yousaw
howweperformedanINSERTandUPDATEstatementinasingleMERGE
statement.
OurexampledidnotmakeuseoftheDELETEfeatureofthe“updateclause”
withinMERGE.Butwecouldhaveincludedone,likethis:
TheUSINGclausecanbaseaMERGEonasubqueryaswellasa
tableorview.
Inthisexample,we’veaddedline6,whichcontainsthe“deleteclause”for
theMERGE.
Buttakenote:
The“deleteclause”affectsonlyrowsthatarearesultofthe
completed“updateclause”andremaininthetargettable—whichinthis
instanceisWWA_INVOICES.
Rowsaddedasaresultofthe“insertclause”areunaffectedbythe
“deleteclause.”
So,MERGErepresentsacombinationoftheUPDATEandINSERTDML
statementsand,toalesserandsomewhatlimitedextent,theDELETEstatement.
CERTIFICATIONSUMMARY
TheINSERTstatementcanbeaugmentedwithanumberofclausestointroduce
conditionallogicintoitsexecutionandtoadddatatomorethanonetablefrom
withinasingleINSERTstatement.Conditionallogiccanbeaddedwitha
WHENconditionandoptionallytheELSEkeyword.TheINSERTALLform
willtestincomingdataagainsteachWHENcondition,andtheINSERTFIRST
formwillstopatthefirstWHENconditionthatevaluatestotrue.Ineither
situation,theoptionalELSEclausecandefineaninsertthatwillexecuteifall
previousWHENconditionsfailed.ConditionalINSERTstatementsmaybeused
to“pivot”datafromcolumnsintorowsandbackagain.
TheMERGEstatementdoesnotdoanythingyoucannototherwisedowitha
seriesofotherDMLstatements,butitsadvantageisitspowerfulabilityto
performmultipleoperationsfromwithinasingleSQLstatementandthereforea
singleexecutionandsinglepassthroughthedatabase.
✓TWO-MINUTEDRILL
DescribetheFeaturesofMultitableINSERTs
Multitableinsertsareusefulforapplyingconditionallogictothe
databeingconsideredforinsertion.
Conditionallogiccanevaluateincomingrowsofdatainaseriesof
steps,usingseveralevaluationconditions,andcanofferalternative
strategiesforaddingdatatothedatabase,allinasingleSQLstatement.
MultitableINSERTstatementsofferflexibilityandperformance
efficiencyoverthealternativeapproachesofusingmultipleSQL
statements.
MultitableINSERTstatementsmayuseconditionaloperationssuch
astheWHENconditionandtheELSEclause.
AWHENconditioncanbeusedtoevaluateincomingdataand
determinewhetheritshouldbeinsertedintothedatabase,andifyes,
whichtableandwhichcolumnsaretobeinserted.
TheELSEclauseisalastalternativechoicethatwillexecuteifno
WHENconditionevaluatedtotrue.
BothWHENandELSEareassociatedwiththeirownunique
INSERTstatementdirectives;dependingonwhichconditionsapply,the
appropriateINSERTstatementdirectiveswillexecute.
EachconditioncanINSERTdataindifferentwaysintodifferent
tables.
TheINSERTFIRSTstatementtestseachWHENconditionand
executestheassociatedINSERTstatementdirectiveswiththefirst
WHENconditionthatevaluatestotrue.
TheINSERTALLstatementexecutesalltheWHENconditionsthat
evaluatetotrue.
TheELSEclauseexecutesforeithertheINSERTFIRSTor
INSERTALLstatementwhennoneoftheWHENconditionshas
executed.
ThesubqueryofamultitableINSERTdeterminesthedatathatwill
beconsideredintheinsertlogic;itcanbeacomplexqueryandcan
includejoins,GROUPBYclauses,setoperators,andothercomplex
logic.
MergeRowsinaTable
TheMERGEstatementisoneoftheSQLDMLstatements,
alongsideSELECT,INSERT,UPDATE,andDELETE.
MERGEreplicatessomeofthefunctionalityfoundinINSERT,
UPDATE,andDELETEandcombinesitallintoasinglestatementthat
executeswithasinglepassthroughthedatabase.
MERGEdoesn’tdoanythingnewthatyoucannotalreadydowith
existingDMLstatements,butitdoesthemmoreefficientlyin
combination.
TheMERGEstatementincludesan“updateclause”andan“insert
clause.”
TheWHENMATCHEDTHENUPDATEkeywordsformthe
“updateclause.”
TheWHENNOTMATCHEDTHENINSERTkeywordsformthe
“insertclause.”
TheDELETEclauseoftheMERGEstatementonlydeletesrows
thatwerefirstupdatedwiththe“updateclause”andremainaftera
successfulupdate;theymustalsomeettheWHEREconditionofthe
“deleteclause.”
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseonecorrectanswerforeachquestion
unlessotherwisedirected.
DescribetheFeaturesofMultitableINSERTs
1.WhatcananINSERTstatementdo?(Choosetwo.)
A.Addrowsintomorethanonetable
B.Adddataintomorethanonecolumninatable
C.Deleterowsbyoverwritingthem
D.Jointablestogether
2.AmultitableINSERTstatement:
A.Canaccomplishtasksthatcannototherwisebedoneinany
combinationofSQLstatements
B.WillcreateanytablesinwhichitattemptstoINSERTbutthatdo
notyetexist
C.Canuseconditionallogic
D.Iscapableofinsertingrowsintononupdatableviews
3.ReviewthefollowingdiagramsoftheSPAREStable:
AlsoexaminethediagramsofthetablesPORT_INVENTORY,
STORE_INVENTORY,andSHIP_INVENTORY,shownhere.
NowconsiderthefollowingSQLstatement:
RegardingthisSQLstatement,whichofthefollowingstatementsis
true?
A.ThestatementwillfailbecausethereisnoELSEclause.
B.ThestatementwillfailbecauseitismissingaWHENcondition.
C.ThestatementwilladdarowreturnedfromtheSPAREStableto
theSHIP_INVENTORYtableonlyiftheWHENconditiononline2
evaluatestotrue.
D.ThestatementwilladdeveryrowreturnedfromtheSPARES
tabletotheSHIP_INVENTORYtable.
4.ReviewtheSQLstatementintheprecedingquestion.Ifoneofthe
INTOclausesexecutedonatableandresultedinaconstraintviolationon
thattable,whatwouldresult?
A.Therowwouldnotbeinserted,andtheINSERTstatement
wouldskiptothenextrowreturnedbythesubqueryandperform
anotherpassthroughtheWHENconditions.
B.Therowwouldnotbeinserted,andtheINSERTstatementwould
stop.Noadditionalrowswouldbereturnedbythesubqueryor
processed,butrowsthathavealreadybeenprocessedareunaffected.
C.Therowwouldnotbeinserted,theINSERTstatementwould
stop,andallrowsaffectedbytheINSERTstatementwouldberolled
back,asiftheINSERTstatementhadneverbeenexecuted.
D.Noneoftheabove.
5.Reviewthediagramsinquestion3,andconsiderthefollowingSQL
statement:
Whichoneofthefollowinganswerscorrectlyidentifiesdatathat,if
presentintheSPAREStable,willbeinsertedbythisconditionalINSERT
statementintothetable—ortables—identifiedbytheanswer?
A.PART_NO=123;PART_NAME=‘BAH-OPS,’inboth
STORE_INVENTORYandPORT_INVENTORY
B.PART_NO=401;PART_NAME=‘PAN-OPS,’inboth
SHIP_INVENTORYandPORT_INVENTORY
C.PART_NO=170;PART_NAME=‘TRA-OPS,’in
STORE_INVENTORY
D.PART_NO=4;PART_NAME=‘PAN-OPS,’inboth
STORE_INVENTORYandSHIP_INVENTORY
6.Reviewthediagramsinquestion3,andexaminethefollowing
statement:
WhichofthefollowingstatementsistrueforthisSQLstatement?
A.IfthefirstWHENconditioninline2istrue,theINTOclausein
line3andline4willbeexecuted,afterwhichprocessingwillskipto
thenextrowreturnedbythesubquery.
B.IfthefirstWHENconditioninline2istrue,theWHEN
conditioninline7willnotbeevaluated.
C.NomatterwhichWHENconditionistrue,theINTOclausein
line5willbeexecutedregardless.
D.RegardlessofwhetherthefirstWHENconditionistrue,the
secondWHENconditionwillbeevaluated.
MergeRowsinaTable
7.TheMERGEstatementincludesaUSINGclause.Whichofthe
followingstatementsisnottrueoftheUSINGclause?
A.Itcanbeusedtospecifyasubquery.
B.ThedataitidentifiesremainsunchangedaftertheMERGE
statementexecutes.
C.TheUSINGclauseisoptional.
D.Itcanbeusedtospecifyaninlineview.
8.Seethediagramsinquestion3.Youwanttomergerowsfromthe
PORT_INVENTORYtableintotheSHIP_INVENTORYtable.Youstart
withthefollowingSQLstatement:
WhatwillthisSQLstatementdo?
A.ItwillfailwithasyntaxerrorbecauseyoumusthaveanELSE
clause.
B.Itwillfailwithasyntaxerrorbecauseyoucannotreferencethe
targettable(SHIP_INVENTORY)intheWHEREclauseinline8.
C.ItwilladdrowsfromPORT_INVENTORYto
SHIP_INVENTORYthatdonotalreadyexistinSHIP_INVENTORY,
limitedtoLAST_ORDERvaluesfromtheyear2019.
D.ItwilladdrowsfromPORT_INVENTORYto
SHIP_INVENTORYthatdonotalreadyexistinSHIP_INVENTORY,
regardlessofthevalueforLAST_ORDER.
9.ExaminetheSQLsyntaxinquestion8.Whichofthefollowingtwo
alternativesforline3aresyntacticallycorrect?
A.Onlyoption1
B.Onlyoption2
C.Bothoption1andoption2
D.Neitheroption1noroption2
10.Whichofthefollowingstatementsisfalse?
A.Itispossibletomergeintotwoormoretables.
B.Itispossibletomergeintoaview.
C.TheUSINGclausecanreferencetwoormoretables.
D.Youcannotperformanupdatetoacolumnthatisreferencedin
theONclause.
SELFTESTANSWERS
DescribetheFeaturesofMultitableINSERTs
1. AandB.INSERTstatementscanaddrowstomorethanonetable
usingconditionalandunconditionallogic.INSERTstatementscanalsoadd
datatomorethanonecolumninanygiventable.
CandDareincorrect.INSERTcannotoverwritedata;itaddsnewrows
toatable.INSERTdoesnotperformjoins.
2. C.MultitableINSERTstatementscanuseconditionallogic,with
statementssuchasWHENandELSE.
A,B,andDareincorrect.MultitableINSERTSdonotdoanythingyou
couldn’totherwisedowithoneormoreSQLstatements.Theiradvantageis
thattheycanaccomplishcomplexSQLtasksinasinglepassthatmight
otherwiserequiremultiplepassesthroughthedatabase,thusyielding
performanceadvantages.Andnothingcanaddrowsintoanonupdatable
view—ifit’snotupdatable,it’snotupdatable.
3. C.TheWHENconditioninline2determineswhethertheINTO
clausesinlines3,4,5,and6willexecute.
A,B,andDareincorrect.TheELSEclauseisnotrequired.Noparticular
WHENconditionisrequired.TheINTOclauseforSHIP_INVENTORYis
subjecttotheWHENconditioninline2.
4. C.Theentirestatementfails,andallinsertedrowsarerolledback.It
isasifthestatementhadneverbeenexecuted.Hadthisstatementincluded
anycallstoasequencegeneratoranditsNEXTVALpseudocolumnwould
haveadvancedthecountinthegenerator,thateffectwouldremain
unchanged.However,thisexampledoesnotincludeanysequence
generators,sothatparticularexceptiondoesnotapply.
A,B,andDareincorrect.
5. C.ThePART_NOof170hasalengthof3,andthatislongerthan2,
sotheWHEREclauseinline13isfoundtobetrue,andtherowwillbe
evaluatedbytherestoftheINSERTFIRSTstatement.Next,the
PART_NAMEofPAN-OPSwillcausethefirstWHENconditiontobetrue,
andsincethisisanINSERTFIRSTstatement,nootherWHENcondition
willbeconsidered.
A,B,andDareincorrect.Theseanswersresultfromvarious
interpretationsoftheWHENconditionsandELSE.InanINSERTFIRST
statement,thefirstWHENconditionthatevaluatestotrueistheonly
conditionthatisexecuted.Allothersareignored.IfnoWHENisfoundto
betrue,thentheoptionalELSEclausewillbeprocessed.
6. D.BothWHENconditionswillbeevaluatedbecausethe
conditionalINSERTisanINSERTALLstatement.
A,B,andCareincorrect.IfthefirstWHENconditionistrue,bothINTO
clausesthatfollowitwillbeexecuted—thatincludestheINTOonline5
throughline6.WhetherthefirstWHENconditionistrueorfalse,the
secondwillalsobeevaluatedsincethisisanINSERTALLstatement.The
INTOinline5throughline6willbeevaluatedonlyifthefirstWHEN
conditionistrue.
MergeRowsinaTable
7. C.TheUSINGclauseisnotoptional;itisrequiredintheMERGE
statement.
A,B,andDareincorrect.USINGcanidentifyatable,view,orsubquery.
Aninlineviewisalsoacceptable.Itidentifiesthesourceofdatatobe
merged;thesourcedataremainsunchangedaftertheMERGEstatementis
executed.
8. B.ItwillfailbecausetheWHEREclausereferencessomethingthat
isnotinthesourcetable.TheWHEREclauseisanextensionofUSING,
whichspecifiesthetargettable.TheAtablealiasreferenceismeaningless
andwillfail.
A,C,andDareincorrect.ThereisnoELSEclauseinMERGE,soitis
notonlynotrequired,itisnotaccepted.
9. C.Bothoptionsareacceptable.TheONconditioncanbeany
comparisonofexpressions,anditcanincludeBooleanoperators.
A,B,andDareincorrect.
10. A.YoucannotMERGEintotwoormoretables.Onlyoneispermitted.
B,C,andDareincorrect.YoucanMERGEintoaviewprovidedthe
viewisupdateable.TheUSINGclausecanreferencetwoormoretablesby
wayofajoinorsubquery.Youcannotchangethevaluesofajoincriteria
duringthejoin,soyoucannotupdatecolumnsthatarereferencedinanON
clause.
14
ControllingUserAccess
T
CERTIFICATIONOBJECTIVES
14.01DifferentiateSystemPrivilegesfromObjectPrivileges
14.02GrantPrivilegesonTablesandonaUser
14.03DistinguishBetweenPrivilegesandRoles
✓Two-MinuteDrill
Q&ASelfTest
hischapterexploresthesubjectofuseraccessandtheprivilegesassociated
withperformingactionsinthedatabase.Everyactionperformedbyanyuser
accountrequiresacorrespondingprivilegeorsetofprivilegestoperformthat
action.Therearetwocategoriesofprivileges.Systemprivilegesarerequiredto
performataskinthedatabase;objectprivilegesarerequiredtousethosesystem
privilegesonanygivendatabaseobjectinparticular.Privilegesmaybegranted
toauseraccountortoanotherdatabaseobjectcalledarole.Arole,inturn,can
begrantedtoauseraccount,whicheffectivelygrantsthesetofprivileges
collectedwithintherole.Oncegranted,privilegesandrolescanlaterberevoked.
Together,privilegesandrolesarethemechanismformanagingandcontrolling
accesstothedatabasebyuseraccounts.Thischapterlooksathowtocreateand
manageprivilegesandroles.
Awordofwarningaboutthesamplecodecontainedinthischapter:someof
ithastheabilitytochangeyourdatabasepermanentlywithresultsthatmaybe
undesirable.SomeofourcodesampleswilllookatSQLcodethatusesthe
SYSTEMuseraccount,animportantaccountthatshouldbecontrolledby
experienceddatabaseadministratorsinanyproductiondatabase.Youshould
alwayscheckwithyourdatabaseadministrator(DBA)beforetryinganycode
samplesfromanybook,butthischapterinparticularincludescodethatyou
shouldnotexecuteinaprofessionalinstallationwithoutfirstcheckingwithyour
DBA.
CERTIFICATIONOBJECTIVE14.01
DifferentiateSystemPrivilegesfromObjectPrivileges
Throughoutthisbook,we’velookedathowauseraccountcanuseSQL
statementstocreateanduseavarietyofdatabaseobjects.However,beforeany
useraccountcanexecuteaSQLstatement,itmustbegrantedtheprivilegeto
executethatSQLstatement.Furthermore,onceadatabaseobjecthasbeen
created,anyuseraccountthatwillusethedatabaseobjectmustfirstbegranted
privilegestodoso.
Therearethreegeneralcategoriesofprivileges,asdescribedinTable14-1.
TABLE14-1 TypesofPrivileges
We’llrevieweachoftheitemslistedinTable14-1inthischapter.
SystemPrivileges
Systemprivilegesaretherighttoperformsometaskinthedatabase.For
example,tologintothedatabase,auseraccountisgrantedthesystemprivilege
CREATESESSION.Tocreateatable,auseraccountmustbegrantedthesystem
privilegeCREATETABLE.
Therearemorethan100differentsystemprivilegesthatcanbegrantedtoa
useraccount.Table14-2listssomeofthesystemprivilegesthatarerequiredto
performthetaskswe’vediscussedinthisbook.
TABLE14-2 SomeSystemPrivileges
Systemprivilegesdifferfromobjectprivilegesinthatsystemprivilegesare
whatauseraccountmusthavetocreatedatabaseobjects,amongotherthings.
Then,onceadatabaseobjecthasbeencreated,objectprivilegesonthatdatabase
objectcanbegrantedtootherusers.
Forexample,therighttoexecutetheSQLstatementCREATETABLEand
createanewdatabasetableisasystemprivilege.Buttheabilitytochangerows
ofdatain,forexample,atablecalledBENEFITSownedbyauseraccount
namedEUNICEisanobjectprivilege.Inotherwords,anobjectprivilegeisthe
righttodosomethingtoaparticularobject.
Asananalogy,considertheconceptofadriver’slicense.Adriver’slicenseis
sortoflikeasystemprivilege;it’stherighttodriveacarinageneralsense.
Onceyouhaveadriver’slicense,ifyougetacar,youcandriveit.Butyoudon’t
havetherighttodriveanyone’scarinparticularunlesstheownerspecifically
authorizesyoutodoso.
Therighttodrivesomeoneelse’scarislikeanobjectprivilege.Youneed
bothoftheseprivilegesinordertodriveacarandtobeinfullcompliancewith
thelaw.Thesameistrueinthedatabase:youneedsystemprivilegestoperform
particulartasks,andyouneedobjectprivilegestoperformthosetasksonan
objectinparticular.
Let’slookatsomeofthesyntaxforgrantingprivileges.Notethatforsomeof
theupcomingexamples,we’llusetheSQL*PlustoolandsomeSQL*Plus
commands.TheseSQL*Pluscommandsdonotrequirethesemicolon
terminationcharacterthatisrequiredinSQLstatements.
We’llusetheSQL*PluscommandCONNECTtologintoanotheruser
account.YoucanalsousetheSQL*PluscommandSHOWUSERtoconfirm
whichaccountiscurrentlyactiveinthesession.SQL*Pluscommandsare
helpfultouseinyourSQLsessions.Buttheyarenotontheexam.
Prerequisites
BeforewegetstartedwithGRANTandREVOKEstatements,let’sreviewsome
supportingstatementsthataren’tspecificallyincludedintheexamobjectivesbut
areusefulfordemonstratingsystemprivileges,objectprivileges,roles,andtheir
capabilities.
CREATE,ALTER,andDROPUSER
Let’slookathowtocreateauseraccount.AnySQLuserwiththeCREATE
USERsystemprivilegemayexecutetheCREATEUSERstatement,whose
syntaxlookslikethis:
CREATEUSERusernameIDENTIFIEDBYpassword;
Inthisstatement,usernameisanameyouspecifyaccordingtotherulesfor
namingdatabaseobjects.Thepasswordfollowsthesamerules.(Notethat
passwordsarecasesensitivebydefaultstartingwithOracle11g.)
Forexample,thisstatementwillcreateausernameJOANwiththepassword
DEMERY:
CREATEUSERJOANIDENTIFIEDBYDEMERY;
YoucanusetheALTERUSERstatementtochangethepassword,likethis:
ALTERUSERJOANIDENTIFIEDBYHAWAII;
Finally,youcanremoveauserfromthedatabaseusingtheDROPUSER
statement,likethis:
DROPUSERusername;
Ifauseraccountownsanydatabaseobjects,theprecedingstatementwon’t
work,andyou’llneedtousethis:
DROPUSERusernameCASCADE;
TheCASCADEoptiondirectsSQLtodroptheuseraccountandallofthe
objectsitowns.
Onceauserobjecthasbeencreated,itcanbegrantedprivileges,asyou’llsee
inanupcomingsection.
CONNECT
TheCONNECTstatementisnotaSQLstatementbutaSQL*Plusenhancement
youcanusewithintheOracleSQL*Plustool.Onceyou’vestartedSQL*Plus,
youcanuseCONNECTtologinorswitchloginsessionsfromoneuseraccount
toanother.If,forexample,youareusingtheSQL*Plustoolandhaveloggedin
totheEFCODDaccountandcreatedtheuseraccountJOAN,youcanloginto
theJOANaccountdirectlyfromEFCODDwiththisstatement:
CONNECTJOAN/HAWAII
ThisassumestheuseraccountJOANisstillusingthepasswordHAWAII.It
alsoassumesthatJOANhasbeengrantedtheminimumsystemprivilegestolog
in,suchasCREATESESSION.
Again,asemicolonterminationcharacterisnotrequiredinSQL*Plus
statements.Itisacceptedbutnotrequired.Thesemicolonterminationcharacter
isrequiredinSQLstatementsbutisoptionalinSQL*Plusstatements.
Tablespaces
Inthecourseofsettingupanewuseraccount,thetopicoftablespacesmustbe
addressed.However,thetopicoftablespacesgoesbeyondourscopeandisnot
includedintheexamobjectives,sowe’llshowthesimplewaytoaddressthe
tablespacerequirement,asfollows:
ThiswouldprobablynotbesomethingthatyourtypicalproductionDBA
woulddo.Tablespacesarecontrolledbydatabaseadministrators.AtypicalDBA
generallycreatesuniquelynamedtablespacesandcarefullyallocatesspace
quotastothem.We,however,aren’tconcernedwithanyofthatforthisbookor
fortheexam.Soforus,theprecedingstatementiswhatwe’llinclude.Ifyou
wanttolearnmore,weencourageyoutocheckoutanyoftheoutstandingbooks
fromOraclePressonthetopicofdatabaseadministration.Inthemeantime,if
you’reworkingonyourowntestsystemonyourownpersonalmachine,this
particularstatementthatgrantsUNLIMITEDTABLESPACEismorethan
adequateforourpurposesgoingforward.Ifyou’reusingtheseatwork,check
withyourDBAbeforetryinganyofthecodesamplesinthischapter.
GRANTandREVOKE
Nowlet’sgetdowntobusiness.SystemprivilegesaregrantedwiththeGRANT
statement.Here’sanexampleofaSQLsessionthatlogsintotheOracle
SYSTEMaccount,createsanewuser,andgrantsthenewuseraccountsome
initialsystemprivilegesusingthreeGRANTstatements(linenumbersadded):
Inthesestatements,hereiswhatwearedoing:
Line1WeestablishausersessionwiththeuseraccountSYSTEM,
withapasswordofMANAGER.TheSYSTEMaccountisinstalledwith
everyOracledatabase,andtheDBAinstallingOracleassignsthe
password.(Warning:Donottrythisonaproductionsystem.Noself-
respectingproductionsystemshouldhaveaSYSTEMaccountpassword
settoavalueofMANAGERanyway,butthepointisthatifyouhave
installedyourownversionoftheOracledatabaseonyourownlocal
machineanditisnotusedforproductionwork,thenyoucantrythis,but
ifyou’retryingthingsoutwithinasystematyourworkplaceor
somewherecomparable,thenbesuretocheckwithyourdatabase
administratorbeforetryingthis.)
Line2WecreateanewuseraccountcalledHAROLD,withthe
passwordLLOYD.
Line3WeusetheSQLstatementGRANTtogivetheCREATE
SESSIONprivilegetouserHAROLD.Thisisaminimumrequirement
forustobeabletologintothedatabasewiththeHAROLDuser
account;withoutthisGRANTstatement,wecouldn’tsuccessfullylogin
withtheuseraccountHAROLD.
Line4ThisisonewaytoensurethatHAROLDcancreateobjects.
Seeourearlierdiscussionabouttablespacesintheprevioussection.
Line5UsingGRANT,wegivethesystemprivilegeCREATE
TABLEtouseraccountHAROLD.
SeeFigure14-1fortheresultsofthesestatementsintheSQL*Pluswindow.
FIGURE14-1 SQL*Plussession:GRANTstatements
Nowlet’slogintoHAROLDandtryoutwhatwe’vedone.Forthat,we’lltry
thefollowingSQLstatements:
SeeFigure14-2fortheresults.Notethatwearen’tabletocreatethesequence
becausewehaven’tbeengrantedsufficientprivilegestodoso.Forthat,we’ll
needtologbackintotheSYSTEMaccountandgrantthesystemprivilege
CREATESEQUENCEtoHAROLD.Oncethathasbeenaccomplished,wecan
logbackintoHAROLDandcreatethesequence(seeFigure14-3).
FIGURE14-2 SQL*Plussession:testingsystemprivileges
FIGURE14-3 SQL*Plussession:creatingthesequence
Intheseexamples,wehavebeenloggedintotheSYSTEMaccounttogrant
theseprivileges,butanyqualifiedDBAaccountwilldoandispreferableinany
seriousinstallationwithmultipleOracleusers.Insuchasituation,thelesstimea
developerorDBAspendsintheSYSTEMaccount—ortheotherrestricted
defaultDBAaccountsintheOracledatabasesuchasSYS—thelesslikelya
mistakewillaccidentallycausesomeseriousdamagetothedatabase.
ThebasicsyntaxfortheGRANTstatementissimple.
Here,privilegeisoneoftheseveraldozensofsystemprivilegesthatare
alreadydefinedinthedatabase(seetheOracleDatabaseSQLLanguage
ReferenceManualforacompletelist).Multipleprivilegescanbegrantedatonce
byseparatingeachadditionalprivilegewithacomma,asinGRANTprivilege,
privilege.(We’lldiscussoptioninanupcomingsection.)
ThebasicsyntaxforREVOKEiscomparable.
NotethatyougrantTOandyourevokeFROM.
Onceasystemprivilegeisrevokedfromauser,theeffectisimmediate.
However,anyactionstakenpriortotherevocationstand.Inotherwords,ifa
useraccounthasbeengrantedthesystemprivilegeCREATETABLEandthen
createssometablesbutthenhastheCREATETABLEsystemprivilegerevoked,
thecreatedtablesalreadyinexistenceremaininplace.Theydonotdisappear.
ButtheowningusermaynotcreateadditionaltableswhiletheCREATETABLE
systemprivilegeisrevoked.
We’velookedatafewsystemprivileges,andwe’vesaidthattheyare
somewhatlikeadriver’slicense.Nowlet’sextendtheanalogyalittlebit:
imaginewhatwouldhappenifyoucouldgetauniversaldriver’slicensethat
carriedwithittheabilitytodriveanyone’scarlegallywithoutthecar’sowner
expresspermission.SuchaconceptexistswithintheOracledatabase,andit’s
embodiedinthekeywordANY.Let’slookatthatnext.
ANY
SomesystemprivilegesincludethekeywordANYinthetitle.Forexample,
thereisasystemprivilegeCREATEANYTABLE,whichistheabilitytocreate
atableinanyuseraccountanywhereinthedatabase.Let’slookatasample
sessionthatinvolvesthisprivilege.
TheresultoftheprecedingSQLstatementsisthattwouseraccountswillbe
created.Also,twotableswillbecreated,withonetablecalledMOVIESand
anothertablecalledTVSHOWS.Bothtableswillexistintheuseraccount
LAUREL.ThefirsttablewascreatedbyLAUREL,butthesecondtable,
TVSHOWS,wascreatedbyuseraccountHARDYandwascreatedasatable
thatisownedbyLAUREL.TheuseraccountHARDYwillcontainnotables.
Theofficial“owner”ofbothtablesisLAUREL,asthedatadictionaryconfirms.
WhenasystemprivilegeincludesthekeywordANYinitstitle,itmeansthat
theprivilegewillauthorizeausertoperformthetaskasthoughtheywereany
useraccount.Inthisexample,userHARDYwasabletocreateatableandplace
itintheLAURELaccount,atasktypicallyreservedonlyforuserLAUREL.
However,sinceuserHARDYhasthesystemprivilegeCREATEANYTABLE,
thenHARDYcancreateanytableinanyuseraccount.
ADMINOPTION
InaprevioussectionwesaidwewouldlookattheoptionintheGRANT
statement’ssyntaxweexamined.Hereitis:theoptionisanadditionalclausethat
maybeincludedwiththeGRANTstatement,asfollows:
WhenanysystemprivilegeisgrantedwiththeWITHADMINOPTION
option,thentherecipientreceivesthesystemprivilegeitself,alongwiththeright
tograntthesystemprivilegetoanotheruser(seeFigure14-4).
FIGURE14-4 GRANTversusGRANTWITHADMINOPTION
TheREVOKEstatementdoesnotusetheWITHADMINOPTIONclause.
Wheneverasystemprivilegeisrevoked,theentiresystemprivilegeisrevoked.
Ifauser—let’scallitthefirstuser—grantsasystemprivilegetoasecond
userWITHADMINOPTIONandtheseconduserusestheadminoptionto
grantthatsamesystemprivilegetoathirduser,thenthethirduserretainsthe
privilegeuntilitisexplicitlyrevokedfromthethirduser.Inotherwords,once
theseconduserhasgrantedthethirduserwiththesystemprivilege,itstayswith
thefirstuser,evenifthefirstuser—oranyotherqualifieduser—revokesthe
systemprivilegefromtheseconduser.Ifthathappens,thethirduserstillhasthe
systemprivilege.Theonlywaythethirduserwilllosethesystemprivilegeisif
anyqualifieduserrevokesthesystemprivilegeexplicitlyfromthethirduser
withaREVOKEstatement.Inotherwords,theREVOKEstatementforsystem
privilegesdoesnot“cascade.”Itappliesonlytotheusertowhomtherevocation
isapplied.
ALLPRIVILEGES
Asanalternativetograntingspecificsystemprivileges,aqualifieduseraccount,
suchasSYSTEMorsomeotherDBAqualifiedaccount,canissuethefollowing
statement:
Thisstatementhastheeffectofgrantingallsystemprivilegestotheuser.The
WITHADMINOPTIONclausemaybeusedwiththisaswell.
Needlesstosay,thisshouldbedonewithgreatcaution,ifatall.Itisnot
easilyreversible.Inotherwords,thefollowingisnotanexactcounterpart:
Thisstatementwillreverseallsystemprivilegesgrantedtotheuser,assuming
thatallsystemprivilegeshavebeengrantedtotheuser.Ifnot,anerrormessage
willresult.
PUBLIC
ThePUBLICaccountisabuilt-inuseraccountintheOracledatabasethat
representsallusers.AnyobjectsownedbyPUBLICaretreatedasthoughthey
areownedbyalltheusersinthedatabase,presentandfuture.
TheGRANTstatementwillworkwiththekeywordPUBLICintheplaceofa
useraccountname.Here’sanexample:
ThisstatementgrantstheCREATEANYTABLEprivilegetoeveryuserin
thedatabase.TheCREATEANYTABLEprivilegegiveseveryusertheability
tocreateanytableinanyotheruseraccount.Inotherwords,it’smasshysteria—
orsomethinglikeit.Mindyou,we’renotrecommendingyoudothis,butit’s
syntacticallypossible,andyouneedtobeawareofit.Whilethissortofan
exampleisunlikely,grantingtoPUBLICmaybeusefulwithaselectednumber
ofobjectprivileges,whichwe’lldiscussabitlater.
Notethatifyoucometoyoursensesanddecidetorevokeasystemprivilege
fromPUBLIC,youcandosowithoutrevokinganyothersystemprivileges.In
otherwords,considerthisstatement:
REVOKECREATEANYTABLEFROMPUBLIC;
Notethatifyouwanttograntallprivileges,youusethekeywordsALL
PRIVILEGES.Butifyouwanttograntcertainprivilegestoallusers,
youdonotusethekeywordALL.Instead,yougranttoPUBLIC.
ThisstatementwillreversetheGRANT…TOPUBLICthatweissuedafew
paragraphsearlierandthankfullywillnotrevokeanyindividuallygranted
CREATEANYTABLEsystemprivilegesheldbyanyuseraccounts.Itwill
revokeonlytheGRANTtoPUBLIC.
Ifyou’reeventhinkingaboutusingGRANTALLPRIVILEGESTOPUBLIC
WITHADMINOPTION,youcanputthatthoughtoutofyourmindrightthis
second.
CERTIFICATIONOBJECTIVE14.02
GrantPrivilegesonTablesandonaUser
AnyuserwiththesystemprivilegeCREATETABLEcancreateatable.The
table,oncecreated,isownedbytheuserwhocreatedit.Theownerdoesnot
requireanyexplicitlygrantedprivilegesonthetable.Thetableownercanuse
DMLtoaddrows,changedatainthetable,querythedatainthetable,and
removerowsfromthetable.Butotherusersdonothavethatprivilege
automatically.Otherusersmusthaveexplicitlygrantedprivilegesontheobject,
which,inthiscase,isatable.
(Note:Theexception,ofcourse,isthoseuserswhohavethesystem
privilegesthatallowthemtorunanyDMLstatementsonanytableinthe
database,regardlessofwhoownsit.Thosesystemprivileges,aswesawinthe
previoussection,includeSELECTANYTABLE,INSERTANYTABLE,
UPDATEANYTABLE,andDELETEANYTABLE.)
Anyuserwhoownsatable—oranyotherdatabaseobject—maygrantobject
privilegesontheirdatabaseobjecttootherusersinthedatabase.
ObjectprivilegesexistforallDMLstatements—SELECT,INSERT,
UPDATE,andDELETE—aswellasanyDDLstatementthatisrelevanttoan
existingobject,suchasALTER,forexample.Notethatthereisnoseparateset
ofobjectprivilegesfortheMERGEstatement.
ObjectprivilegesonatableincludealltheDMLstatementsthatcanbe
executedagainstatable.Forexample,ifauseraccountLISAhasthesystem
privilegeCREATETABLE,thenLISAcancreateatable.IfLISAtakes
advantageofthissystemprivilegeandcreatesatableWEBINARS,thenLISA
canaccessthenewtable,butotherusersarenotautomaticallyabletoseethe
table(unless,aswestatedearlier,thoseuserspossessoneoftheANYsystem
privileges,suchasSELECTANYTABLE).Toensurethatotheruseraccounts
canexecuteSQLstatementsonthetable,useraccountLISAwillhavetogrant
objectprivilegesonWEBINARStootherusers.
SeeFigure14-5foraSQL*PlussessioninwhichweconnecttotheSYSTEM
account,wherewecreatetwouseraccounts,LISAandHENRY.WegiveLISA
sufficientprivilegestoconnect(CREATESESSION)andcreatetables.Note
howwecombinedmultiplesystemprivilegesinasingleGRANTstatement.
Also,wegiveHENRYsufficientprivilegestocreateasession—butnothing
more.
FIGURE14-5 Creating,granting,andtestingobjectprivileges—part1
WecontinueinFigure14-6,whereweconnecttotheLISAaccountandcreate
atable,adddatatoit,andthengrantprivilegesonthetabletoHENRY.Thenwe
connecttoHENRY,wherewecanissueSELECTandUPDATEstatementsbut
notINSERT—thatparticularprivilegewasn’tgrantedtoHENRY.
FIGURE14-6 Creating,granting,andtestingobjectprivileges—part2
TakeanotherlookatFigure14-6,andnotethemomentthattheGRANT
statementisissued.RememberthatanyDDLstatementcarrieswithitan
implicitcommitevent.Inotherwords,theGRANTstatementhastheeffectof
makingtheresultsoftheINSERTstatementpermanentinthedatabase.Once
thatGRANThasexecuted,theoptiontorollbacktheINSERTstatementwith
ROLLBACKisnolongeravailable.
SchemaPrefixes
NoteinFigure14-6thatwhenHENRYreferencesatableownedbyLISA,
HENRYmustusetheschemaprefixtomakethereference.Inotherwords,
HENRYcouldnotissueaSELECTstatementlikethis:
ASYNONYMisanobjectinthedatabasethatisanalternativenamefora
databaseobject.APUBLICSYNONYMisaSYNONYMthatisownedbythe
PUBLICuseraccount,whichisanautomaticallycreateduseraccountthatis
maintainedbytheOracledatabase.ThePUBLICuserisn’tintendedtobean
accountintowhichyoulogintogetaccess.Instead,PUBLICisamechanismby
whichyoucancreategloballyownedobjects.Specifically,anythingthatis
ownedbyPUBLICisautomaticallyownedbyallusersinthedatabase.The
sameistrueforPUBLICSYNONYMS.
Inourearlierexample,theuserSYSTEMcouldhavegivenuserLISAthe
systemprivilegetocreatepublicsynonymsbyissuingthefollowingstatement:
Then,later,theuserLISAcouldhaveusedthatsystemprivilegetocreatea
PUBLICSYNONYMlikethis:
Finally,onceuserHENRYgotaroundtoissuingDMLstatementsonthe
WEBINARStable,HENRYcouldhaveomittedtheschemaprefixandinstead
simplyexecutedthisstatement:
Inthisinstance,HENRYwouldbespecifyingtheWEBINARSobject
PUBLICSYNONYM,whichinturnpointstotheobjectLISA.WEBINARS.
NotethatnoobjectprivilegehadtobegrantedonthePUBLICSYNONYM
objecttoHENRY.AllobjectsownedbyPUBLICareautomaticallyavailable
andaccessibletoallusersinthedatabase,presentandfuture.However,
privilegesmustbegrantedtowhateverobjectforwhichthePUBLIC
SYNONYMservesasanalias.It’sonethingtohaveprivilegesonaPUBLIC
SYNONYMthatreferencesatable,butit’sanotherthingtohaveprivilegeson
thetableitreferences.Allusershaveprivilegesautomaticallyonanyobject
ownedbyPUBLIC;theydonothaveautomaticallygrantedprivilegeson
anythingaPUBLICSYNONYMreferences;suchprivilegesmustbegranted
explicitly.
ThissortofusageisthemostcommonpurposeofthePUBLICSYNONYM
object.
NotethattocreatePUBLICSYNONYMobjects,auseraccountmusthave
theCREATEPUBLICSYNONYMsystemprivilege.
NamePriority,Revisited
YoumayrecallourdiscussioninChapter2aboutaconceptcallednamespace.
Whenausermakesareferencetoanobjectbyname,SQLwillusethatnameto
searchforthatobjectasfollows:
First,SQLlooksinthelocalnamespace,whichcontainsobjects
ownedbytheuseraccount:tables,views,sequences,privatesynonyms,
andsomethingcalleduser-definedtypes(theseobjectsarebeyondthe
scopeoftheexam).
Next,SQLlooksinthedatabasenamespace,whichcontainsusers,
roles,andpublicsynonyms.
ThisconceptwasdemonstratedgraphicallyinFigure2-2.
WITHGRANTOPTION
Ifyouwanttograntanotheruseraparticularobjectprivilegeandincludethe
abilityfortheusertograntthatsameobjectprivilegetoyetanotheruser,then
includetheWITHGRANTOPTIONclauseintheGRANTstatement.Here’san
example:
ThisgrantgivesuserHENRYtheabilitytoissueSELECTandUPDATE
statementsontableWEBINARS,alongwiththeabilitytograntthoseprivileges
tootherusers.HENRYisnotobligatedtograntthesetofprivilegestogether;
HENRYcanchoosetobeselective.
NowuserHAROLDhastheabilitytoissueSELECTstatementson
LISA.WEBINARS,aswellastheabilitytograntthatprivilegetoothers.But
HENRYdidnotpassalongtheUPDATEprivilege.
REVOKE
UserLISAmaychoosetorevokeprivilegesfromHENRY,likethis:
IfuserLISAdoesthis,thenHENRYandHAROLDloseallprivileges,as
doesanyonetowhomtheyextendedprivilegeswiththeirWITHGRANT
OPTIONoption.
Inotherwords,therevocationofobjectprivileges“cascades.”Notethatthis
isdifferentfromsystemprivilegerevocation,whichdoesnotcascade,aswe
statedearlierinthischapter.
NotethattheREVOKEstatementdoesnotrequiretheWITHGRANT
OPTIONclause.REVOKEdoesn’tcarewhetherthatoptionhadbeenincluded;
itjustrevokesallspecifiedprivilegesandcascadesthechangethroughoutall
useraccountsasrequired.
ALLPRIVILEGES
TheALLPRIVILEGESoptionworkswithgrantingandrevokingobject
privilegesinmuchthesamewayitdoeswithsystemprivileges,withsome
differences.Here’sanexample:
ThisstatementgivesallprivilegesontheobjectWEBINARStoHENRY,
exceptfortheabilitytograntprivileges.Togranttheabilitytogrant,usethis:
ThekeywordPRIVILEGESisnotrequiredwhengrantingobjectprivileges.
ThesameistruewithREVOKEwhenusedwithobjectprivileges.
Thefollowingisalsogood:
Thisshorthandwayofrevokingobjectprivilegessparestheeffortof
identifyingalltheindividualobjectprivilegesthatmayhavealreadybeen
grantedtoHENRYontheWEBINARStableandrevokesthemallatonce.
NotethatthekeywordPRIVILEGESisoptionalwhenworkingwithobject
privileges,butnotwhenworkingwithsystemprivileges.
IfyouuseREVOKEALLtorevokeobjectprivilegesfromauserandno
objectprivilegesexistontheobjectforthatuser,thennoerrormessageresults,
andthestatementexecutessuccessfullywithnopracticaleffect.
DependentPrivileges
IfuserAownsaview,whichisbasedonatablethatuserAalsoowns,anduser
AgrantsprivilegesontheviewtouserB,thenuserBcanaccesstheview
withoutprivilegestotheunderlyingtable.
IfuserAcreatesatableandapublicsynonym,thenuserBhasimmediate
visibilityofthepublicsynonymbecausethesynonymisownedbyPUBLICand
allusershavevisibilityofallobjectsownedbyPUBLIC.However,userBstill
requiresprivilegesonthetableforwhichthepublicsynonymisanalias.Ifthe
publicsynonymreferencesaviewthatuserAowns,thenuserBmusthave
objectprivilegesontheview,butisnotrequiredtohaveaccesstoitsunderlying
table.
Ifyougrantprivilegesonatableandthendropthetable,the
privilegesaredroppedwiththetable.Ifyoulaterre-createthetable,you
mustalsogranttheprivilegesagain.However,ifyourestoreadropped
tablewiththeFLASHBACKTABLE…BEFOREDROPstatement,you
willrecoverthetable,itsassociatedindices,andthetable’sgranted
privileges,andyouwillnotneedtogranttheprivilegesagain.
ViewPrivilegesintheDataDictionary
We’vealreadylookedatthedatadictionaryandseenhowitprovides
informationaboutthestateofobjectsinthedatabase,aswellasprovidingsome
historicinformation.
Therearemanyviewsinthedatadictionarythatpresentinformationabout
systemprivilegesandobjectprivileges.SeeTable14-3foralistingofsomeof
theseviews.
TABLE14-3 DataAboutPrivilegesintheDataDictionary
Forexample,toseewhatsystemprivilegesaregrantedtoyourcurrentuser
account,youcanquerythedatadictionaryviewUSER_SYS_PRIVS.Here’s
whattheresultsmightlooklikefromuseraccountLISA:
TheequivalentdatadictionaryviewDBA_SYS_PRIVSallowsyoutoseethe
sameinformationforotherusers.
Aprivilegemaybegranteddirectlyasaprivilegeorindirectlyaspart
ofarole.Ifyouintendtodropaprivilegefromauser,usethedata
dictionarytodeterminewhetherthatsameprivilegeisgrantedtoarole
thatisalsograntedtothesameuser.Ifso,thentheprivilegeyoudropped
directlyisstillgrantedtotheuserindirectlythroughtherole.
Toseealltheobjectprivilegesthatyourcurrentuseraccountmayhave
grantedtoothersorthatmayhavebeengrantedbyothers,youcanusethe
followingquery.Thisiswhattheresultsmightlooklikewithintheuseraccount
LISA:
NotethatthefirstseveralrowsshowobjectprivilegesgrantedbyEFCODD
toLISA.ThefinaltworowsshowobjectprivilegesgrantedbyLISAtoHENRY.
Thesearejustafewexamplesofthesortofinformationthedatadictionary
providesaboutsystemprivilegesandobjectprivilegesthathavebeengrantedto
andfromuseraccountswithinthedatabase.
WheninspectingdatadictionaryviewslikeDBA_TAB_PRIVSor
DBA_SYS_PRIVStoseewhatprivilegeshavebeengrantedtoaparticular
useraccount,youcanchecktheGRANTEEcolumnfortheappropriateUSER
name.However,don’tforgettoalsocheckforrowswhereGRANTEE=
'PUBLIC';theseprivilegesarealsoavailabletoyouruseraccount.
GrantRoles
Aroleisadatabaseobjectthatyoucancreateandtowhichyoucanassign
systemprivilegesand/orobjectprivileges.Youcanalsoassignotherrolestoa
givenrole.Onceitiscreated,youcangrantaroletoauserjustasyoucangrant
privilegestoauser.Theuseristhenautomaticallygrantedanyprivileges
containedwithintherole.Aroleisanexcellentwaytomanagethevarious
privilegesrequiredforperformingdifferenttasksinthedatabaseandtoorganize
theprocessofgrantingandrevokingprivileges.
Youmaygranttheroletoasmanyuseraccountsasyouwant.
Ifanyprivilegeissubsequentlyrevokedfromtherole,itisalsorevokedfrom
anyuserstowhomtherolehasbeengranted.Inotherwords,changestoroles
cascadetotheuserstowhomtheroleisgranted.
Threerolesinparticularhavehistoricallybeenassociatedwithstandard
Oracledatabases,buttheyarebeingphasedout.Onapracticallevel,though,it’s
goodtoknowaboutthem,ifyoudon’talready.ThethreerolesareCONNECT,
RESOURCE,andDBA.TheCONNECTroleconsistsoftheCREATE
SESSIONsystemprivilege,intendedforthetypicalgenericenduser.
RESOURCEisacollectionofsystemprivilegesintendedforthetypical
applicationdeveloper.DBAisintendedforthetypicaldatabaseadministrator.
EachcanbeseenindetailinthedatadictionaryviewDBA_SYS_PRIVS(see
Table14-4fordetails).Allthreerolesarestillincludedineachimplementation
oftheOracledatabaseasofthiswriting,butOraclehasstatedformallythatthe
useoftheserolesisnowofficiallydiscouraged,andtheirinclusioninfuture
databaseimplementationsisnotguaranteed.OracleCorporation’sofficial
positionisthatyoushouldcreateyourownsetofrolesasrequired.
YoucanrefertothedatainTable14-4togetanideaofthekindofsystem
privilegesyoumaywanttoincludeinyourROLEobjects.
TABLE14-4 TheClassicRolesCONNECT,RESOURCE,andDBA
Tocreatearole,auseraccountneedstheCREATEROLEsystemprivilege.
Forexample,theuseraccountEFCODDownsseveraltablesandwantsto
grantprivilegesonthesetablestosomeusersinthedatabase.Someofthese
userswillbeperformingqueriesonthetablesandnothingmore.Otherswillbe
responsibleforperformingchangestothedata.Therefore,wewanttocreatetwo
differentrolesandgrantthemthenecessaryprivileges.
Intheprecedingcode,wecreatetwoROLEobjects:onecalled
CRUISE_ANALYST,towhichwegrantsomeSELECTprivilegesontables,and
anothercalledCRUISE_OPERATOR,towhichwegrantsomeotherprivileges.
Oncetheyarecreated,wecangranttheserolestouseraccountsinthedatabase.
Oncearoleisgranted,auserhasaccesstoalloftheprivilegeswithinit.
Arolecanbegrantedtoanotherrole.
ArolecanbegrantedWITHADMINOPTIONtoempowertherecipientto
granttheroletoyetanotheruser.Here’sanexample:
IfausergrantsaroletoanotheruserandusesWITHADMINOPTION,the
secondusermayfurthergrantthesameroletoathirduser.Ifthefirstuser
revokestherolefromtheseconduser,thethirduserretainstheroleuntilitis
explicitlyrevokedfromthethirduserbyaqualifieduser.
Table14-5listssomeofthedatadictionaryviewsthatprovideinformation
aboutexistingrolesinthedatabase.
TABLE14-5 DataDictionaryViewswithInformationAboutROLEObjects
Rolesexistinanamespacethatresidesoutsideofanyuseraccount.
Therefore,youcancreateroleswithnamesthatarethesameasobjectswithina
useraccount,suchastablesandviews.That’snotnecessarilyagoodidea,but
it’sallowedinthedatabase.
Auseraccountmaybegrantedmultiplerolesatonce.
Let’ssayyoucreateanobject,thengrantaprivilegeonthatobjecttoa
role,andthengranttheroletoauser.Ifyoudroptheobject,thenyou
alsodropthegrantedobjectprivilegetotherole.However,therolestill
exists,andthegrantoftheroletotheuserstillexists.Ifyousubsequently
re-createtheobjectandthengranttheobjectprivilegetotheroleonce
again,thenyou’vere-createdthesituationbeforetheobjectwasdropped.
Inotherwords,youdonotneedtore-createtheroleorgranttheroleto
theuseronceagainsinceneitherwasaffectedbytheactofdroppingthe
objectonwhichtheprivilegehadoriginallybeengranted.
CERTIFICATIONOBJECTIVE14.03
DistinguishBetweenPrivilegesandRoles
Aroleobjectdoesnotrepresentprivilegesinandofitself.Itismerelya
collectionofzeroormoreprivileges.Aroleexistsindependentlyofthe
privilegesitmay—ormaynot—contain.Furthermore,therelationshipauser
accounthastoagrantedroleisseparatefromanyprivilegesthatmayhavebeen
granteddirectlytotheuseraccount.Inotherwords,ifauseraccountalreadyhas
anyobjectprivilegesgranteddirectlytoitasaresultofearlierGRANT
statementsandthenlaterisgrantedarolethatduplicatesanyofthoseprivileges,
thentheroleexistsseparatelyfromthoseoriginallygrantedprivileges,which
existindependentlyoftherole.Iftheroleislaterrevoked,thatrevocationdoes
notadverselyaffectanyseparatelygrantedprivilegesgivendirectlytotheuser
account.
IfuserHENRYwerealreadygrantedaprivilegethathappenstobeduplicated
withintheroleCRUISE_ANALYSTandthensubsequentlytheroleisgranted
butthenisrevoked,likethis:
thenanyobjectprivilegesgranteddirectlytoHENRYstillexist.
Forexample,examinethefollowingcode:
UserHENRYstillhasSELECTonINVOICESbecauseofline1,inspiteof
lines2through5.
Similarly,iftheroleisrestoredbutthedirectobjectprivilegeisrevoked,
HENRYstillhasaccessthroughtherole.Here’sanexample:
Rememberthat“privileges”mayrefertoeithersystemprivilegesor
objectprivileges,whichareverydifferent.
Rolesconsistofsomecombinationofoneormoresystemand/orobject
privilegesand/orotherroles.
HENRYstillhasprivilegesonINVOICESinspiteofline5.Thereasonisthe
CRUISE_ACCOUNTANTrole,fromlines2through4.
However,iftheobjectprivilegerevokedfromHENRYinline5werealsoto
berevokedfromtheCRUISE_ACCOUNTANTrole,thentheobjectprivilege
wouldberemovedfromHENRYaltogether.
CERTIFICATIONSUMMARY
Asystemprivilegeistherighttoperformataskinthedatabase,usingaDDL,
DCL,orDMLstatementonobjectsingeneral.Therighttoperformthosetasks
onaparticularobjectinthedatabaseisanobjectprivilege.Finally,arole
combinesprivilegesintoasingleobjectsothatacombinationofprivilegescan
bemanagedasagroup.
TheSQLstatementsGRANTandREVOKEareusedtoissuesystem
privilegesandobjectprivilegesandtotakethemaway.Privilegesaregivento—
ortakenawayfrom—useraccounts.Anyuserinthedatabasemusthave
privilegestoperformanytask.TheactoflogginginrequirestheCREATE
SESSIONsystemprivilege.OtherprivilegesincludeCREATEPUBLIC
SYNONYMandCREATETABLE.
TheANYkeywordinasystemprivilegeindicatestheabilitytoworkwith
objectsthatareownedbyanyuseraccount.
Auseraccount,bydefault,hasobjectprivilegesontheobjectsitowns.
Objectprivilegesarerequiredforausertobeabletointeractwithobjectsitdoes
notown.
Insteadofgrantingprivilegestoauser,youmaycreatearole,thengrant
privilegestoarole,andthengranttheroletooneormoreusers.Theadvantage
isthatifyouhavemultipleusers,aroleismucheasiertochangesinceyoucan
grantorrevokeprivilegesasdesiredaftertherolehasbeenassignedtoany
numberofusers,andalloftheuserswillautomaticallyhavethenewprivileges
grantedorrevokedautomatically.
Thedatadictionaryprovidesinformationaboutsystemprivileges,object
privileges,androlesfromtheperspectiveofboththegrantorandthegrantee.
✓TWO-MINUTEDRILL
DifferentiateSystemPrivilegesfromObjectPrivileges
TherighttouseanygivenSQLstatementand/ortogenerally
performataskinthedatabaseisasystemprivilege.
Therighttoperformsometaskonaspecificexistingobjectinthe
databaseisanobjectprivilege.
Bothsystemandobjectprivilegesaregrantedtoandrevokedfrom
usersinthedatabase.
SystemprivilegesmaybegrantedWITHADMINOPTION,which
providestheabilityfortherecipienttograntthesameprivilegetoyet
anotheruser.
Whenasystemprivilegeisrevoked,therevocationdoesnot
cascade,meaningthatitisrevokedonlyfromtheuserfromwhomitis
beingrevoked,notfromotheruserstowhomtherevokedusermayhave
extendedtheprivilege.
TheALLPRIVILEGESkeywordscanbeusedtograntorrevoke
allprivilegestoorfromauser.
GrantPrivilegesonTablesandonaUser
ObjectprivilegescorrespondtoDMLstatementsandtoDDL
statementsthatarerelevanttoexistingobjects.
ObjectprivilegesmaybegrantedWITHGRANTOPTION,which
providestheabilityfortherecipienttograntthesameprivilegetoyet
anotheruser.
Whenanobjectprivilegeisrevoked,therevocationcascades,
meaningthatitisrevokedfromtheuserfromwhomitisbeingrevoked,
aswellasfromotheruserstowhomtherevokedusermayhaveextended
theprivilege.
Whenauserhasbeengrantedaccesstoanobject,theobjectname
willrequireaschemanameprefixtobecorrectlyidentified.
APUBLICSYNONYMcanprovideanalternativenameforthe
schema-prefixedversionofthegrantedobject.
TheALLPRIVILEGESkeywordscanbeusedtograntorrevoke
allprivilegestoorfromauser.
Avarietyofdatadictionaryviewsprovideinformationabout
systemandobjectprivileges.
Usersmayseeprivilegesgrantedtothem,orgrantedbythemto
others,byqueryingthedatadictionary.
AroleiscreatedwiththeCREATEROLEstatement.
RolesmaybegrantedWITHADMINOPTION,whichprovidesthe
abilityfortherecipienttograntthesameroletoyetanotheruser.
Rolesexistinanamespaceoutsideofanindividualuseraccount.
Aroleisacollectionofprivilegesandotherroles.
Arolemaybegrantedtoanotherrole.
DistinguishBetweenPrivilegesandRoles
Aprivilegegranteddirectlytoauserexistsindependentlyfroma
privilegegrantedtoarole.
Ifyourevokeaprivilegedirectlyfromauserwhoalsohasbeen
grantedarolecontainingthesameprivilege,theroleremains
unchanged,andtheuserstillhasprivilegesbywayoftherole.
Thesamesituationistruewithregardtorevokingprivileges
directlyfromroles;ifyourevokeaprivilegefromarolethatauser
alreadyhasthroughadirectgrant,thedirectgrantstaysinforce.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthe
materialpresentedinthischapter.Chooseoneanswerforeachquestion,unless
otherwisedirected.
DifferentiateSystemPrivilegesfromObjectPrivileges
1.WhichofthefollowingSQLstatementswillauthorizetheuseraccount
JESSEtocreatetablesineachandeveryuseraccountinthedatabase?
A.GRANTCREATEALLTABLETOJESSE;
B.GRANTCREATEPUBLICTABLETOJESSE;
C.GRANTCREATEANYTABLETOJESSE;
D.GRANTCREATETABLETOJESSEWITHPUBLIC
OPTION;
2.YouareloggedintouseraccountFREDandhavebeentaskedwith
grantingprivilegestotheuseraccountETHEL.Youexecutethefollowing
SQLstatements:
Assumingbothstatementsexecutesuccessfully,whatistheresult?
A.ETHELdoesnothavethesystemprivilegeCREATEANY
TABLEortherighttogranttheCREATEANYTABLEsystem
privilegetoanyotheruser.
B.ETHELhasthesystemprivilegeCREATEANYTABLE
becausetheWITHADMINOPTIONclausewasn’tincludedinthe
REVOKEstatement.
C.ETHELnolongerhasthesystemprivilegeCREATEANY
TABLEbutstillhastherighttogranttheCREATEANYTABLE
systemprivilegetoanyotheruser,sincetheWITHADMINOPTION
clausewasomittedfromtheREVOKEstatement.However,ETHEL
maynotgranttheCREATEANYTABLEprivilegetoherself.
D.ETHELnolongerhasthesystemprivilegeCREATEANY
TABLEbutstillhastherighttogranttheCREATEANYTABLE
systemprivilegetoanyotherusersincetheWITHADMINOPTION
clausewasomitted.Furthermore,ETHELmaygranttheCREATE
ANYTABLEprivilegetoherselfbecauseoftheWITHADMIN
OPTIONclause.
3.Whichofthefollowingisthesystemprivilegethatisrequiredasa
minimumtoallowauseraccounttologintothedatabase?
A.CREATEANYLOGIN
B.CREATEANYSESSION
C.CREATESESSION
D.CREATETABLE
4.Whichofthefollowingisthesystemprivilegethatempowersthe
granteetocreateanindexinhisorherownuseraccountbutnotinthe
accountsofothers?
A.CREATETABLE
B.CREATEANYTABLE
C.CREATEINDEX
D.CREATEANYINDEX
GrantPrivilegesonTablesandonaUser
5.YouruseraccountownsatableBACK_ORDERS,andyouwantto
grantprivilegesonthetabletoauseraccountnamedCARUSO,which
alreadyhasthesystemprivilegesCREATESESSIONandUNLIMITED
TABLESPACE.ExaminethefollowingSQLstatement:
Oncethisstatementhasbeenexecuted,whichofthefollowing
statementswillbetrueforuserCARUSO?
A.CARUSOwillhaveSELECTprivilegesonBACK_ORDERS
butnottheabilitytogiveotherusersSELECTprivilegeson
BACK_ORDERS.
B.CARUSOwillhaveSELECTprivilegesonBACK_ORDERS,as
wellastheabilitytogiveotherusersSELECTprivilegeson
BACK_ORDERS.
C.CARUSOwillhaveSELECT,INSERT,UPDATE,andDELETE
privilegesonBACK_
ORDERSbutnottheabilitytogiveotherusersthosesameprivileges
onBACK_ORDERS.
D.CARUSOwillhaveSELECTandALTERTABLEprivilegeson
BACK_ORDERSbutnottheabilitytogiveotherusersthosesame
privilegesonBACK_ORDERS.
6.Youruseraccountownsanupdatableview,BACKLOG,whichis
basedonthetablePROJECTS.YouaretaskedtogiveSELECTand
UPDATEcapabilitiestoanotheruseraccountnamedMARINO.Currently,
MARINOhasnoprivilegesoneitherthetableortheview.Youwantfor
MARINOtohavetheabilitytograntSELECTontheviewtootherusersas
well.ExaminethefollowingSQLcode:
Whichofthefollowingstatementsistrue?
A.Thestatementswillfail,andMARINOwillnotbeabletouse
theview.
B.Thestatementswillexecutesuccessfully,butMARINOwillnot
beabletoSELECTfromtheviewbecausethePROJECTStablehas
notbeengrantedtoMARINO.
C.Thestatementswillexecutesuccessfully,andMARINOwillbe
abletoSELECTfromtheviewbutnotUPDATEtheview.
D.Thestatementswillexecutesuccessfullyandperformas
intended.
7.UseraccountMUSKIEownsatablecalledCBAY.Whichofthe
followingstatementscanbeexecutedbyMUSKIEandenableuser
ONEILLtoexecuteUPDATEstatementsontheCBAYtable?(Choose
three.)
A.GRANTALLONCBAYTOONEILL;
B.GRANTALLPRIVILEGESTOONEILL;
C.GRANTALLTOONEILL;
D.GRANTINSERT,UPDATEONCBAYTOONEILL;
8.Examinethefollowingtwoclaims:
[1]TheDBA_TAB_PRIVSdatadictionaryviewallowsauser
accounttoseeobjectprivilegesithasgrantedtootheruseraccounts.
[2]TheDBA_TAB_PRIVSdatadictionaryviewallowsauser
accounttoseeobjectprivilegesgrantedbyotheruseraccountsto
itself.
Whichoftheseclaimsistrue?
A.Only1
B.Only2
C.Both1and2
D.Neither1nor2
9.Whichofthefollowingdatadictionaryviewscontainsinformation
aboutgrantsontablesthathavebeenmadebyotheruserstoyouruser
account,aswellasgrantsontablesthathavebeenmadebyyouruser
accounttootheruseraccounts?
A.USER_TAB_COLUMNS
B.USER_TAB_PRIVS
C.USER_TABLES
D.ALL_TAB_PRIVS_RECD
10.Whatcanbegrantedtoarole?(Chooseallthatapply.)
A.Systemprivileges
B.Objectprivileges
C.Roles
D.Noneoftheabove
11.WhichofthefollowingstatementswillgranttheroleOMBUDSMANtouser
JOSHUAinsuchawaythatJOSHUAmaygranttheroletoanotheruser?
A.GRANTOMBUDSMANTOJOSHUAWITHADMIN
OPTION;
B.GRANTOMBUDSMANTOJOSHUAWITHGRANT
OPTION;
C.GRANTOMBUDSMANTOJOSHUAWITHROLEOPTION;
D.GRANTOMBUDSMANTOJOSHUACASCADE;
12.UserHARDINGownsatableTEAPOT.UserHARDINGthenexecutesthe
followingSQLstatementstogiveaccesstothetabletouserALBERT:
WhichofthefollowingstatementscanuserALBERTnowexecuteon
theTEAPOTtable?
A.SELECT*FROMDOME.HARDING.TEAPOT;
B.SELECT*FROMHARDING.DOME.TEAPOT;
C.SELECT*FROMHARDING.TEAPOT;
D.Noneoftheabove
DistinguishBetweenPrivilegesandRoles
13.Arole:
A.Takestheplaceofprivilegesautomaticallysothatanyprivilege
grantedtoarolesupersedesanygrantsthathavealreadybeengranted
directlytoauser
B.Cannotbegiventhesamenameasatable
C.Canbegrantedtoauser,whocanbegrantedonlyoneroleata
time
D.CanbecreatedbyauseronlyifthatuserhastheCREATE
ROLEsystemprivilege
14.YouhaveatableFURNISHINGSandaretoldtograntDELETEprivileges
onthetabletouserHEARST.ExaminethefollowingSQLstatements:
NowyouaretoldtochangetheprivilegesgiventoHEARSTsothat
HEARSTcannolongerexecuteDELETEstatementsonthe
FURNISHINGStable.Whichofthefollowingwillaccomplishthegoal?
(Choosethebestanswer.)
A.REVOKEDELETEONFURNISHINGSFROMHEARST;
B.REVOKEDELETEONFURNISHINGSFROMMGR;
C.REVOKEDELETEONFURNISHINGSFROMHEARST,
MGR;
D.Noneoftheabove
15.Assumeadatabasewiththreevalidusers:NEIL,BUZZ,andMICHAEL.
Assumeallusershavetheappropriateprivilegestheyrequiretoperform
thetasksshownhere.AssumeNEILownsatablecalledPROVISIONS.
Examinethefollowingcode(assumeallpasswordreferencesarevalid):
Whatobjectisidentifiedinline11bythenamePROVISIONS?
A.Thepublicsynonymcreatedinline7
B.Thesynonymcreatedinline10
C.Nothing,becauseuserNEILdidnotincludeWITHGRANT
OPTIONSintheGRANTSELECTONPROVISIONSTOBUZZ
statement
D.Somethingelsenotlistedabove
SELFTESTANSWERS
DifferentiateSystemPrivilegesfromObjectPrivileges
1. C.ThesystemprivilegeCREATEANYTABLEisthesystem
privilegethatyou’relookingforinthisquestion.ThekeywordANYis
foundinmanysystemprivilegestoindicatethattheuserauthorizedwith
thesystemprivilegemayperformthetaskasthoughitwereanyuser
accountinthedatabase.
A,B,andDareincorrect.ThereisnoALLkeywordinthiscontext,and
PUBLICdoesnotapplyhere.ThereisnosystemprivilegewiththeWITH
PUBLICOPTIONkeywords.
2. A.TheWITHADMINOPTIONclauseisnotallowednorneededin
theREVOKEstatement.
B,C,andDareincorrect.Theyareallinterestingideas,buttheyareall
wrong.
3. C.TheCREATESESSIONsystemprivilegeistheminimum
requirement.
A,B,andDareincorrect.ThereisnosystemprivilegeCREATEANY
LOGINorCREATEANYSESSION.CREATETABLEisnotrequiredto
establishausersession.
4. A.TheCREATETABLEprivilegealsoincludestheabilitytocreate
anindex.RememberthataCREATETABLEstatementmayincludethe
PRIMARYKEYorUNIQUEconstraint,which—ifcreated—will
automaticallycausethecreationofanindextosupporteachconstraint.
B,C,andDareincorrect.Thereisn’taCREATEINDEXsystem
privilege.TheabilityisincludedwithCREATETABLE.CREATEANY
TABLEempowersthegranteetheabilitytocreatetablesintheaccountsof
others,whichpotentiallymayalsocreateindicesinthosesameaccounts.
CREATEANYINDEXisavalidsystemprivilegeforcreatingindex
objectsinuseraccountsotherthanyourown.
GrantPrivilegesonTablesandonaUser
5. A.GRANTSELECTONtableTOusergivestheusertheabilityto
SELECTonthetableandnothingmore.
B,C,andDareincorrect.TogiveCARUSOtheabilitytoSELECTon
thetableaswellastograntotherusersSELECT,theWITHGRANT
OPTIONclausewouldneedtohavebeenincludedwiththeGRANT
statement,asinGRANTSELECTONBACK_ORDERSTOCARUSO
WITHGRANTOPTION.TogranttheotherDMLstatementsonthetable,
eachwouldhavetohavebeenincluded,asinGRANTSELECT,INSERT,
UPDATE,DELETEONBACK_ORDERSTOCARUSO.Togrant
SELECTandALTER,bothwouldhavetohavebeennamed,asinGRANT
SELECT,ALTERONBACK_ORDERSTOCARUSO.
6. D.Thestatementsaresyntacticallycorrectandwillperformas
intended.
A,B,andCareincorrect.ThePROJECTStabledoesnotneedtobe
grantedtoMARINOsincetheVIEWhasbeengranted.SincetheVIEWis
updatable,thentheUPDATEprivilegewillworkaswell.
7. A,B,andD.AllthreeformsresultintheUPDATEprivilegebeing
grantedtouserONEILLfortheCBAYtable.
Cisincorrect.ThisstatementisaninvalidSQLstatement.Iteitherneeds
forthekeywordPRIVILEGEStograntallsystemprivilegestoONEILLor
needstonameanobjectforwhichALLprivilegesshouldbegranted.The
questionisspecificallyaskingaboutgrantingprivilegesontheCBAYtable,
sotheALLPRIVILEGESformwouldnotwork.
8. C.ThedatadictionaryviewDBA_TAB_PRIVSallowsausertosee
privilegesthathavebeengrantedtoitselforbyitselftoothers.
A,B,andDareincorrect.
9. B.USER_TAB_PRIVSisthecorrectanswer.
A,C,andDareincorrect.USER_TAB_COLUMNShasnoinformation
aboutgrants.NeitherdoesUSER_TABLES.The
ALL_TAB_PRIVS_RECDviewcontainsdataaboutincominggrantsonly.
10. A,B,andC.Bothsystemandobjectprivileges,aswellasotherroles,can
begrantedtoanygivenrole.
Disincorrect.
11. A.WITHADMINOPTIONiswhatisusedforroles.
B,C,andDareincorrect.WITHGRANTOPTIONworksforobject
privilegesbutnotroles.ThereisnosuchclauseasWITHROLEOPTION.
CASCADEdoesnotapplyhere.
12. C.Theschemanameprefixcorrectlyidentifiesthetable.Inaddition,since
thepublicsynonymTEAPOTreferencesthetable,thenDESCTEAPOT
wouldalsohaveworked—butthatwasnotoneoftheoptionslisted.
A,B,andDareincorrect.Youcannotusetheroleasaprefixorany
othercomponentofthenameofadatabaseobject.
DistinguishBetweenPrivilegesandRoles
13. D.TheCREATEROLEprivilegeisrequiredtocreatearole.
A,B,andCareincorrect.Aroledoesnotreplaceprivilegesbutinstead
isgrantedalongsideofthem.Arolemaybeusedtoreplaceprivilegesasa
managementchoice,andinfactsuchanapproachisadvisable,butitisnot
doneautomatically.Rolesexistinadifferentnamespacefromtablesand
mayduplicatetablenames.Ausermaybegrantedmultiplerolesatany
giventime.
14. C.ThisSQLstatementaccomplishesthegoalinonestatement.
A,B,andDareincorrect.AandBarehelpfulbutdonotcompletely
accomplishthetask.DisincorrectbecauseCiscorrect.
15. B.FromwithintheMICHAELuseraccount,SQLfirstsearchesthelocal
namespaceandthensearchesthedatabasenamespace.Thelocal
namespacecontainstheprivatesynonym,andthatwillbefoundfirst,
beforeSQLlooksinthedatabasenamespace.
A,C,andDareincorrect.TheGRANTstatementissuedbyNEILdoes
notrequireWITHGRANTOPTIONforthesynonymstofunction.
T
A
AbouttheDownload
hise-bookcomeswithTotalTestercustomizablepracticeexamsoftwarewith
140practiceexamquestions.TheTotalTestersoftwarecanbedownloaded
andinstalledonanyWindowsVista/7/8/10computerandmustbeinstalledto
accesstheTotalTesterpracticeexams.
TodownloadtheTotalTester,simplyclickthelinkbelowandfollowthe
directionsforfreeonlineregistration.
http://www.totalsem.com/1259584615d
SystemRequirements
ThesoftwarerequiresWindowsVistaorhigherand30MBofharddiskspacefor
fullinstallation,inadditiontoacurrentorpriormajorreleaseofChrome,
Firefox,InternetExplorer,orSafari.Torun,thescreenresolutionmustbesetto
1024×768orhigher.
InstallingandRunningTotalTester
Onceyou’vedownloadedtheTotalTestersoftware,double-clicktheSetup.exe
icon.Thiswillbegintheinstallationprocessandplaceanicononyourdesktop
andinyourStartmenu.TorunTotalTester,navigatetoStart|(All)Programs|
TotalSeminarsordouble-clicktheicononyourdesktop.
TouninstalltheTotalTestersoftware,gotoStart|ControlPanel|Programs
AndFeatures,andthenselecttheTotalTesterprogram.SelectRemove,and
Windowswillcompletelyuninstallthesoftware.
AboutTotalTester
TotalTesterprovidesyouwithasimulationoftheOracleDatabaseSQLexam
(Exam1Z0-071).ExamscanbetakeninPracticeMode,ExamMode,orCustom
Mode.PracticeModeprovidesanassistancewindowwithhints,referencesto
thebook,explanationsofthecorrectandincorrectanswers,andtheoptionto
checkyouranswerasyoutakethetest.ExamModeprovidesasimulationofthe
actualexam.Thenumberofquestions,thetypesofquestions,andthetime
allowedareintendedtobeanaccuraterepresentationoftheexamenvironment.
CustomModeallowsyoutocreatecustomexamsfromselecteddomainsor
chapters,andyoucanfurthercustomizethenumberofquestionsandtime
allowed.
Totakeatest,launchtheprogramandselectOracleDatabaseSQLfromthe
InstalledQuestionPackslist.YoucanthenselectPracticeMode,ExamMode,or
CustomMode.Allexamsprovideanoverallgradeandagradebrokendownby
domain.
TechnicalSupport
ForquestionsregardingtheTotalTestersoftwaredownloadoroperation,visit
www.totalsem.comore-mailsupport@totalsem.com.
Forquestionsregardingthee-bookcontent,pleasee-mailhep_customer-
service@mheducation.com.ForcustomersoutsidetheUnitedStates,e-mail
international_cs@mheducation.com.
Glossary
1GLFirst-generationlanguage.The1sand0sthatcomputersuseto
communicate.Binarylanguage.
2GLSecond-generationlanguage.Assemblerlanguage.
3GLThird-generationlanguage.Ageneralcategoryofcomputerprogramming
languagesthattendtosupportstructuredorobject-orientedprogrammingina
mannerthatisclosertothespokenwordthan2GLs.Common3GLsareJava,
C++,JavaScript,andPHP.
4GLFourth-generationlanguage.Closertothespokenwordthan3GLs.The
mostwell-knownandwidelyused4GLisSQL.
administratorSeedatabaseadministrator.
aggregateAsinglevaluerepresentinganynumberofothervalues.
aliasAnalternativenameforsomething.Forexample,JoeisanaliasforJoseph.
alphabeticDescribesthelettersofthealphabet.
alphanumericDescribesthelettersofthealphabetandnumbers.
ALTERASQLstatementthatmodifiesthestructure,thename,orsomeother
attributeofanexistingobjectinthedatabase.(Note:Thereareexceptionstothis
definitionthatoccurwhenALTERiscombinedwiththekeywordSESSIONor
STATEMENT.)analyticfunctionsFunctionsthatoperateonagroupofrows
(knownasawindow)andreturnmultiplerowsforeachgroup.Sometimescalled
analyticalfunctions.
ANSIAmericanNationalStandardsInstitute.Anorganizationthatoverseesa
numberofvoluntarycommitteesthatsetstandardsformanyindustries,
includingsoftwaredevelopmentandinformationtechnology.
attributeApropertyorcharacteristic.Examplesmightincludeaname,ZIP
code,orentrydate.Correspondstoacolumninatable.Seealsoentity.
BLOBBinaryLargeObject.Adatatypethatstoresunstructuredbinarydata,up
to128terabytes.BLOBdatatypescanberolledbackorcommittedaspartof
anydatabasetransaction.Suitableforstoringmultimediadata.
BooleanReferstothevaluationofexpressionsaseithertrue,false,orunknown
andusingthelogicaloperatorsAND,OR,andNOT.Namedafterthe
mathematicianGeorgeBoole.
built-inAlreadypresent.SQLbuilt-infunctionsarethosethatcomealready
installedinadatabase,asopposedtouser-definedfunctionsthatyoucancreate
yourselfandaddtothesetofavailablefunctionsinadatabase.
CartesianproductThecombinationofeachrowinonetablewitheveryrowin
anothertable.Theresultoftwoormoretablesjoinedtogetherwithnospecified
joincriteria.Alsoknownasacross-join.
caseinsensitiveWithoutregardforwhetheraletterisinuppercaseorlowercase
form.Forexample,whenperformingacase-insensitivecomparisonoftheletter
Aandthelettera,thetwoareequal.
casesensitiveWithregardforwhetheraletterisinuppercaseorlowercaseform.
Forexample,whenperformingacase-sensitivecomparisonoftheletterAand
thelettera,thetwoarenotequal.
characterThesymbolsofawritingsystem.
characterclassAlsoknownasPOSIXcharacterclasses.Shorthandreferences
inregularexpressionsforspecifyingarangeofcharacters.
charactersetAnencodingsystemforrepresentingcharactersinbytes.
CHECKconstraintAruleonatablethatfiltersincomingdata.Onlydatathat
satisfiesthatrulewillbeacceptedbythetable.AlsoknownasaCHECK
integrityconstraint.
childAroworrecordthatisonelevelbelowanotherlevelinahierarchicaldata
relationship.Forexample,ifonetablecontains“orders”andanothercontainsthe
“lineitems”thateachordercontains,thenatablecontainingthose“lineitems”
wouldbesaidtobethechildtable.Achildtableisonethattypicallyhasa
foreignkeyrelationshipwithaparenttablesothatrowsintheparenttableare
onelevelhigherinthehierarchythantherowsinthechildtable.Seealso
orphan;parent.
clauseAsubsetwithinalargerconstruct,suchasaportionofastatementor
command.
CLOBCharacterLargeObject.Adatatypethatstoreslargeamountsof
characterdata,upto128terabytes.CLOBdatatypescanberolledbackor
committedaspartofanydatabasetransaction.
CoddThelastnameofDr.E.F.Codd,thepersoncreditedwithformingthe
originalideasthatledtothecreationofmodern-dayrelationaldatabase
programming.
columnAverticalspaceinadatabasetable.Columnshaveanameandadata
type.
commandAdirective.
COMMENTASQLstatementtoaddcommentstothedatadictionaryfor
databaseobjectsyouhavecreated.
commitTocausechangeswithinthecurrentsessiontobemadepermanent.
COMMITASQLstatementtosavedatatothedatabase.
conditionAnexpressionthatevaluatestoameaningfulresulttoindicatethe
nextcourseofaction.Conditionsareusedtodeterminewhetherastatementwill
takeaparticularactionornot;thedecisionhingesonwhetherthecondition
evaluatestotrueorfalse.
conditionalAsituationthatdependsontheevaluationofacondition.
connectEstablishausersessionwiththedatabase.
constantSeeliteral.
constraintAruledefininghowdataistobeprocessed.Atablecanhaveoneor
moreconstraintsthatmayrestrictittohavingcertainkindsofdataandrejecting
others.Seealsoreferentialintegrity.
conversionTheactoftransformingsomethingfromoneformtoanother.
ConversionfunctionsinSQLcanchangedatafromonedatatypetoanotherdata
type.
correlatedsubqueryAsubquerythatuses,aspartofitsexecutionlogic,data
fromanouterquery.
CREATEAreservedwordthatstartsoneofmanySQLstatements,usedto
createdatabaseobjectssuchastables,views,indexes,sequences,andsynonyms.
cross-joinSeeCartesianproduct.
datadictionaryAsetoftablesandviewsautomaticallymaintainedbythe
Oraclesystemfordocumentingthecharacteristicsandstatusofallobjectsinthe
database.
datafileAphysicalfileinthefilesystemforstoringdata,locatedeitherinthe
operatingsystemfilesystemorinanAutomatedStorageManagementdisk
group.
datatypeAsetofrulesdefiningasubsetofdata.
databaseAnorganizedcollectionofinformation.
databaseadministratorOftenabbreviatedDBA.Thejobofadministeringthe
database.TheDBAoftenistaskedwithinstallingthedatabasesoftwareand
configuringitforuse,performingbackups,generallymakingthedatabase
systemavailableforuse,maintainingoptimalperformance,andtakingstepsto
protectagainstlossofdata.
dateAcalendardate.
datetimeAnyofthesetofdatatypesDATE,TIMESTAMP,TIMESTAMP
WITHTIMEZONE,orTIMESTAMPWITHLOCALTIMEZONE.
daylightsavingtimeTimedefinedasa1-houroffsetfromstandardtimeto
providemoredaylightattheendoftheworkingdayduringseasonsinwhich
daylightislimited.
DBASeedatabaseadministrator.
DBMSDatabasemanagementsystem.
DDLDataDefinitionLanguage.AsubsetofSQL.ReferstothesetofSQL
statementsthatisusedtocreatedatabaseobjects,modifytheirstructure,and
removethemfromthedatabase.
defaultWhenusedinassociationwithaparameter,“default”isthevalueofthat
parameterwhennospecificvalueisassigned.Seeparameter.
DEFINEAreservedwordusedinpatternmatchingtospecifypatternvariables.
DELETEASQLstatementusedtoremovedatafromthedatabase.
deprecatedSaidofafeaturethatmaystillexistbutisnolongerofficially
supportedandwhoseuseisofficiallydiscouraged.
developerAnindividualengagedinthejobofcreatingapplications.
developmentTheactofcreatingapplications.
DMLDataManipulationLanguage.AsubsetofSQL.ReferstothesetofSQL
statementsusedtoqueryexistingdataindatabaseobjects,adddatatoexisting
databaseobjects,modifythatdata,andremovedatafromthedatabase.
DROPAreservedwordusedtostartoneofmanySQLstatements,allofwhich
areusedtoremovecertainexistingdatabaseobjectsfromthedatabase.
EllisonThelastnameofLarryEllison,founderofOracleCorporation,thefirst
companytoreleaseacommercialRDBMSproduct.
entityAnorganizedcollectionofattributesinadatamodel.Correspondstoa
table.Seealsoattribute;ERD.
equijoinAjointhatusesanequalityoperator(theequalsign)inthejoin
condition.
ERDEntity-relationshipdiagram.Adiagramthatshowsentitiesandhowthey
relatetoeachother.Seealsoentity.
escapecharacterAsinglecharacterthatcantakeonanalternativepurpose
separatefromitscharacter’sstandardmeaning.Forexample,asinglequotation
markisanescapecharacterwhenprecedinganothersinglequotationmarkina
textstringdelimitedbysinglequotessothatstringssuchas‘O’’Brian’willbe
correctlyinterpretedasO’Brianinthedatabase,ratherthanthetruncatedstring
‘O’followedbythecharactersBrian’—whichwouldbemeaninglessinanySQL
statementandwouldresultinasyntaxerror.
explicitcommitTheCOMMITstatement.
expressionAcombinationofliteralvalues,operators,variables,andfunctions,
withtheintentofcomputingavalueofaparticulardatatype.
externaltableASQLtablethatstorestablemetadatainthedatabasebutstores
thetable’sdataoutsideofthedatabase.
FIRSTAreservedwordthatreferstothefirstrowinasequenceofrows.
FLASHBACKASQLstatementusedtorestoreolderversionsofdatabase
objects.
flashbackoperationsAsetofoperationsusingundodatatosupportdata
recoveryandtheanalysisofhistoricaldataovertime.
foreignkeyAreferentialintegrityconstraintinatable.Aforeignkeyspecifies
oneormoreattributesinoneentitythatrelatetooneormoreattributesin
anotherentity.Valuesenteredintheforeignkey’sattributesmustalreadyexistin
thereferencedtable’scorrespondingattributes.Seealsoreferentialintegrity;
constraint.
functionAsetofcodethatperformsaparticulartaskandreturnsasingleresult.
ASQLfunctioncanbeusedwithinaSQLexpression.Afunctionisonetypeof
subprogram,alsoknownasaprogramunit.Thereisanotherformknownasa
procedure,whichisnotincludedontheexam.
GRANTASQLstatementusedtogivesystemprivilegesorobjectprivilegesto
auseraccount.
hierarchicalqueryAquerythatspecifiesmultiplelevelsofrelationship.
Typicallybuiltonaself-join.Notethatatypicaljoinoftwotablesinaparent-
childrelationshipcanbesaidtobeatwo-levelhierarchy;technicallythatwould
beaccurate.ButthetermhierarchicalqueryinOracleSQLisgenerally
understoodtoindicateaparticulartypeofquerybasedonadatamodelthatis
capableofsupportingmorethantwolevels.
IEEEInstituteofElectricalandElectronicsEngineers.Anonprofitorganization
withthemissiontoadvancetechnologyasitrelatestotheuseofelectricity.
implicitcommitAcommiteventotherthantheCOMMITstatement.The
executionofDDLcodewillresultinanimplicitcommit.
indexAdatabaseobjectthatcopiesasubsetofdatafromatable,presorted,and
intendedtosupportfasterqueryingontheindexedtable.
inlineviewAsubquerythatperformslikeaviewinsupportofasingleSQL
statement.
innerjoinAjoinoftwoormoretablesinwhichajoinconditionisspecified,
andtheresultconsistsexclusivelyofrowsinonetablethatmatchrowsinthe
othertableaccordingtothejoincondition.Ifarowinonetablehasnomatching
counterpartintheothertable,itisnotincludedintheresults.Seealsoouterjoin.
INSERTASQLstatementusedtostoredatainadatabasetable.
instanceOnesetofOraclebackgroundprocessesandmemorystructuresusedto
accessadatabase.
integrityconstraintSeeconstraint.
interpolationAmethodforcalculatingoneormorevalueswithinarangeof
knownvalues.
invisiblecolumnAninvisiblecolumninatableisnotvisible,butitsvaluesare
availabletobereferencedbySQLstatements,includingINSERTandSELECT
statements,andincludingVIEWobjectsbasedonthetable.
invisibleindexAnindexthatcanbemadeinvisibletotheOracleDatabase
QueryOptimizertoomittheinclusionofthatindexfromtheexecutionplanofa
givenSQLstatement.
joinTheactofconnectingrowsinonetablewithrowsinoneormoreother
tables,basedonsomecriteriathatdeterminehowthedatainthetablescorrelates
toeachother.
keyOneormoreattributes—orcolumns—usedinthedefinitionofanintegrity
constraint.Keysincludeprimarykeys,foreignkeys,anduniquekeys.
keywordAspecialwordusedinaSQLcommandorservingsomeotherspecial
purpose.Keywordsareoftenreservedwords,buttheyarenotnecessarily
reserved.
LASTAreservedwordthatreferstothelastrowinasequenceofrows.
linearReferstoastraight-linenumericpattern,asopposedtoexponential
patterns.Forexample,linearinterpolationconsidersknownvaluesinarange
andcomputesinterimvalues,assumingalinearrelationshipamongallvalues.
literalAfixeddatavalue.Alsocalledaconstant.
LOBLargeObject.Anyofanumberofdatatypesthatstorelargeamountsof
information.SeealsoBLOB;CLOB;NCLOB.
lowercaseThelettersofthealphabetinminisculeform,inotherwords,a,b,and
soon.
MERGEASQLstatementthatperformsacombinationofINSERT,UPDATE,
and/orDELETEstatementfunctionality.
metacharacteroperatorsUsedtodefinepatternsinregularexpressions.
metadataDataaboutdata.Forexample,isthe“accountnumber”atagiven
organizationanumericvalue,orisitanalphanumericvalue?Orperhaps
alphabetic?Metadatadescribesdatainhigh-levelterms.
multitableinsertASQLINSERTstatementthatisabletoaddrowsofdatato
oneormoretables.Multitableinsertscanbeconditionalorunconditional.
namespaceAvirtuallocationwithinthedatabaseinwhichnodatabaseobjects
maysharethesamename.Allnamesmustbeuniquewithinagivennamespace.
naturaljoinAjoininwhichthejoincriteriaareimpliedbasedoncommon
namesofcolumnsinthetablesbeingjoined.
NCLOBNationalCharacterSetLargeObject.Adatatypethatstoreslarge
amountsofcharacterdatainanationaldatabasecharacterset.Storesupto128
terabytes.NCLOBdatatypescanberolledbackorcommitted.
NEXTAreservedwordthatreferstothenextrowinasequenceofrows.
NLSNationalLanguageSupport.
NLSparametersVariablesthatcustomizethebehaviorofthedatabasein
accordancewithagivenlocale.NLS_SORTisanexample.
non-equijoinAjoinconditionthatusesoperatorsotherthantheequality
operatortospecifythejoincondition—suchasgreater-thanorless-than
operators.
normalizationAspecificseriesofprocessesintendedtosupportthedesignofa
databasetomaximizeefficiency.
NoSQLRefersto“notonlySQL”databases.
NULLUnknown.Theabsenceofinformation.
numberAdigit.
numericSaidofasetofdatatypesthatacceptnumberdata.
objectAniteminthedatabase.Objectshavepropertiesofstructureandsecurity.
objectprivilegeTherighttoperformaparticulartaskonaparticularobjectin
thedatabase.Seealsosystemprivilege.
OFFSETAreservedwordusedwithFETCHtolimitrowsreturnedbyaquery,
startingafterthenumberofrowsspecifiedbyOFFSET.
ONEROWPERMATCHReservedwordsusedwhenperforminganalytics
acrossmultiplerowsofdata.
operatorprecedenceTherulesdefiningtheorderinwhichoperatorswithinan
expressionareprocessed.
operatorsSymbolsthatperformtasksonvalueswithinanexpression.
optimizerAfeaturebuiltintotheOracledatabasethatevaluatesprocessing
withinthedatabasetoimprovespeedandoptimizerperformanceofSQL
statements.
ORA_ROWSCNAconservativeupperboundofthelatestcommittimeforthe
transactionthatlastchangedtherow.TheactualcommitSCNofthetransaction
canbesomewhatearlier.Seealsosystemchangenumber(SCN).
OracleTheleadingRDBMSproductonthemarkettoday.
OracleCorporationThefirstcompanytoproduceacommercialRDBMS
product.
orphanAchildrowinachildtableforwhichthereisnocorrespondingparent
rowinthecorrespondingparenttable.
outerjoinAjoinoftwoormoretablesinwhichajoinconditionisspecified,
andtheresultconsistsofrowsinonetablethatmatchrowsintheothertable
accordingtothejoincondition,aswellasrowsthatdonotmatch.Ifarowinone
tablehasnomatchingcounterpartintheothertable,itmaybeincludedinthe
results.Seealsoinnerjoin.
parameterAvariablethatispassedtoorfromafunctionorprocedure.
parentAroworrecordthatisonelevelaboveanotherlevelinahierarchical
datarelationship.Forexample,ifonetablecontains“orders”andanother
containsthe“lineitems”thateachordercontains,thenatablecontainingthose
“orders”wouldbesaidtobetheparenttable.Aparenttableisonethatis
referencedbyaforeignkeyinachildtablesothatrowsintheparenttableare
onelevelhigherinthehierarchythantherowsinthechildtable.Seealso
orphan;child.
parseToanalyzecodeforsyntacticaccuracy.SQLcodethatissubmittedfor
executionisparsedfirstandthenexecuteduponsuccessfulcompletionofthe
parsingprocess.
PARTITIONBYReservedwordsusedtospecifyasubsetofrowswithina
largerquery.
patternvariablesApatternvariableisanameyoucreateandassociatewitha
conditionyouspecify.Patternvariablesareusedtosearchformatchesby
comparingdataacrossmultiplerowsofdatawithcomparisonoperators.
POSIXPortableOperatingSystemInterface(forUnix).AsetofIEEEstandards
fordefiningstandardsandinteroperabilityonanumberofissues.
precedenceAlogicalprioritizationofasetofitems.
precisionPartofthedefinitionofanumericdatatype.Precisionspecifiesthe
numberofsignificantdigitsinthenumericvalue.Seealsoscale.
predicatesThesecompareoneexpressiontoanothertoproduceatrue,false,or
NULLresult.CanbecombinedwithBooleanoperatorsAND,OR,andNOT.
PREVAreservedwordthatreferstothepreviousrowinasequenceofrows.
primarykeyAuniquenon-NULLattributeinanentity,orauniquenon-NULL
columninatable.
privatesynonymAsynonymthatisnotaPUBLICsynonym.Thereisno
PRIVATEkeyword.
privilegeTherighttoperformataskinthedatabase.Seealsoobjectprivilege;
systemprivilege.
procedureAsetofcodethatperformsaparticulartask.Aproceduremayreturn
anywherefromzerotomultipleresults.ProcedurescannotbeusedwithinaSQL
expressionbutinsteadareofteninvokedinstatementsbythemselves.
productionProfessionaluse.Databaseapplicationsin“production”areactively
storingdataforanongoingorganization,asopposedtodatabaseapplications
thatareindevelopmentortesting.
projectionTheconceptofqueryingasubsetofcolumnsfromatable.
pseudocolumnsValuesthataredefinedautomaticallybytheOraclesystemfor
certainobjectsinthedatabase,suchastablesandsequences.Pseudocolumnscan
beselectedlikeacolumninatable.
PUBLICAspecialdatabaseuserautomaticallymaintainedbythedatabase.
PUBLICrepresentsallusersinthedatabase.GrantingprivilegestoPUBLIChas
theeffectofgrantingthemtoallusers.
PURGEASQLstatementtoremoveobjectsfromtherecyclebin.
queryASELECTstatement.Arequestofthedatabaseforsomeofthedata
containedwithinit.
RDBMSRelationaldatabasemanagementsystem.
readconsistencyTheabilityfordatainthedatabasetobereadandjoinedina
mannerthatisaccurate.Readconsistencyrepresentsaviewofdatathatis
“frozen”inaninstantoftime.Readconsistencybecomesimportantwhen
joiningtablesthatarebeingmodifiedinrealtimesothatasthedatabasequeries
onetableandthenanother,thecombinedrecordsreflectwhatwasintended.
recordAsetofdataelementsrelatedtoeachotherandrepresentinga
meaningfulcollectionofinformation.Onerowcanbearecord;joinedrows
mightalsobearecord.
recyclebinThestructureintheSQLdatabaseintowhichdroppedobjectsare
tracked.
redologsAsetofoperatingsystemfilesthatrecordallchangesmadetoa
database,whetherthosechangeshavebeencommittedornot.
referentialintegrityAconstraint,orrule,ononetable’scolumnthatrequires
anyvaluetobestoredinthatcolumntobealreadypresentinanotherparticular
table’scolumn.Seealsoforeignkey.
regularexpressionAlanguageofpatternmatching.Nottobeconfusedwith
expressions.Oracle’ssupportforregularexpressionsisconsistentwiththe
POSIXandUnicodestandards.
relationalHavingarelationorbeingrelated.Adatabaseissaidtoberelational
whenitisbuiltondataobjectsthatcanbejoinedtogetherbasedoncommon
criteriawithinandamongtheobjects.
RENAMEASQLstatementusedtochangethenameofcertainobjectsinthe
database.
reservedwordSpecialwordssetasideforspecialuseandnotavailablefor
applicationdevelopment.Youcannotusereservedwordsasthenamesof
databaseobjectsorvariables.
restorepointAmarkedpointintime,toberecordedforpossiblefuture
referenceinsupportofflashbackoperations.
REVOKEASQLstatementtoremovesystemprivilegesorobjectprivileges
thathavebeengrantedtoauseraccount.
roleAcollectionofoneormoreprivileges.
rollbackAnactionthatrestoresthedatabasetothemostrecentcommitwithin
thecurrentsession.
ROLLBACKASQLstatementusedtorestorethedatabasetoanearlierstate.
Cancelstheeffectsofatransactioninprogress.
rowOnesetofvaluesforthecolumnsofatable.
savepointAmarkedpointintime,toberecordedforpossiblefuturerollback.
SAVEPOINTASQLstatementthatmarksapointinasession.Futureusesof
theROLLBACKstatementmaychoosetorestorethedatabasetothepoint
markedbyaSAVEPOINTstatement.
scalarsubqueryAsubquerythatreturnsonecolumninonerowasitsoutput—
inotherwords,asinglevalue,asopposedtorowsofvaluesorcolumnsof
values.
scalePartofthedefinitionofanumericdatatype.Scalespecifieswhere
roundingwilloccurinthenumericdatatype.Seealsoprecision.
schemaAcollectionoftablesownedbyauseraccount.
SCNSeesystemchangenumber(SCN).
segmentAleveloflogicaldatabasestorage.
SELECTASQLstatementusedtoqueryoneormoredatabasetables.
selectionTheabilitytoqueryasubsetofrowsfromatable.
selectivityThedegreeofuniquenessofvaluesinacolumn.Ifallvaluesinthe
columnareidentical,selectivityissaidtobelow.Ifthevaluesareallunique,
selectivityissaidtobehigh.
self-joinAjointhatconnectsrowsinatablewithotherrowsinthesametable.
semijoinAquerythatreturnsrowsthatmatchanEXISTSsubquery.
sequenceAnumbergenerator.Adatabaseobject.
sessionAuserprocessinwhichtheuserinteractswiththedatabase.
setoperatorAnyoftheoperatorsUNION,UNIONALL,INTERSECT,or
MINUS.
SKIPAreservedwordusedinpatternmatching.Maybecombinedwithother
keywordstoformkeywordphrases,forexample,AFTERMATCHSKIPTO
NEXTROW.
SQLSeeStructuredQueryLanguage.
standarddeviationWhenusedwithnumericanalysis,standarddeviationisa
quantifieddegreeofvariationofindividualvalueswithinalargesetofvalues.
Theformulaforstandarddeviationtakesthesquarerootofthevariance.See
varianceformoreinformation.
standardtimeAlsoknownaswintertimezones.TimeasdefinedbyUTC.
statementAcommand.
stringAseriesofcharacters.
StructuredQueryLanguageAworldwidestandardlanguageforinteracting
withadatabase.
subqueryASELECTstatementcontainedwithinanother(outer)SELECT
statementsothatthedataofthesubqueryfeedsintotheprocessingoftheouter
query.
superaggregateAnaggregationofaggregatevalues.
synonymAnalias,oralternativename,forsomethinginthedatabase.A
synonymisitselfanobjectinthedatabase.
syntaxTherulesforformingastatement,acommand,orsomeotherlanguage
construct.
SYSAbuilt-inuseraccountwithDBAprivilegesthatcomeswithallOracle
installations.SYSownsthedatadictionary.
SYSTEMAbuilt-inuseraccountwithDBAprivilegesthatcomeswithall
Oracleinstallations.
systemchangenumber(SCN)Amarkerthatspecifiesacommittedversionof
thedatabaseataparticularpointintime.Eachcommittedtransactionisassigned
anSCN.Seealsotransaction.
systemprivilegeTherighttoperformaparticulartaskinthedatabase.Seealso
objectprivilege.
tableAstorageunitinthedatabasethatconsistsofcolumnsandrows.
tablespaceAmechanisminthedatabasethatishometooneormoretablesand
storesthatdatainoneormoredatafiles.
TCLTransactionControlLanguage.AsubsetofSQL.ReferstothesetofSQL
statementsthatisusedtocontrolauser’ssessioninwhichDMLstatementsare
used.TCLdetermineswhethertheresultsofaDMLstatementareallowedtobe
madepermanentorwhethertheyareundonefromthedatabase.
textCharacter-baseddata.
timezoneAregionoftheearththatusesuniformstandardtimeasanoffsetfrom
UTC.Therearecurrently24suchregionsdefinedintheearth,dividedroughly
bylongitudinallines.Alsoknownastimezoneregion.
timezonenameThenameofatimezoneregion.Examplesare
Pacific/AucklandandAmerica/Indianapolis.
timezoneoffsetAtimedifferencebetweenthelocaltimeandUTC.
timestampAvaluerepresentingthedateandtime.
transactionAseriesofoneormoreSQLstatementsexecutedbetweencommit
events.
TRUNCATEASQLstatementusedtoremovedatafromadatabasequicklybut
withoutrecoverability.
unconditionalWithoutrestriction.
undosegmentsSegmentsthataremaintainedautomaticallybythedatabaseto
supportrollbackoperations,toassurereadconsistency,andtootherwiserecover
fromlogicalcorruptions.
UnicodeAnindustrystandardthatattemptstocreateastandardizedencodingof
everycharacterofeverylanguageinexistence.
uniqueOneofakind.
uniqueidentifierAnunambiguousreferencetosomething,leavingnodoubt
whatisbeingreferenced.
UPDATEASQLstatementusedtomodifydatainadatabasetable.
uppercaseThelettersofthealphabetinmajusculeform,alsoknownascapital
letters,suchasA,B,andsoon.
useraccountAprocessthatprovidespassword-protectedaccesstoand
ownershipofasetofdatabaseobjectsandprivileges.
UTCCoordinatedUniversalTime.ThenewnameforGreenwichMeanTime.
Theuniversalstandardformeasuringtimeinternationally.UTCmeasurestime
asitexistsattheRoyalObservatoryofGreenwich,London.
variableAsmallunitofstorage,representedbyanameandadatatype,for
holdingvaluesthatcanbechanged.
varianceWhenusedwithnumericanalysis,variationquantifiesthedegreeof
variationofindividualvalueswithinalargesetofvalues.Varianceisdetermined
byaveragingasetofvalues,subtractingeachvaluefromtheaverage,squaring
eachdifference,andsummingtheresult.
viewAnamedquerythatisstoredinthedatabase.
windowWhenusedwithanalyticfunctions,awindowisagroupofrows
surroundingatargetrow.Analyticsmayperformoperationsonthetargetrowby
leveragingdatafromthroughoutthewindow.
wintertimezoneSeestandardtime.
INDEX
Pleasenotethatindexlinkspointtopagebeginningsfromtheprintedition.
Locationsareapproximateine-readers,andyoumayneedtopagedownoneor
moretimesafterclickingalinktogettotheindexedmaterial.
NUMBERS
1GL(first-generationlanguage),569
1NF(firstnormalform),23–25
2GL(second-generationlanguage),569
2NF(secondnormalform),23–25
3GL(third-generationlanguage),569
3NF(thirdnormalform),23–25
4GL(fourth-generationlanguage),569
A
ACCEPTcommand,substitutionvariables,178–180
accesscontrol.Seeuseraccesscontrol
ACCESSPARAMETERS,createexternaltable,89–90
ADD_MONTHSdatefunction,221
ADMINOPTIONclause,GRANTstatement,539–540
administrator.SeeDBA(databaseadministrator)
aggregate,defined,569
aggregatefunctions.Seealsogroupfunctions
commonlyused,281
defined,223
DENSE_RANK,292
FIRSTandLAST,292–293
GROUPBYrulesfor,296–298
manygroupfunctionsusedas,280
nestingrulesfor,300–303
RANK,290
aliases,569
ALLkeyword
conditionalmultitableINSERT,500–501
grantcertainprivilegestoallusers,541
unconditionalmultitableINSERT,499,501
ALLoperator
AVGfunction,288
comparison,multi-rowsubquery,371
COUNTfunction,285
ALL_prefix,datadictionaryviews,476–477,548
ALLPRIVILEGESoption,541,546–547
alphabetic,570
alphanumeric
inampersandsubstitution,175
characterdatatypesas,57
metadataas,570
ALTERSESSIONstatement,28,60,426
ALTERstatement
asDDLstatement,28
defined,570
implicitcommitwhenexecuting,124
ALTERSYSTEMstatement,28,60
ALTERTABLEstatement
createconstraints,66–67
createforeignkeys,75
FLASHBACKTABLElimitations,430–431
ALTERUSERstatement,534
ALTERVIEWstatement,402–403
AmericanNationalStandardsInstitute(ANSI),7,570
ampersandsubstitution
ACCEPTandPROMPTcommands,178–180
DEFINEcommand,177,180–182
restrict/sortoutputatruntimewith,173–177
reviewdrill,190–191
reviewself-testQ&A,195–196,199–200
SETandSHOWcommands,177–178
asSQL*Pluscapabilityonexam,148
UNDEFINE,177
VERIFYsystemvariable,178
analyticfunctions.Seealsoaggregatefunctions
defined,570
DENSE_RANK,291
FIRSTandLAST,292–293
groupfunctionsusedas,280
LAGandLEAD,226–230
OVER,PARTITIONBY,andORDERBY,224–226
overviewof,223
PERCENTILE_CONT,232–233
RANK,289–290
STDDEV,230–232
ANDoperator,Boolean
HAVINGclausewith,304–305
operatorprecedence,168–169
overviewof,164–167
ANSI(AmericanNationalStandardsInstitute),7,570
ANYcomparisonoperator,multi-rowsubquery,371
ANYkeyword,systemprivileges,538–539
ASkeyword,createviews,395
ASCreservedword,ascendingsortinORDERBY,151–152
asterisk,COUNTfunction,284–285
attributes
*reservedfornaming,50
buildingrelationaldatabase,20–21
createsimpletable,46–47
indatabasenormalization,23–24,32
defined,570
entity-relationshipdiagramwith,18–19
autonomous,subqueriesas,352
AVGfunction,287–288,295
B
batchscripts,180
BEFOREDROP,recoverdroppedtables,426
BETWEENreservedword,WHEREclause,170–171
BLOB(binarylargeobject)datatypes
constraintrestrictions,80
defined,570
overviewof,62
Boolean
defined,570
HAVINGclause,304–305
limitrowsretrievedbyquery,164–169
NOToperator,166–168
operatorprecedence,168–169
AND/ORoperators,164–166
built-in
datatypes,61
defined,570
functions,203
C
callingfunctions,SQLstatement,203
Cartesianproduct,8,570
CASCADEclause,107–109,534
CASCADECONSTRAINTS,droppedcolumns,82–84
CASEconditionalexpression,265
caseinsensitive
defined,570
table/objectnamesas,48
casesensitive
characterdatatypecomparisonsas,161
datadictionarynames,422
defined,571
objectnamesindatadictionaryas,422
passwordsas,534
quotednamesas,50
textsearchesas,162,206–207
case,strings
INITCAPmanaging,207–209
UPPERandLOWERmanaging,206–207
CASTconversionfunction,263–264
CEILnumericalfunction,215
CHARdatatype,57
characterclass(POSIXcharacterclass),571
characterdatatypes
listof,57
MINandMAXgroupfunctionsfor,286–287
ORDERBYandNULL,157
characterfunctions
CONCATand||,208–209
INITCAP,207–208
INSTR,212
LENGTH,211–212
LPAD,RPAD,209–210
LTRIMandRTRIM,210–211
overviewof,206
SOUNDEX,213–214
SUSTR,212–213
tasksperformedby,204
TRIM,211
UPPERandLOWER,206–207
characterset,defined,571
characters
defined,571
LIKEoperatorenablingwildcard,160,162–164
rulesfortable/objectnames,48
CHECKconstraint
createdattimeoftablecreation,77–78
datatyperestrictionson,79–80
defined,571
child,defined,571
childtables,recursivelytruncate,107–109
CHUNKparameter,BLOBdatatype,62
clause,defined,571
CLOB(characterlargeobject)datatype,62,80,571
Codd,Dr.E.F.,571
columnalias,154–155
columns
createmultipleindexesonsamesetof,423–424
CREATETABLEwith,53–54
datatypesavailablefor.Seedatatypes,columndefined,571
designatetableindexes,413
dropped,80–84
inDUALtable,206
groupingmultiple,298–299
insertrowsviadefaultcolumnlist,110–113
insertrowsviaenumeratedcolumnlist,113–116
inspectconstraintsindatadictionary,487–488
inspectindatadictionary,484–485,488
multiple-columnsubqueries,356
settoUNUSED,84–86
storageoftable,390
structureof,391
inUSER_TABLESview,476
visible/invisible,403–407
command,defined,571
COMMENTS
addtodatadictionary,480–482
defined,571
asDMLstatement,29
readindatadictionary,479–480
commit,defined,572
COMMITstatement
controltransactions,122
defined,30,572
explicitcommit,123–124
implicitcommit,124–125
andmultiplesessions,125–127
rulesforusingSAVEPOINT,129–131
comparisonoperators
Booleanlogic,164–169
ISNULLandISNOTNULL,171–172
LIKE,162–164
multi-rowsubqueries,370–372
single-rowsubqueries,369
WHEREclause,158–160
COMPILEstatement,402–403
compileviews,datadictionary,485–486
compositeindexes,418–420
compositeUNIQUEconstraint,71
CONCATand||characterfunction,208–209
concatenationoperators,209–210
condition,defined,572
conditional,defined,572
conditionalexpressions,SELECT
CASE,265
DECODE,266–267
defined,246
NULLIF,268–269
NVL,267–268
overviewof,264
review,269–271,273–275,277–278
conditionalmultitableINSERTstatements,499,500–502,505–513
connect,defined,572
CONNECTrole,551
CONNECTstatement,SQL*Plus,534–535
constant.Seeliterals
constraints
cannotbeaddedtoexternaltables,87
CHECK,77–78
createinALTERTABLE,66–67
createinCREATETABLE,53–54,63–66
create,modify,ordropwithALTERVIEW,402–403
indatadictionaryviews,487–488
datatyperestrictionson,79–80
defined,44,572
ONDELETEclause,76–77
FOREIGNKEY,73–77
fulllistof,78–79
implicitindexcreation,414–415
INSERTstatementand,115–116
multipleconstraints,78
naming,50
NOTNULL,67,69–71
preventsINSERT/UPDATE/DELETEonviews,398–399
PRIMARYKEY,71–73
recoverwithFLASHBACKTABLE,425–429
asschemaobjects,390–391
system-assignednames,51
UNIQUE,71
UPDATEstatementand,119–120
viewsand,397
CONSTRAINT_TYPEcolumn,datadictionaryviews,487–488
controltransactions
COMMIT,123–127
overviewof,122–123
ROLLBACK,127–129,132–133
SAVEPOINT,129–132
conversionfunctions
CAST,263–264
TO_CHAR,253–259
TO_DATE,259–260
defined,246
TO_DSINTERVAL,262
explicitandimplicit,247–249
marktimetorestoredata,433–434
TO_NUMBER,250–253
NUMTODSINTERVAL,263
NUMTOYMINTERVAL,262
overviewof,246–247
reviewcertificationsummary,269–270
reviewdrill,271
reviewself-testQ&A,272–278
TO_TIMESTAMP,260
TO_TIMESTAMP_TZ,261
TO_YMINTERVAL,261
CoordinatedUniversalTime(UTC),583,585
correlatedsubquery
defined,352,572
deleterowsinDELETE,362–363
Oracle1Z0-071vs.1X0-051examson,8
overviewof,356–357
querydatainSELECT,UPDATE,andDELETE,357–359
updaterowsinUPDATE,360–362
useof,355
COUNTfunction,283–285
CREATEANYTABLEprivilege,541
CREATEINDEXstatement
compositeindex,418
singlecolumnindex,416
specifyvisibilityofindex,422
CREATE,reservedword,572
CREATERESTOREPOINTstatement,434
CREATESEQUENCEstatement,408–409
CREATEstatement
asDDLstatement,28
asDMLstatement,29
implicitcommitsand,124
CREATETABLEstatement
createcompositePRIMARYKEYconstraint,73
createexternaltable,89–90
createforeignkeyswithALTERTABLEvs.,75–76
createin-lineconstraints,64–65
createout-of-lineconstraints,65–66
createPRIMARYKEYconstraint,72
createsimpletable,46–48
grantprivilegesonuserandtables,542–552
nametableorotherobject,48–53
overviewof,53–54
system-assignednames,51
usesubqueries,352–353,355
CREATEUSERstatement,533–534
CREATEUSERsystemprivilege,533–534
CREATEVIEWstatement,352–353,395–397
cross-join.SeeCartesianproduct
CURVALpseudocolumn,sequencegenerators,410–412
CYCLE,sequenceoption,409
D
DAB_SYS_PRIVSview,datadictionary,486
data
DMLstatementsworkswithobject,29–30
retrievefromtablewithSELECT,30–32
DataDefinitionLanguage(DDL).SeeDDL(DataDefinitionLanguage)
statementsdatadictionaryviews
addcommentsto,480–481
compileviews,485–486
defined,572
DICTIONARYview,481–482
dynamicperformanceviews,477–479
findcolumns,488
identifyuser’sownedobjects,482–484
inspectconstraints,487–488
inspecttablesandcolumns,484–485
manageobjectswith,473
Oracleexamson,8,11
queryvarious,474–475
readcomments,479–480
reviewcertificationsummary,489
reviewdrill,490–491
reviewself-testQ&A,492–496
forroles,551–552
storesinformationabouttables,390
structureof,475–477
viewprivilegesin,486–487,547–549
datafiles,573,584
data,manipulating
controltransactions,122–133
deleterowsfromtable,121–122
insertrowsintotable,109–116
reviewcertificationsummary,133–134
reviewdrill,135–137
reviewself-testQ&A,138–145
truncatedata,106–109
updaterowsintable,117–121
DataManipulationLanguage.SeeDML(DataManipulationLanguage)
statementsdatamodeling.SeeERD(entity-relationshipdiagram)
data,restrictingandsorting
ampersandsubstitution.Seeampersandsubstitutionlimitrows.See
rowsretrievedbyquery,limitoverviewof,148
reviewcertificationsummary,186–188
reviewdrill,189–191
reviewself-testQ&A,192–200
sortrowsretrievedbyquery.Seerowsretrievedbyquery,sortuseSQL
rowlimitingclause,182–186
datasets.Seelargedatasets
datatypes
comparing,160–162
conversionfunctionsfor.Seeconversionfunctionsdefined,573
explicitvs.implicitconversionof,247–249
noSQLBoolean,168
usingSELECTwithsetoperators,451–452
datatypes,column
built-invs.user-defined,63
character,57
date,59–61
insertrows/implicitconversionof,114–115
largeobject(LOB),61–62
numeric,58–59
overviewof,56
restrictionsonconstraints,79–80
database
defined,573
normalization,23–25
relationshipbetweenSQLand,25–27
date
defined,573
andNUMBERconstants,223
datedatatypes
formatmodels,254–260
functions.Seedatefunctions
listof,59–61
MEDIANgroupfunctionfor,288–289
MINandMAXgroupfunctionsfor,286–287
ORDERBYandNULLwith,157
datefunctions
ADD_MONTHS,221
DATEandNUMBERconstants,223
LAST_DAY,220
MONTHS_BETWEEN,221–222
NEXT_DAY,220
NUMTODSINTERVAL,222
NUMTOYMINTERVAL,222
ROUND—Date,218–219
SYSDATE,217
tasksperformedby,204–205
TRUNC—Date,219–220
datetime,573.Seealsodatedatatypesdatetimeconversionfunctions
TO_DSINTERVAL,262
NUMTOYMINTERVAL,262
TO_TIMESTAMP,260
TO_TIMESTAMP_TZ,261
TO_YMINTERVAL,261
daylightsavingtime
defined,573
TIMEZONE_HOURfieldforchangesin,59
TZDtimezonewith,256
DBA(databaseadministrator)
controlovertablespaces,535
defined,573
exclusiveaccesstoSYSaccount,475
GRANTALLPRIVILEGESoption,540
GRANTWITHADMINOPTION,539–540
role,551
tryingcodesamplesinthisbookand,530
DBA_prefix,datadictionaryviews,476–477
DBA_RECYCLEBIN,DROPTABLE,426
DBA_ROLE_PRIVS,datadictionaryview,487,552
DBA_ROLES,datadictionaryview,552
DBA_SYS_PRIVS,datadictionaryview,487,548–549,552
DBA_TABLES,datadictionaryview,476
DBA_TAB_PRIVS,datadictionaryview,487,548–549,552
DBMS(databasemanagementsystem),defined,573
DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBERfunction,SCN,
431,434
DDL(DataDefinitionLanguage)statements
automaticallyupdatesdatadictionary,475
defined,573
implicitcommitswhenexecuting,124
impliedcommitscausedby,30
managetables.Seetables,create/manageoverviewof,28–29
DECODEconditionalexpression,266–267
defaultcolumnlist,110–113
default,defined,573
DEFINE,reservedword,177,180–182,573
DELETEstatement
acceptssubqueries,352
COMMIT,multiplesessionsand,125–127
defined,573
deleterowsfromtable,121–122
deleterowswithcorrelatedsubquery,362–363
asDMLstatement,29
executeonviews,396–400
indexmaintainedwithevery.Seeindexesquerydataviacorrelated
subqueriesin,355,357–359
removerows,106
TRUNCATETABLEvs.,106–107
DELETE_RULEcolumn,datadictionaryview,487–488
DENSE_RANKfunction,291–292
dependentobjects,andtablerecovery,428
dependentprivileges,547
deprecated,defined,573
DESCstatement,SQL*Plus,7,54–56,152
DESCRIBEstatement
describeDICTIONARYview,481
describeviewwith,391,394
reviewtablestructurewith,54–56
descriptivenames,databaseobjects,51
developer,defined,573
development,defined,574
DIRECTORYobjects,87–90
DISABLENOVALIDATEstate,constraints,402
DISTINCToperator
withAVGgroupfunction,288
avoidLOBsusedwith,59
withCOUNTgroupfunction,285
preventsINSERT/UPDATE/DELETEonviews,399
DML(DataManipulationLanguage)statements
acceptssubqueries.Seesubqueries
defined,574
SQLstatementsforming,122
workswithexistingdatabaseobjects,29–30
workswithTCLstatements,30
documentation
additional,16
usingthisbookforexam,16
doublequotations
columnaliasoptions,155
quotednames,50–51
DROPCOLUMNstatement,80–85
DROPINDEXstatement,420–421
DROPRESTOREPOINTstatement,434
DROPstatement
defined,28,574
implicitcommitswith,124
restoredroppedtableBEFOREDROP,547
DROPTABLEstatement,426
DROPUNUSEDCOLUMNSstatement,86
DROPUSERstatement,534
DUALtable,206
DUMMYcolumn,DUALtable,206
dynamicperformancesynonyms
V$DATABASE,479
V$INSTANCE,479
V$OBJECT_USAGE,479
V$PARAMETER,479
V$RESERVED_WORDS,479
V$SESSION,479
V$TIMEZONE_NAMES,479
dynamicperformanceviews,477–479
E
elements,numericformatmodel,250–253
Ellison,Larry,574
ELSEclause,conditionalmultitableINSERT,499–501,506–508
ENDkeyword,CASEconditionalexpression,265
entity,574.Seealsoattributes;ERD(entity-relationshipdiagram)entity-
relationshipdiagram.SeeERD(entity-relationshipdiagram)enumeratedcolumn
list,113–116
equalssign,identifyrowswithWHEREclause,158–159
equijoins
defined,574
innerjoins,322–325
multitablejoins,330–331
naturaljoins,327–329
outerjoins,335–339
vs.non-equijoins,321
ERD(entity-relationshipdiagram)
anddatamodeling,17–20
databasenormalization,23–25
defined,574
many-to-manyrelationships,22–23
overviewof,16
relationaldatabasesand,20–21
escapecharacter,singlequote,207–208,252,570
examoverview
OracleSQLvs.ANSISQL,7
OracleSQLvs.OracleSQL*Plus,7
passingscore,11–12
SQLFundamentalsIvs.SQLCertifiedAssociate,7–12
studymaterials,13–16
subjectareas,12–13
testlogistics,4–7
EXISTSoperator,subqueries,363
EXPLAINPLAN,indexdesign,418
explicitcommit
defined,574
overviewof,123–127
rulesforSAVEPOINT,131
explicitconversion,247–249
expressions
attachtoconstraints,77–78
conditional.Seeconditionalexpressions,SELECT
conditionalmultitableINSERT,500
defined,574
dynamic,353
evaluatemultiple,164–169
GROUPBYclauserulesfor,296–297
INSERTstatementand,109
numberfunctionsin,204
ORDERBYclausefor,153–154,300
placecolumnaliasesafter,154
subqueriesasalternativeto,355
UPDATEstatementand,118–119
useSELECTwithsetoperators,451
WHEREclauseand,158–160
externaltables
create,89–90
defined,574
DIRECTORYobjects,87–88
Oracleutilitiesfor,88
restrictionson,86
workingwith,91
F
failedexecutionattempt,368
FETCHclause,SQLrowlimitingclause,182–186
fields,datedatatype,59–61
FIRSTfunction,292–293
first-generationlanguage(1GL),569
FIRSTkeyword
conditionalmultitableINSERT,500–501
defined,574
FETCH,182
firstnormalform(1NF),23–25
flashbackoperations
defined,575
dependentobjects,428
markingtime,431–434
overviewof,424–425
recoverdatainexistingtables,428–431
recoverdroppedtables,425–426
recyclebin,427
reviewcertificationsummary,436
reviewdrill,439
reviewself-testQ&A,444–445,448
statementexecution,428–429
FLASHBACKstatement
asDDLstatement,28
defined,575
FLASHBACKTABLEstatement
executionof,428
limitations,430–431
recoverdatainexistingtables,429–431
recoverdroppedtables,425–429
restoredataviaTIMESTAMP,432
restoredroppedtable/grantedprivileges,547
FLOORnumericalfunction,215
foreignkey
defined,575
jointabletoitselfusingself-joins,334
notrequiredtojointables,332
FOREIGNKEYconstraint,73–77,79–80
formatmodels
datedatatypes,254–260
numeric,250–253
fourth-generationlanguage(4GL),569
FROMclause
definedynamicviewswithsubqueries,353
GRANTstatementwith,538
inlineviewsreplacing,400–402
innerjoins,323
jointabletoitselfwithself-joins,334
multitablejoins,330–331
preventsINSERT/UPDATE/DELETEonviews,399
WHEREclausealwaysfollows,158–159
FULLOUTERJOIN,338–339
functions
analytical.Seeanalyticfunctions
applyconditionalexpressions,264–269
built-invs.user-defined,203
conversion.Seeconversionfunctions
defined,575
group.Seegroupfunctions
single-rowfunctions.Seesingle-row(scalar)functions
G
GRANTstatement
WITHADMINOPTION,539–540
ALLPRIVILEGES,540–541,546–547
asDDLstatement,28
defined,575
WITHGRANTOPTION,545–546
implicitcommitswhenexecuting,124
privilegesontablesanduser,542–552
privilegesvs.roles,552–553
PUBLICwith,541
roles,550–552
syntaxforsystemprivileges,536–538
GRANTEEcolumn,datadictionaryviews,549
GROUPBYclause
avoidusingLOBswith,59–61
groupdatawith,293–298
include/excludegroupedrows,303–304
multiplecolumns,298–299
nestingfunctions,300–303
ORDERBYclauseand,299–300
preventsINSERT/UPDATE/DELETEonviews,398
groupfunctions
asaggregateandanalyticfunctions,280
AVG,287–288
COUNT,283–285
DENSE_RANK,291–292
FIRST,LAST,292–293
groupdata.SeeGROUPBYclause
HAVINGclause,303–305
MEDIAN,288–289
MIN,MAX,286–287
others,292–293
RANK,289–290
reviewcertificationsummary,305–306
reviewdrill,307–308
reviewself-testQ&A,307–308
SUM,285–286
useof,280–283
GV_$prefix,dynamicperformanceviews,477–479
GV_$prefix,globaldynamicperformanceviews,477
GV$prefix,globaldynamicperformanceviews,477
H
HAVINGclause,include/excludegroupedrows,303–305
hierarchicalquery,defined,575
I
ID(identification),forexamregistration,4–5
IEEE(InstituteofElectricalandElectronicsEngineers),575
IF-THEN-ELSE,DECODEfunction,267
implicitcommit
COMMIT,multiplesessionsand,125–127
defined,123,575
invokedbyrestoreddata,430
overviewof,124–125
rulesforSAVEPOINT,131
implicitconversion,114–115,247–249
implicitindexcreation,414–415
in-lineconstraints,64–65,79
INoperator
multi-rowsubquery,371
single-rowsubquery,369
WHEREclause,169–170
INCREMENTBYinteger,sequences,408
INDEXobject,defined,43
indexes
alternativesonsamecolumnset,423–424
columns,421–422
defined,575
dropping,420–421
implicitcreationof,414–415
maintenance,418
OracleDatabaseoptimizerand,414
overviewof,412–413
recoverwithFLASHBACKTABLE,425–429
reviewcertificationsummary,436
reviewdrill,437–439
reviewself-testQ&A,443–444,448
asschemaobjects,391–392
singlecolumn,416–420
skipscanningincompositeindexes,419–420
unique,420
usage,416–418
INITCAPcharacterfunction,mixed-casestrings,207–208
inlineviews
createwithsubqueries,355
defined,575
reasonstouse,402
innerfunctions,234
innerjoins
defined,576
naturaljoinsas,327–329
oldersyntaxfor,324–325
overviewof,322–324
USINGkeywordfor,329–330
vs.outerjoins,321
INSERTstatements
addrowstotable,109
COMMIT,multiplesessionsand,125–127
conditionalmultitable,499–502,505–513
constraintsand,115–116
defined,576
asDMLstatement,29
executionerrorsin,116
indexesfor.Seeindexes
insertrowsviadefaultcolumnlist,110–113
insertrowsviaenumeratedcolumnlist,113–116
invisiblecolumnsandviews,404–407
permanentchangeswithCOMMIT,124
permanentresultswithGRANT,544
insingleMERGEstatement,514–517
subqueriesin,352–353,355
UPDATEvs.,121
forviews,396–400
instance,defined,576
InstituteofElectricalandElectronicsEngineers(IEEE),575
INSTRcharacterfunction,212
integrityconstraint.Seeconstraints
interpolation
defined,576
MEDIANperformslinear,289
PERCENTILE_CONTforlinear,232,235
INTERSECToperator
combinesmultiplequeriesintosinglequery,456–457
ensureSELECTcombineswith,451–452
inmultiplecombinations,458–459
assetoperator,450–451
INTERVALDAYTOSECONDdatatype,262
INTERVALYEARTOMONTHdatatype,61,183–186,261–262
INTERVALYEARTOSECONDdatatype,263
INTOclause
conditionalmultitableINSERT,499–501,505–511
mergerowsintotable,514–516
unconditionalmultitableINSERT,499,503–505
invalidviews,recompile,402–403
invisibleindexes,421–422
INVISIBLEkeyword,CREATEINDEX,422
invocationoffunctions,SQLstatements,203
ISNOTNULLoperator,WHEREclause,171–172
ISNULLoperator,WHEREclause,171–172
J
joins
avoidusingLOBswith,59
defined,320,576
displaydatafrommultipletables,320
ondynamicperformanceviews,478–479
impactonviews,403–407
inner,322–325
multitable,330–331
natural,327–329
non-equijoins,331–333
outer,335–339
reviewcertificationsummary,339
reviewdrill,340–341
reviewself-testQ&A,342–350
self-joins,333–335
tablealiasesusedby,325–327
typesof,320–321
USINGkeyword,329–330
K
key,defined,576
keyword,defined,576
L
LAGanalyticalfunction,226–230
largedatasets
featuresofmultitableINSERTs,498–502
mergerowsintotable,513–517
overviewof,498
performpivotwithmultitableINSERT,512–513
reviewcertificationsummary,518
reviewdrill,519–520
reviewself-testQ&A,521–527
useconditionalINSERTs,505–511
useunconditionalINSERTs,502–505
largeobjectdatatypes.SeeLOB(largeobject)datatypes
LASTfunction,292–293
LASTreservedword,576
LAST_DAYdatefunction,220
LEADanalyticalfunction,226–230
LEFTOUTERJOIN,338–339
LENGTHcharacterfunction,stringlength,211–212
LIKEcomparisonoperator,162–164,369
limitrows.Seerowsretrievedbyquery,limit
linear,defined,576
list
ofconstraintsintablecreation,78–79
ofdatabaseobjects,42–43
literals
alsocalledconstants,577
defined,577
LOB(largeobject)datatypes
cannotcreateindexoncolumnsof,413
convertLONGdatatypesto,62
defined,577
listof,61–62
restrictionsforexternaltables,87
logintouseraccount,withCONNECT,534
LONGdatatypes,convert,62
LOWERcharacterfunction,206–207
LPADcharacterfunction,209–210
LTRIMcharacterfunction,210–211
M
many-to-manyrelationships,23–24
marktime,restoredata,431–434
MAXfunction,286–287
MAX_STRING_SIZEparameter,VARCHAR2datatype,57
MAXVALUEinteger,sequences,408–409
MEDIANfunction,288–289
MERGEstatement
defined,577
asDMLstatement,29
mergerowsintotable,514–517
subqueriesacceptedby,352
metacharacteroperators,577
metadata,474–475,577
MINfunction,286–287
MINUSoperator
combinesmultiplequeriesintosinglequery,457–458
ensureSELECTcombineswith,451–452
inmultiplecombinations,458–459
assetoperator,450–451
MINVALUEinteger,sequences,408–409
mobilephone,inexamprocess,4,7
MODnumericalfunction,217
MONTHS_BETWEENdatefunction,221–222
multiple-choicequestions,onexam,5–6
multiple-columnsubqueries,356
multiplecolumns,grouping,298–299
multipleconstraints,65,78
multiple-rowsubqueries,356,369–372
multiplesessions,COMMITand,125–127
multirowfunctions.Seeaggregatefunctions
multitableINSERTs
defined,577
featuresof,498–502
pivotingwith,512–513
review,518–519
reviewself-testQ&A,521–524,526–527
useconditionalINSERTs,505–511
useunconditionalINSERTs,502–505
multitablejoins,330–331
N
namespaces
defined,577
namepriorityin,544
rolesand,551
understanding,51–53
naming
columns,inINSERTstatement,113
constraints,fromtablecreation,63–66
datadictionaryobjects,422
datadictionaryviewprefixes,476–477
retrieveddroppedobjects,428
SAVEPOINTstatements,130
schema,45
subqueries,usingWITH,364–365
tablesorotherobjects,48
views,353,395
NationalLanguageSupport(NLS),250–253,577
naturaljoins,327–329,577
NCLOB(NationalCharacterSetLargeObject)datatype,62,577
nestedfunctions
conversionfunctionsas,260
overviewof,234
andpatterns,234–235
rulesfor,300–303
singleaggregatefunctions,288
nestedinlineviews,400
nestedqueries,355
NEXTkeyword,182,577
NEXTVALpseudocolumn,sequencegenerators,410–412
NLS(NationalLanguageSupport),250–253,577
NLS_DATE_FORMAT,datedatatype,60
NOCYCLE,sequences,409
NOMAXVALUEinteger,sequences,408–409
NOMINVALUEinteger,sequences,408–409
non-equijoin,321,336–339,578
non-scalar(oraggregate)functions,234–235
nonschemaobjects,42–43,45–46
normalization,23–25,578
NoSQL,defined,578
NOTEXISTSoperator,subqueries,363
NOTINoperator,multi-rowsubqueries,371–372
NOTNULLconstraint
conceptofNULL,69–71
createdattimeoftablecreation,65,69
datatyperestrictionson,79–80
preventsINSERT/UPDATE/DELETEonviews,398
inPRIMARYKEYconstraint,71
reviewof,79
syntaxvariationin,67–68
NOToperator
withBETWEENinWHEREclause,171
HAVINGclauseusing,304–305
mayprecedeINoperator,170
operatorprecedence,168–169
overviewof,166–168
NOToperator,multi-rowsubqueries,371
NULL
conceptof,69–70
COUNTfunctionand,284–285
DECODEconditionalexpression,266–267
defined,578
ISNULL,ISNOTNULL,171–172
MEDIANfunctionignores,288
multi-rowsubqueriesand,371–372
NOTNULLconstraintand,70–71
NULLIFconditionalexpression,267–268
NVLconditionalexpression,267–268
ORDERBYclauseand,157
resultsofSELECTwithORDERBY,150
UNIQUEallowsadditionof,71
NULLIFconditionalexpression,267–268
NUMBERdatatype,58–59
numbers,392,578
numericdatatypes
AVGfunction,287–288
defined,578
formatmodelsfor,250–253
listof,58–59
MEDIANgroupfunctionfor,288–289
MINandMAXgroupfunctionsfor,286–287
RANKgroupfunctionfor,289–290
numericliterals,223
numericalfunctions
CEIL,215
FLOOR,215
MOD,217
overviewof,215
REMAINDER,216
ROUND-Number,215
tasksperformedby,204
TRUNC-Number,216
NUMTODSINTERVALfunction,222,263
NUMTOYMINTERVALfunction,222,262
NVLconditionalexpression,267–268
O
objectprivileges
assigntoroles,550–552
create/grant/testontable,542–544
defined,531,578
dependentprivileges,547
grant/revokewithALLPRIVILEGES,546–547
grantroles,549–552
granttoPUBLIC,451
privilegesvs.roles,552–553
revokewithREVOKE,546
viewindatadictionary,549
vs.systemprivileges,530–531,533
objects
categorizemain,42–46
DDLstatementsbuild,28
defined,578
dependent,428
DMLstatementsworkwithdatain,29–30
identifyuser-owneddatadictionary,482–484
manage.Seedatadictionaryviews
naming,48–53
schema,2
OFFSET,reservedword,186,578
ONcondition,mergerowsintotable,514–516
ONDELETECASCADEclause,recursivelytruncatechildtables,107–109
ONDELETEclause,FOREIGNKEYconstraint,76–77
ONEROWPERMATCH,578
one-to-manyrelationships,databasenormalization,23–24
ONLYkeyword,FETCH,183
operatorprecedence,168–169,458,578
operators
Boolean,164–169
comparison.Seecomparisonoperators
defined,578
optimizer,578
OPTIMIZER_USER_INVISIBLE_INDEXESparameter,421
ORoperator,Boolean,164–166,168–169,304–305
ORREPLACEkeywords,88,395–397
OracleCorporation,defined,579
OracleDatabaseoptimizer
overviewof,414
single-columnindexes,416–420
SQLstatementprocessing,413
structuringSQLstatementforindex,417
visibleandinvisibleindexes,421–422
OracleDatabaseSQLCertifiedAssociate,4–5,7–12
OracleDatabaseSQLLanguageReferenceManual.SeeSQLLanguage
ReferenceManual
Oracle,defined,578
Oracleexam.Seeexamoverview
OracleSQL*Plus,OracleSQLvs.,7
ORACLE_LOADER,externaltables,89–90
ORA_ROWSCNpseudocolumn,432,578
ORDERanalyticalfunction,224–226
ORDERBYclause
analyticfunctionsand,223
avoidLOBswith,59–61
columnaliasesand,154–155
controlorderofrowsreturned,459–461
expressionsin,153–154
withinlineviews,401
innerjoinsand,323
withLAGandLEADfunctions,227,229
andNULL,157
aspartofSELECT,157–158
referencebyname,149–151
restrictuseofGROUPBYinSELECT,299–300
sortcolumns,156–157
sortdirectionwithASCandDESC,151–152
sortrowsretrievedbySELECT,157–158
WITHTIEStiedto,184–186
userowlimitingclauseafter,182–186
useSELECTwithsetoperators,452
ORGANIZATIONEXTERNAL,externaltables,89–90
orphan,defined,579
out-of-lineconstraints,65–66,79
outerjoins
defined,579
FULLOUTERJOINS,337–338
LEFTOUTERJOINS,336
naturaljoinsas,327–329
Oraclesyntax,338–339
RIGHTOUTERJOINS,336–337
self-joins,334
USINGkeywordfor,329–330
vs.innerjoins,321
OVERanalyticalfunction,224–229
overloadedfunctions,253
OWNERview,datadictionary,476
P
parameters
characterfunctions.Seecharacterfunctionsconditionalexpressions.See
conditionalexpressions,SELECT
conversionfunctions.Seeconversionfunctionsdatefunctions.Seedate
functions
defined,579
function,202
groupfunctions.Seegroupfunctions
NLS,250–253
numericalfunctions,215–217
parent
defined,579
queries,insubqueries,352–353
parse,defined,579
PARTITIONBY
defined,579
usedwithanalyticversionofRANK,289–290
usedwithanalytics,225–226
usedwithLAGandLEADfunctions,227–228
passwords
ascasesensitive,534
createuseraccounts,533–534
establishnewuseraccounts,535–536
patternvariables,defined,579
patterns,andnestedfunctions,234–235
PERCENTkeyword,FETCH,182
percentsign(%)wildcardsymbol,LIKEcomparisonoperator,162–164
PERCENTILE_CONTanalyticalfunction,232–233
performance,dynamicviewsof,477–479
performancetuning
benefitsofindexes,413
designindexesfor,418
withOracleDatabaseoptimizer,417–418
persistentstore,asrelationaldatabase,25
PIVOTkeyword,513
pivotingdata,conditionalmultitableINSERT,512–513
POSIX(PortableOperatingSystemInterfaceforUnix),571,579
precedence
Booleanoperator,168–169
defined,579
operator,578
setoperatorshaveequal,458
precision
defined,580
NUMBERdatatype,58–59
predicates,defined,580
prefixes
datadictionaryviews,476–477
dynamicperformanceviews,477–479
namingobjects,51
schema,544–545
PREV,reservedword,580
PRIMARYKEYconstraint
composite,72–73
createdattimeoftablecreation,64–66,71–73
datatyperestrictionson,79–80
FOREIGNKEYconstraintrequiring,73–75
implicitindexcreation,414–415
requiredataforcolumnusing,70–71
reviewof,79
primarykey,defined,580
PRIMARYKEY,sequencesand,392
privatesynonyms,46,580
privileges
categoriesof,530–531
checkingviewstoinspect,486–487
defined,580
dependent,547
object.Seeobjectprivileges
rolesas.Seeroles
rolesvs.,552–553
system.Seesystemprivileges
problems,solvedbysubqueries,354–355
procedure,defined,580
production,defined,580
projection,defined,580
PROMPTcommand,ampersandsubstitution,178–180
pseudocolumns
defined,580
inlineviewsandROWNUM,401
sequencegenerators,410–412
PUBLICdatabaseuser
defined,580
GRANTandREVOKEprivilegeson,541
PUBLICSYNONYMownedby,544
PUBLICSYNONYM
createforsimpletable,46
fordynamicperformanceviews,478–479
overviewof,45–46
renamedatadictionaryobjectsvia,475–477
schemaprefixes,544–545
PURGEstatement
defined,580
asDMLstatement,29
removeallobjectsinschema’srecyclebin,429
removelatestversionofitemfromrecyclebin,428
removeobjectsfromrecyclebin,427
Q
queries
combineinlineviewswithcomplex,401
combinemultiple,withsetoperator,452–455
combineviewswithcomplex,396
defined,581
ondynamicperformanceviews,478–479
hierarchical,575
indexesimproveperformanceof,412
limitrowsretrievedby.Seerowsretrievedbyquery,limitasSELECT
statements,352
solvingwithsubqueries.Seesubqueriesquestions,howtoprogress
throughexam,5–6
quotednames,tables/otherobjects,50–51
quotes,ampersandvariableand,175–176
R
RANKfunction,289–290
RAWdatatypes,413
RDBMS(relationaldatabasemanagementsystem)
captureactualdatawith,20–21
ERDand.SeeERD(entity-relationshipdiagram)andjoins,320
relationshipbetweenSQLand,25–27
readconsistency
defined,581
ofdynamicperformanceviews,478–479,489
undosegmentsassuring,585
recompileviews,datadictionary,485–486
record,defined,581
recovery
ofdatawithinexistingtablesovertime,429–431
ofdroppedtables,425–429
identifypointatwhichtorestoredata,431–434
recyclebin
defined,581
DROPTABLEand,426
PURGE,428,429
recoverdependentobjects,428
redologs,defined,581
referencebyposition,sortcolumns,156
references,exam.SeeSQLLanguageReferenceManual
referentialintegrity
defined,581
FOREIGNKEYconstraintensuring,73
registrationprocess,exam,4–5
regularexpressions,defined,581
relationaldatabasemanagementsystem.SeeRDBMS(relationaldatabase
managementsystem)relationship,betweendatabaseandSQL,25–27
REMAINDERnumericalfunction,216
RENAMEstatement
asDDLstatement,28
defined,581
RENAMETOkeywords,recoverdroppedtable,426
reservedwords
defined,582
keywordsoftenas,576
namesfordatabaseobjectscannotbe,48
quotednamesmayinclude,50
RESOURCErole,551
restorepoint
create,434
defined,582
recoverdroppedtables,425
restrict
data.Seedata,restrictingandsortingoutputatruntime.Seeampersand
substitutionREVOKEALLstatement,547
REVOKEstatement
ALLPRIVILEGESoption,547
basicsyntaxforsystemprivileges,538
asDDLstatement,28
defined,582
doesnotcascadeforsystemprivileges,540
implicitcommitswhenexecuting,124
onprivileges,546
privilegesvs.roles,553
onPUBLICaccount,541–542
RIGHTOUTERJOIN,338–339
ROLEobjects,defined,44,46
ROLE_ROLE_PRIVS,datadictionaryview,552
roles
defined,531,582
grant,550–552
grantprivilegesindirectlyas,548
privilegesvs.,552–553
ROLE_SYS_PRIVSview,datadictionary,487
ROLE_TAB_PRIVSview,datadictionary,487
rollback
defined,582
FLASHBACKTABLEstatementand,426
ROLLBACKstatement
controltransactionswith,127–129
defined,30,122,582
rollbacktonamedSAVEPOINT,132–133
rulesforusingSAVEPOINT,129–131
undochangesbeforeexecutingCOMMITvia,123
ROUNDdatefunction,218–219,220
ROUND-numberfunction,215
ROWNUMpseudocolumn,401
rows
controlorderofreturned,459–461
defined,582
findSCNforgiven,432
include/excludegrouped,303–305
insertintotables,109–116
mergeintotable,514–517
multiple-rowsubqueriesand,356,369–372
sequencessupportaddingtable,392
single-rowsubqueriesand,356,365–369
SQLlimitingclausefor,182–186
subqueriesreturncolumnsin,352
useSQLrowlimitingclause,182–186
rowsretrievedbyquery,limit
additionalconcepts,172–173
Booleanlogic,164–169
overviewof,157–158
WHEREclause,158–164,169–172
rowsretrievedbyquery,sort
ASCandDESC,151–152
columnalias,154–155
combinations,156–157
expressions,153–154
ORDERBYandNULL,157
overviewof,148–149
referencebyname,149–151
referencebyposition,156
RPADcharacterfunction,209–210
RTRIMcharacterfunction,210–211
rules
columnalias,154–155
combineSELECTwithsetoperators,451–452
createviews,395
datatypecomparisons,161
databasenormalization,23–25
GROUPBYclause,296–297
namedatabaseobjects,48–50
nestingfunctions,300–303
SAVEPOINT,130–131
runtime
valueofsubstitutionvariableat,173–177
violatedconstraintscausingerrorsat,115–116
S
savepoint,defined,582
SAVEPOINTstatement
controltransactionswith,129–132
defined,30,122,582
ROLLBACKtoparticularnamed,132–133
scalarfunctions.Seesingle-row(scalar)functions
scalarsubquery,353,357,582
scale,58–59,582
schema
create/useindexes.Seeindexes
create/usesequences,409–412
createviews.Seeviews
defined,582
flashbackand.Seeflashbackoperationsfunctionalityof,390–392
listof,42–43
nonschemaobjectsvs.,45–46
overviewof,44–45
prefixes,544–545
reviewcertificationsummary,435–436
reviewdrill,437–439
reviewself-testQ&A,440–448
SCN(systemchangenumber)
conversionfunctions,433–434
defined,582,584
identifyrestorepointvia,434
markpointatwhichtorestoredata,431–434
recoverdroppedtablesvia,425
restoredatausingTIMESTAMPvs.,432
SAVEPOINTnameassociatedwith,130
SCN_TO_TIMESTAMPfunction,433
SEARCH_CONDITIONcolumn,datadictionaryview,488
second-generationlanguage(2GL),569
secondnormalform(2NF),23–25
segments
defined,582
undo,425,585
SELECTCURRENT_SCNFROMV$DATABASE,431
SELECTstatements
applyconditionalexpressions,264–269
buildtoretrievedatafromtable,30–32
WITHclause,364–365
combinewithsetoperators,451–459
controlorderofrowsreturned,459–461
defined,583
DML,29–30
functionsin.Seesingle-row(scalar)functionsGROUPBYuniqueto.
SeeGROUPBYclauseidentifyrowswithWHEREclause,158–159
madeintosubqueries.Seesubqueries
querydataviacorrelatedsubqueriesin,355,357–359
restrictingandsortingdatawith.Seedata,restrictingandsortingrules
forcreatingviews,395
useexternaltables,91
viewasnamed,391,392
selection,defined,583
selectivity,defined,583
self-join
defined,583
FIRSTandLASTfunctionsin,293
overviewof,333–335
semicolonterminationcharacter,SQLvs.SQL*Plus,54–55,180,534
semijoin,363,583
sequence
createanddrop,408–409
defined,44,583
overviewof,407–408
asschemaobject,392
use,409–410
session,defined,583
SESSION_PRIVS,datadictionaryview,487,548
SESSION_ROLES,datadictionaryview,552
SETclause
setoperatorsvs.,119
UPDATEstatementand,117–119,360–362
SETCOLINVISIBLEONstatement,404
SETcommands,ampersandsubstitution,177–178,180–181
setoperators
combinemultiplequeriesintosinglequery,452–455
controlorderofrowsreturned,459–461
defined,583
descriptionof,450–451
ensureSELECTcombineswith,451–452
INTERSECT,456–457
MINUS,457–458
multiplecombinationsof,458–459
overviewof,450
preventsINSERT/UPDATE/DELETEonviews,398
reviewcertificationsummary,462
reviewdrill,463
reviewself-testQ&A,464–472
SETclausevs.,119
UNIONALL,456
SETUNUSED,columns,84–86
SHOWcommand,ampersandsubstitution,177–178
single-columnindexes,416–420
singlequoteescapecharacter,207–208,252,570
single-row(scalar)functions
character.Seecharacterfunctions
date.Seedatefunctions
defined,280
DUALtableand,206
groupfunctionsvs.,281–283
nesting,234–235
numerical,215–217
overviewof,202
reviewcertificationsummary,235–236
reviewdrill,237
reviewself-testQ&A,238–244
rulesfornesting,300–303
inSELECTstatements,205
typesof,202–205
single-rowsubqueries,356,365–369
SKIP,reservedword,583
skipscanning,419
SocialSecurityNumbers(SSNs),avoidusing,420
SOMEcomparisonoperator,multi-rowsubquery,371
sort
data.Seedata,restrictingandsortingoutputatruntime.Seeampersand
substitutionrows.Seerowsretrievedbyquery,sortSOUNDEXcharacter
function,213–214
specialcharacters,namingdatabaseobjects,48
SQLFundamentalsI(1Z0-051exam),7–12
SQLLanguageReferenceManual
aggregatefunctions,293
databaseobjects,42
privileges,537
asreferenceforthisbook,16
reservedwords,48
SQLfunctions,233
SQLstatementsascommands,29
valuesforNUMBERdatatype,58
SQLstatements
mostcommonlyused,26–27
purposeofDDL,28–29
purposeofDML,29–30
typesofinOracleSQL,27
SQL(StructuredQueryLanguage)
buildSELECTstatement,30–32
defined,583
ERD/relationaldatabaseconnection.SeeERD(entity-relationship
diagram)examoverview.Seeexamoverview
overviewof,2–4
purposeofDDL,28–29
purposeofDML,29–30
relationshipbetweendatabaseand,25–27
reviewcertificationsummary,32
reviewdrill,33–34
reviewself-testQ&A,35–39
rowlimitingclause,182–186
SQL*Plus.Seeampersandsubstitution
SSNs(SocialSecurityNumbers),avoidusing,420
standalonequeries,352
standarddeviation
aggregatefunctionssupporting,281
calculatingSTTDEV,230–232
defined,583
standardtime
daylightsavingtimeas1-houroffsetfrom,573
defined,583
timezonesuseuniform,585
STARTWITHinteger,sequences,408
statements,defined,583
STDDEVanalyticalfunction,230–232
stringdatatype,57
strings,defined,583
structure,ofdatadictionaryviews,475–477
StructuredQueryLanguage.SeeSQL(StructuredQueryLanguage)study
materials,exam,13–15
subjectareas,exam,12–13
subqueries
defined,352,584
multitableINSERTsrequire,499–501,505–511
overviewof,352–353
problemssolvedby,354–355
querydatausingcorrelated,357–359
reviewcertificationsummary,373
reviewdrill,374–376
reviewself-testQ&A,377–388
typesof,356–357
update/deleterowsusingcorrelated,359–363
useEXISTSandNOTEXISTSoperators,363
useWITHclause,364–365
writemultiple-row,369–372
writesingle-row,365–369
subqueryfactoring,WITHclause,364
substitutionvariables,7
SUMfunction,224–226
summaryscreen,exam,6
superaggregate,defined,584
SUSTRcharacterfunction,212–213
synonyms
datadictionaryviews,477
defined,584
dynamicperformance,479
GV$prefixinglobaldynamicperformanceviews,477
renamingdatadictionaryobjectsviapublic,475–477
schemaprefixesand,544–545
SYNONYMobject,44
V$prefixindynamicperformanceviews,477
syntax,defined,584
SYSuseraccount,475,584
SYSDATEdatefunction,217
system-assignednames,53,66–67
systemprivileges
WITHADMINOPTION,539–540
ALLPRIVILEGES,540–541
ANYkeyword,535–538
assigntoroles,550–552
defined,531,584
GRANTandREVOKEonPUBLIC,541–542
grantontablesandusers,542–552
grantingwithGRANTstatement,535–538
listofsome,531–533
overviewof,530–531
prerequisites,533–535
PUBLICkeyword,541–542
viewindatadictionary,547–548
vs.objectprivileges,533
SYSTEMuseraccount,530,584
T
TABLEobject,defined,43
tables
aliases,324–327,330–331,335
constraints,390
createsimple,46–48
datadictionaryinformationstoredin,475
defined,584
external,86–91
indexeson.Seeindexes
inspectindatadictionary,484–485
invisiblecolumnsand,404–405
join.Seejoins
manipulatedata.Seedata,manipulatingmergerowsinto,514–517
naming,48–53
privilegesonuserand,542–552
recoverdropped,425–429
asschemaobjects,390
usesubqueriestopopulate,355
tables,create/manage
categorizeobjects,42–46
constraints,63–80
datatypesforcolumns,56–63
dropcolumns,80–84
externaltables,86–91
overviewof,41
reviewcertificationsummary,91–93
reviewdrill,94–96
reviewself-testQ&A,97–104
setcolumnUNUSED,84–86
simpletables,46–54
structure,54–56
tablespaces,535,584
TCL(TransactionControlLanguage),30,584.Seealsocontroltransactions
technicalsupport,forthisbook,567
testlogistics,examregistration,4
testing
indexontablewithinvisibleindex,421–422
objectprivileges,542–544
text
datatypes,57
defined,584
searchingwithUPPER/LOWER,206–207
third-generationlanguage(3GL),569
thirdnormalform(3NF),23–25
timezone,585
timezonename,585
timezoneoffset,585
TIMESTAMPdatatype
conversionfunctions,260,433–434
dateandNUMBERconstants,223
defined,60
recoverdroppedtablesidentifiedby,425
timestamp,defined,585
TIMESTAMPWITHLOCALTIMEZONEdatatype,61,263
TIMESTAMPWITHTIMEZONEdatatype,60–61,80,261
TIMESTAMP_TO_SCNconversionfunction,433
TOkeyword
FLASHBACKTABLEstatement,426
GRANTstatement,535–538
TO_CHARfunctions
TO_CHAR—CHARACTER,253–254
TO_CHAR—DATE,254–255
TO_CHAR—NUMBER,254
overviewof,253
ROUNDfunctionusedwith,218–219
TO_DATEfunction,259–260
TO_DSINTERVALfunction,262
TO_NUMBERfunction,250–253
top-levelquery,subqueries,352,365
TotalTesterexamsoftware,566
TO_TIMESTAMPnfunction,260,432
TO_TIMESTAMP_TZfunction,261
TO_YMINTERVALfunction,261
TransactionControlLanguage(TCL),30,584.Seealsocontroltransactions
transactions,defined,585
TRIMcharacterfunction,211
TRUNCfunction,216,219–220
TRUNCATEstatement,28,585
TRUNCATETABLEstatement,106–109
U
unconditional,defined,585
unconditionalmultitableINSERTstatements,499,502–505
UNDEFINE,ampersandsubstitution,177
underscore(_)wildcard,LIKEoperator,162–164
undofunction.SeeROLLBACKstatement
undosegments,425,585
Unicode,62,585
UNIONALLoperator,451–452,456,458–459
UNIONoperator
combinemultiplequeriesintosinglequery,452–455
controlorderofrowsreturned,459–461
ensureSELECTcombineswith,451–452
inmultiplecombinations,458–459
assetoperator,450–451
UNIONALLoperatorvs.,456
UNIQUEconstraint
composite,71
createdattimeoftablecreation,71
datatyperestrictionson,79–80
implicitindexcreation,414–415
inPRIMARYKEYconstraint,71
reviewof,79
uniqueindexvs.,420
unique,defined,585
uniqueidentifier,defined,585
uniqueindexes,420
uniquenames,andnamespaces,51–53
UNUSED,setcolumnsto,84–87
UPDATEstatement
COMMIT,multiplesessions,and,125–127
defined,585
asDMLstatement,29
executeonviews,396–400
indexmaintainedwithevery.Seeindexesquerydataviacorrelated
subqueriesin,355,357–359
insingleMERGEstatement,514–516
updaterowsintable,117–121
updaterowswithcorrelatedsubquery,360–362
usesubqueriesin,352–353,355
UPPERcharacterfunction,textsearch,206–207
uppercase,defined,585
useraccesscontrol
privileges,530
privilegesontablesandusers,542–552
privilegesvs.roles,552–553
PUBLICuseraccount,541
reviewcertificationsummary,554
reviewdrill,555–556
reviewself-testQ&A,557–564
systemprivileges.Seesystemprivilegesuseraccount
defined,585
identifyownedobjectsindatadictionary,482–484
overviewof,45
privilegesontables,542–552
roles,551
schemaobjectsvs.nonschemaobjects,45–46
viewsystemprivileges,548
user-definedfunctions,203
user-definedtypes,61
USERfunction,205
USERobject,44,46
USER_prefix,datadictionaryviews,476–477,478
USER_CATALOGview,datadictionary,482–484
USER_CONSTRAINTS,datadictionaryview,487–488
username,createuseraccount,533–534
USER_OBJECTS,datadictionaryview,484,486
USER_RECYCLEBIN,DROPTABLE,426
USER_SYS_PRIVS,datadictionaryview,486,548
USER_TAB_COLUMNS,datadictionaryview,484–485
USER_TABLESview,datadictionary,475–476,484–485
USER_TAB_PRIVS,datadictionaryview,486,548
USER_VIEW,datadictionaryview,486
USINGkeyword,329–330,514–516
UTC(CoordinatedUniversalTime),583,585
utilities,Oracle,88,124
V
V$prefix,dynamicperformancesynonyms,478–479
V_$prefix,dynamicperformanceviews,477–478
VALUESclause,multitableINSERTs,499–500,503–505
VARCHAR2datatype,57
variable,defined,585
variance
aggregratefunctionsfor,305
calculatestandarddeviationand,230–232
defined,585
VARIANCEfunction,withSTDDEV,230–232
VERIFY,ampersandsubstitution,178
views.Seealsodatadictionaryviews
ALTERVIEWstatement,402–403
andconstraints,397
create,393–397
create/dropsequences,408–410
defined,44,585
FIRSTandLASTfunctionsin,293
inline,400–402
INSERTstatementwith,109
ofmultipletables.Seejoins
overviewof,392–393
recompileinvalid,402–403
reviewcertificationsummary,435
reviewdrill,437
reviewself-testQ&A,440–442,446–447
asschemaobjects,391
UPDATEstatementwith,117
updateable,397–400
usingsubqueries,353
visible/invisiblecolumnsimpacting,403–407
visiblecolumns,403–407
visibleindexes,421–422
VISIBLEkeyword,CREATEINDEX,422
W
WHENclause
conditionalmultitableINSERTwith,499–502,505–511
unconditionalmultitableINSERTomits,502–505
WHEN/THENcomparisonpair,CASE,265
WHEREclause
additionalfeaturesof,169–172
benefitsofindexes,413
compareexpressionswith,159–160
customize,172
datatypecomparisonsand,160–162
DELETEstatementwith,121–122,362–363
innerjoinswith,324
LIKEcomparisonoperatorwith,162–164
limitrowsretrievedbyquerywith,158–159
mergerowsintotablewith,514–516
supportforBooleanlogic,164–169
UPDATEstatementwith,117–118,120–121,360–362
usemultiplesubquerieswithin,368
useSQLrowlimitingclauseafter,182–186
usesubqueries,353
wildcardsearches,162–164,369
window,defined,585
wintertimezone.Seestandardtime
WITHADMINOPTIONclause,GRANT,539–540,551
WITHclause,364–365
WITHGRANTOPTIONclause,GRANT,545–546
WITHTIES,rowlimiting,183–186