There is an everincreasing demand for staff with IT industry certification. The benefits to employers are significant—they can be certain that staff have a certain level of competence—and the benefits to the individuals, in terms of demand for their services, are equally great. Many employers now require technical staff to have certifications. The Oracle certifications are among the most sought after. But apart from rewards in a business sense, knowing that you are among a relatively small pool of elite Oracle professionals and that you have proved your competence is a personal reward well worth attaining.
Trang 2OCA Oracle Database 12c:
SQL Fundamentals I
Exam Guide (Exam 1Z0-061)
®
Trang 3ABOUT THE AUTHOR
Roopesh Ramklass (Canada) is an Oracle Certified Master with expertise in
infrastructure, middleware, and database architecture He has worked for Oracle Global Support, Advanced Customer Services, and Oracle University He has run
an IT consultancy and is experienced with infrastructure systems provisioning, software development, and systems integration He has spoken at numerous Oracle User Group conferences and is the author of several technology books
About the Technical Editor
Cecil Strydom has been working exclusively as an Oracle DBA for the last 13 years,
covering everything from performance tuning to disaster recovery He has worked
with Oracle database versions 8 through 11g and has experience with RAC, Data
Guard, eBusiness, Portal, Apex, and various other Oracle applications Cecil is an OCP-certified Oracle DBA and is currently a systems consultant for a multinational company based in Johannesburg, South Africa
Trang 4OCA Oracle Database 12c:
SQL Fundamentals I
Exam Guide (Exam 1Z0-061)
Roopesh Ramklass
New York Chicago San Francisco Athens London Madrid Mexico City Milan New Delhi Singapore Sydney Toronto
McGraw-Hill Education is an independent entity from Oracle Corporation and is
not affiliated with Oracle Corporation in any manner This publication and CD-ROM
may be used in assisting students to prepare for the OCA Oracle Database 12c:
SQL Fundamentals I exam Neither Oracle Corporation nor McGraw-Hill Education
warrants that use of this publication or CD-ROM will ensure passing the relevant exam.
®
Trang 5McGraw-Hill Education books are available at special quantity discounts to use as premiums and sales promotions,
or for use in corporate training programs To contact a representative, please visit the Contact Us pages at www mhprofessional.com.
OCA Oracle Database 12c: SQL Fundamentals I Exam Guide (Exam 1Z0-061)
Copyright © 2014 by McGraw-Hill Education (Publisher) All rights reserved Printed in the United States of America Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced
or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of Publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates All other trademarks are the property
of their respective owners, and McGraw-Hill Education makes no claim of ownership by the mention of products that contain these marks.
Screen displays of copyrighted Oracle software programs have been reproduced herein with the permission of Oracle Corporation and/or its affiliates.
1234567890 DOC DOC 10987654 ISBN: Book p/n 978-0-07-182027-1 and CD p/n 978-0-07-182026-4
of set 978-0-07-182028-8 MHID: Book p/n 0-07-182027-2 and CD p/n 0-07-182026-4
Cenveo Publisher Services
Art Director, Cover
Jeff Weeks
Information has been obtained by Publisher from sources believed to be reliable However, because of the possibility
of human or mechanical error by our sources, Publisher, or others, Publisher does not guarantee to the accuracy, adequacy, or completeness of any information included in this work and is not responsible for any errors or omissions
or the results obtained from the use of such information.
Trang 6With love to Ameetha for sharing your journey with me
Trang 8CONTENTS AT A GLANCE
1 Relational Database Design Using Oracle 1
2 Data Retrieval Using the SQL SELECT Statement 55
3 Restricting and Sorting Data 109
4 Single-Row Functions 175
5 Using Conversion Functions and Conditional Expressions 233
6 Reporting Aggregated Data Using the Group Functions 277
7 Displaying Data from Multiple Tables 315
8 Using Subqueries to Solve Problems 365
9 Using the Set Operators 395
10 Manipulating Data 423
11 Using DDL Statements to Create and Manage Tables 475
A About the CD-ROM 513
Glossary 517
Index 533
Trang 10Acknowledgments xix
Preface xxi
Introduction xxv
1 Relational Database Design Using Oracle 1
Position the Server Technologies 3
The Oracle Server Architecture 3
The Oracle WebLogic Server 5
Oracle Enterprise Manager 7
Cloud Computing 8
Exercise 1-1: Investigate Your Database and Application Environment 9
Development Tools and Languages 10
Understand Relational Structures 11
Real-World Scenarios 11
Data Modeling 12
Entities and Relations 12
Exercise 1-2: Design an Entity-Relationship Diagram for the Geological Cores Scenario 20
Rows and Tables 22
Summarize the SQL Language 26
SQL Standards 27
SQL Commands 27
A Set-Oriented Language 28
Use the Client Tools 29
SQL*Plus 30
SQL Developer 37
Create the Demonstration Schemas 42
Users and Schemas 42
The HR and OE Schemas 43
Demonstration Schema Creation 46
Trang 11✓ Two-Minute Drill 49
Q&A Self Test 50
Lab Question 52
Self Test Answers 53
Lab Answer 54
2 Data Retrieval Using the SQL SELECT Statement 55
List the Capabilities of SQL SELECT Statements 56
Introducing the SQL SELECT Statement 56
The DESCRIBE Table Command 57
Exercise 2-1: Describing the Human Resources Schema 60
Capabilities of the SELECT Statement 62
Execute a Basic SELECT Statement 64
The Primitive SELECT Statement 64
Syntax Rules 69
Exercise 2-2: Answering Our First Questions with SQL 72
SQL Expressions and Operators 75
The NULL Concept 87
Exercise 2-3: Experimenting with Expressions and the DUAL Table 92
✓ Two-Minute Drill 96
Q&A Self Test 98
Lab Question 100
Self Test Answers 102
Lab Answer 104
3 Restricting and Sorting Data 109
Limit the Rows Retrieved by a Query 110
The WHERE clause 110
Comparison Operators 119
Exercise 3-1: Using the LIKE Operator 131
Boolean Operators 133
Precedence Rules 139
Trang 12Sort the Rows Retrieved by a Query 143
The ORDER BY Clause 143
Exercise 3-2: Sorting Data Using the ORDER BY Clause 148
Ampersand Substitution 150
Substitution Variables 150
Define and Verify 157
Exercise 3-3: Using Ampersand Substitution 163
✓ Two-Minute Drill 166
Q&A Self Test 168
Lab Question 170
Self Test Answers 171
Lab Answer 173
4 Single-Row Functions 175
Describe Various Types of Functions Available in SQL 176
Defining a Function 176
Types of Functions 180
Use Character, Number, and Date Functions in SELECT Statements 183
Using Character Case Conversion Functions 183
Exercise 4-1: Using the Case Conversion Functions 188
Using Character Manipulation Functions 189
Exercise 4-2: Using the Character Manipulation Functions 202
Using Numeric Functions 203
Working with Dates 209
Using Date Functions 213
Exercise 4-3: Using the Date Functions 216
✓ Two-Minute Drill 225
Q&A Self Test 227
Lab Question 229
Self Test Answers 230
Lab Answer 231
Trang 135 Using Conversion Functions and
Conditional Expressions 233
Describe Various Types of Conversion Functions Available in SQL 234
Conversion Functions 234
Use the TO_CHAR, TO_NUMBER, and TO_DATE Conversion Functions 237
Using the Conversion Functions 238
Exercise 5-1: Converting Dates into Characters Using the TO_CHAR Function 245
Apply Conditional Expressions in a SELECT Statement 250
Nested Functions 250
General Functions 252
Exercise 5-2: Using NULLIF and NVL2 for Simple Conditional Logic 257
Conditional Functions 260
Exercise 5-3: Using the DECODE Function 266
✓ Two-Minute Drill 269
Q&A Self Test 271
Lab Question 273
Self Test Answers 274
Lab Answer 275
6 Reporting Aggregated Data Using the Group Functions 277
Describe the Group Functions 278
Definition of Group Functions 278
Types and Syntax of Group Functions 280
Identify the Available Group Functions 283
Using the Group Functions 283
Exercise 6-1: Using the Group Functions 289
Nested Group Functions 290
Group Data Using the GROUP BY Clause 292
Creating Groups of Data 292
The GROUP BY Clause 294
Trang 14Grouping by Multiple Columns 296
Exercise 6-2: Grouping Data Based on Multiple Columns 297
Include or Exclude Grouped Rows Using the HAVING Clause 299
Restricting Group Results 300
The HAVING Clause 301
Exercise 6-3: Using the HAVING Clause 304
✓ Two-Minute Drill 307
Q&A Self Test 309
Lab Question 311
Self Test Answers 312
Lab Answer 314
7 Displaying Data from Multiple Tables 315
Write SELECT Statements to Access Data from More Than One Table Using Equijoins and Nonequijoins 316
Types of Joins 317
Joining Tables Using ANSI SQL Syntax 322
Qualifying Ambiguous Column Names 323
The NATURAL JOIN Clause 325
Exercise 7-1: Using the NATURAL JOIN 327
The JOIN USING Clause 328
The JOIN ON Clause 330
Exercise 7-2: Using the NATURAL JOIN…ON Clause 332
N-Way Joins and Additional Join Conditions 333
Nonequijoins 336
Join a Table to Itself Using a Self-Join 338
Joining a Table to Itself Using the JOIN…ON Clause 338
Exercise 7-3: Performing a Self-Join 340
View Data That Does Not Meet a Join Condition by Using Outer Joins 341
Inner versus Outer Joins 342
Left Outer Joins 343
Right Outer Joins 345
Full Outer Joins 346
Exercise 7-4: Performing an Outer-Join 347
Trang 15Generate a Cartesian Product of Two or More Tables 349
Creating Cartesian Products Using Cross Joins 350
Exercise 7-5: Performing a Cross-Join 351
✓ Two-Minute Drill 356
Q&A Self Test 358
Lab Question 361
Self Test Answers 362
Lab Answer 363
8 Using Subqueries to Solve Problems 365
Define Subqueries 366
Exercise 8-1: Types of Subqueries 367
Describe the Types of Problems That the Subqueries Can Solve 369
Use of a Subquery Result Set for Comparison Purposes 369
Star Transformation 371
Generate a Table from Which to SELECT 372
Generate Values for Projection 373
Generate Rows to be Passed to a DML Statement 373
Exercise 8-2: More Complex Subqueries 374
List the Types of Subqueries 376
Single- and Multiple-Row Subqueries 376
Correlated Subqueries 377
Exercise 8-3: Investigate the Different Types of Subqueries 379
Write Single-Row and Multiple-Row Subqueries 382
Exercise 8-4: Write a Query That Is Reliable and User Friendly 383
✓ Two-Minute Drill 387
Q&A Self Test 388
Lab Question 392
Self Test Answers 393
Lab Answer 394
9 Using the Set Operators 395
Describe the Set Operators 396
Sets and Venn Diagrams 396
Trang 16Use a Set Operator to Combine Multiple
Queries into a Single Query 400
The UNION ALL Operator 401
The UNION Operator 401
The INTERSECT Operator 403
The MINUS Operator 403
More Complex Examples 405
Exercise 9-2: Using the Set Operators 407
Control the Order of Rows Returned 410
Exercise 9-3: Control the Order of Rows Returned 411
✓ Two-Minute Drill 416
Q&A Self Test 417
Lab Question 419
Self Test Answers 420
Lab Answer 421
10 Manipulating Data 423
Describe Each Data Manipulation Language (DML) Statement 424
INSERT 425
UPDATE 426
DELETE 427
MERGE 428
TRUNCATE 429
DML Statement Failures 429
Insert Rows into a Table 433
Exercise 10-1: Use the INSERT Command 439
Update Rows in a Table 441
Exercise 10-2: Use the UPDATE Command 444
Delete Rows from a Table 446
Removing Rows with DELETE 446
Exercise 10-3: Use the DELETE Command 447
Removing Rows with TRUNCATE 449
MERGE 450
Trang 17Control Transactions 451
Database Transactions 451
The Transaction Control Statements 455
Exercise 10-4: Use the COMMIT and ROLLBACK Commands 456
✓ Two-Minute Drill 463
Q&A Self Test 465
Lab Question 469
Self Test Answers 471
Lab Answer 473
11 Using DDL Statements to Create and Manage Tables 475
Categorize the Main Database Objects 476
Object Types 476
Users and Schemas 478
Naming Schema Objects 479
Object Namespaces 481
Exercise 11-1: Determine What Objects Are Accessible to Your Session 482
Review the Table Structure 482
Exercise 11-2: Investigate Table Structures 483
List the Data Types That Are Available for Columns 484
Exercise 11-3: Investigate the Data Types in the HR schema 488
Create a Simple Table 488
Creating Tables with Column Specifications 489
Creating Tables from Subqueries 490
Altering Table Definitions After Creation 492
Dropping and Truncating Tables 493
Exercise 11-4: Create Tables 494
Explain How Constraints Are Created at the Time of Table Creation 496
The Types of Constraints 497
Defining Constraints 500
Exercise 11-5: Work with Constraints 504
Trang 18✓ Two-Minute Drill 506
Q&A Self Test 507
Lab Question 509
Self Test Answers 510
Lab Answer 511
A About the CD-ROM 513
System Requirements 514
Total Tester Premium Practice Exam Software 514
Installing and Running Total Tester Premium Practice Exam Software 514
Electronic Book 515
Technical Support 515
Total Seminars Technical Support 515
McGraw-Hill Content Support 515
Glossary 517
Index 533
Trang 20This book was written amidst emigrating from South Africa to Canada and completed
during one of the most brutal winters in Canadian history Concluding the task to a standard I am satisfied with during this tumultuous time would not have been possible without the love, support, encouragement, and friendship of my wife, Dr Ameetha Garbharran
■ I am grateful too for the meticulous attention to detail and wisdom of the technical editor, my esteemed colleague and friend Cecil Strydom, who kept
me focused on the quality of this endeavor
■ Finally, thank you to the team at McGraw-Hill Education, specifically Mary Demery and Stephanie Evans, who kept me on track with my deadlines and showed empathy and understanding during our intercontinental transition
Trang 22The objective of this study guide is to prepare you for the 1Z0-061 exam by familiarizing
you with the knowledge tested in the exam Because the primary focus of the book is
to help you pass the test, we don’t always cover every aspect of the related technology
Some aspects of the technology are only covered to the extent necessary to help you understand
what you need to know to pass the exam, but we hope this book will serve you as a valuable
professional resource after your exam
In This Book
This book is organized in such a way as to serve as an in-depth review for the
Oracle Database 12c: SQL Fundamentals exam for both novice and experienced
Oracle professionals Each chapter covers a major aspect of the exam, with an emphasis on the “why” as well as the “how to” of working with and supporting Oracle SQL
On the CD-ROM
For more information on the CD-ROM, please see the “About the CD-ROM”
appendix at the back of the book
Exam Objective Map
At the end of the Introduction you will find an Exam Objective Map This table has been constructed to allow you to cross-reference the official exam objectives with the objectives as they are presented and covered in this book The objectives are listed as presented by the certifying body with a chapter and page reference
Trang 23In Every Chapter
We’ve created a set of chapter components that call your attention to important items, reinforce key points, and provide helpful exam-taking hints Take a look at what you’ll find in each chapter:
■ Every chapter begins with Certification Objectives—what you need to know
in order to pass the section in the exam dealing with the chapter topic The Certification Objective headings identify the objectives within the chapter,
so you’ll always know an objective when you see it!
■ Exam Watch notes call attention to information about, and potential pitfalls
in, the exam These helpful hints are written by authors who have taken the exam and received their certification—who better to tell you what to worry about? They know what you’re about to go through!
■ Exercises are interspersed throughout the chapters These are designed to give
you a feel for the real-world experience you need in order to pass the exam
They help you master skills that are likely to be an area of focus in the exam
Don’t just read through the exercises; they are hands-on practice that you should be comfortable completing Learning by doing is an effective way to increase your competency with a product
■ On the Job notes describe the issues that come up most often in real-world
settings They provide a valuable perspective on certification- and related topics They point out common mistakes and address questions that have arisen from on-the-job discussions and experience
product-■ Inside the Exam sidebars highlight some of the most common and confusing
problems that students encounter when taking a live exam Designed to anticipate what the exam will emphasize, getting inside the exam will help ensure you know what you need to know to pass You can get a leg up on how to respond to those difficult-to-understand questions by focusing extra attention on these sidebars
Trang 24■ Scenario & Solution sections lay out potential problems and solutions in a
quick-to-read format
SCENARIO & SOLUTION
When querying the JOBS table for every row
containing just the JOB_ID and MAX_SALARY
columns, is a projection, selection, or join being
performed?
A projection is performed since the columns in the JOBS table have been restricted to the JOB_ID and MAX_SALARY columns
An alias provides a mechanism to rename a column
or an expression Under what conditions should you
enclose an alias in double quotes?
If an alias contains more than one word or if the case of
an alias must be preserved, then it should be enclosed
in double quotation marks Failure to double quote a multi-worded alias will raise an Oracle error Failure to double quote a single-word alias will result in the alias being returned in uppercase
The SELECT list of a query contains a single
column Is it possible to sort the results retrieved by
this query by another column?
Yes Unless positional sorting is used, the ORDER
BY clause is independent of the SELECT clause in a statement
■ The Certification Summary is a succinct review of the chapter and a
restatement of salient points regarding the exam
■ The Two-Minute Drill at the end of every chapter is a checklist of the main
points It can be used for last-minute review
■ The Self Test offers questions similar to those in the exam The answers to
these questions, as well as explanations of the answers, can be found at the end of each chapter By taking the Self Test after completing each chapter, you’ll reinforce what you’ve learned from that chapter while becoming familiar with the structure of the exam questions
■ The Lab Question at the end of the Self Test section offers a unique and
challenging question format that requires you to understand multiple chapter concepts in order to answer correctly These questions are more complex and more comprehensive than the other questions, as they test your ability
to take all the knowledge you’ve gained from reading the chapter and apply
it to complicated, real-world situations These questions are aimed to be more difficult than what you will find in the exam If you can answer these questions, you have proven that you know the subject!
✓
Q&A
Trang 25Some Pointers
Once you’ve finished reading this book, set aside some time to do a thorough review
You might want to return to the book several times and make use of all the methods
it offers for reviewing the material:
1 Reread all the Two-Minute Drills, or have someone quiz you You also can use
the drills as a way to do a quick cram before the exam You may want to make flashcards out of 3 × 5 index cards with the Two-Minute Drill material
2 Reread all the Exam Watch notes and Inside the Exam elements Remember that
these notes are written by authors who have taken the exam and passed They know what you should expect—and what you should be on the lookout for
3 Review all the Scenario & Solution sections for quick problem solving.
4 Retake the Self Tests Taking the tests right after you’ve read the chapter is
a good idea, because the questions help reinforce what you’ve just learned
However, it’s an even better idea to go back later and answer all the questions
in the book in a single sitting Pretend that you’re taking the live exam
When you go through the questions the first time, you should mark your answers on a separate piece of paper That way, you can run through the questions as many times as you need to until you feel comfortable with the material
5 Complete the exercises Did you do the exercises when you read through each
chapter? If not, do them! These exercises are designed to cover exam topics, and there’s no better way to get to know this material than by practicing Be sure you understand why you are performing each step in each exercise If there is something you are not clear on, reread that section in the chapter
Trang 26There is an ever-increasing demand for staff with IT industry certification The benefits
to employers are significant—they can be certain that staff have a certain level of competence—and the benefits to the individuals, in terms of demand for their services, are equally great Many employers now require technical staff to have certifications The Oracle
certifications are among the most sought after But apart from rewards in a business sense,
knowing that you are among a relatively small pool of elite Oracle professionals and that you have
proved your competence is a personal reward well worth attaining
There are several Oracle certification tracks—this book is concerned with the Oracle Database Administration certification track, specifically for release 12c of the
database There are three levels of DBA certification: Certified Associate (OCA), Certified Professional (OCP), and Certified Master (OCM) The OCA qualification
is based on two examinations, the first of which is covered in this book and may
be taken online The OCP qualification requires passing a third examination
These examinations can be taken at many Oracle Testing Centers or Pearson VUE Authorized Test Centers and consist of 60 to 70 questions to be completed in
90 minutes The OCM qualification requires completing a further two-day evaluation
at an Oracle testing center, involving simulations of complex environments and use
of advanced techniques
To prepare for the first OCA examination, you can attend an Oracle University instructor-led training course, you can study Oracle University online learning material, or you can read this book In all cases, you should also refer to the Oracle Documentation Library for details on syntax This book will be a valuable addition
to other study methods, but it is also sufficient by itself It has been designed with the examination objectives in mind, though it also includes a great deal of information that will be useful to you in the course of your work For readers working
in development, the subject matter of this book is also the starting point for studying Oracle Corporation’s development tools: SQL, PL/SQL, and the APEX development environment
SQL is an amazing language and the exam and this book are the first steps in
a journey that is likely to last the length of your career Study the material and
Trang 27experiment and as you work through the exercises and sample questions and become more familiar with the Oracle environment, you will realize that there
is one golden rule:
When in doubt, try it out
In a multitude of cases, you will find that a simple test that takes a couple of minutes can save hours of speculation and poring through manuals If anything is ever unclear, construct an example and see what happens This book was developed using Windows and Linux, but to carry out the exercises and your further investigations you can use any platform that is supported for Oracle
Your initiation into the exciting world of Oracle database administration is about
to begin
Exam 1Z0-061
1.0 Retrieving Data Using the SQL SELECT Statement
1.1 List the capabilities of SQL SELECT statements 2 56
1.2 Execute a basic SELECT statement 2 64
2.1 Limit the rows that are retrieved by a query 3 110
2.2 Sort the rows that are retrieved by a query 3 143
2.3 Use ampersand substitution to restrict and sort output at runtime 3 150
3.0 Using Single-Row Functions to Customize Output
3.1 Describe various types of functions available in SQL 4 176
3.2 Use character, number, and date functions in SELECT statements 4 183
4.0 Using Conversion Functions and Conditional Expressions
4.1 Describe various types of conversion functions that are available in SQL 5 234
4.2 Use the TO_CHAR, TO_NUMBER, and TO_DATE conversion functions 5 237
4.3 Apply conditional expressions in a SELECT statement 5 250
5.0 Reporting Aggregated Data Using the Group Functions
5.1 Identify the available group functions 6 283
5.2 Describe the use of group functions 6 278
Trang 28Official Objective Ch No Pg No
5.3 Group data by using the GROUP BY clause 6 292
5.4 Include or exclude grouped rows by using the HAVING clause 6 299
6.0 Displaying Data from Multiple Tables Using Joins
6.1 Write SELECT statements to access data from more than one table using
6.2 Join a table to itself by using a self-join 7 338
6.3 View data that generally does not meet a join condition by using outer joins 7 341
6.4 Generate a Cartesian product of all rows from two or more tables 7 349
7.0 Using Subqueries to Solve Queries
7.2 Describe the types of problems that the subqueries can solve 8 369
7.3 Describe the types of subqueries 8 376
7.4 Write single-row and multiple-row subqueries 8 382
8.0 Using the SET Operators
8.2 Use a set operator to combine multiple queries into a single query 9 400
8.3 Control the order of rows returned 9 410
9.0 Managing Tables Using DML Statements
9.2 Insert rows into a table 10 433
9.3 Update rows in a table 10 441
9.4 Delete rows from a table 10 446
10.0 Introduction to Data Definition Language
10.1 Categorize the main database objects 11 476
10.2 Explain the table structure 11 482
10.3 Describe the data types that are available for columns 11 484
10.4 Create a simple table 11 488
10.5 Explain how constraints are created at the time of table creation 11 496
Trang 301.05 Create the Demonstration Schemas
✓ Two-Minute Drill
Q&A Self Test
Trang 31The content of this chapter is not directly tested by the Oracle certification examination,
but it is vital in understanding the purpose of SQL This is considered prerequisite knowledge that every student should have, beginning with an appreciation of how the Oracle server technologies fit together and the positioning of each product
The Oracle server technologies product set is more than a database There are also the Oracle WebLogic Server and the Oracle Enterprise Manager Taken together, these are the server technologies that make up the Oracle Cloud Cloud computing
is an emerging environment for managing the complete IT environment and providing services to users on demand
Databases fundamentally provide the infrastructure for the organization, storage,
and retrieval of data in an efficient manner Oracle Database 12c has evolved
from a Relational Database Management System (RDBMS) to an Object RDBMS supporting the organization of virtually any type of information with no practical limit on the volume of data that may be stored The vast data volumes generated
by Amazon.com, the Large Hadron Collider (LHC) at CERN in Europe, and many financial institutions and governments are organized and managed in Oracle databases Although Oracle databases have features addressing demands for scalability, high availability, and superb performance, this guide will focus on the data organization problem Structured Query Language (SQL, pronounced “sequel”) is
an international standard for managing data stored in relational databases Oracle
Database 12c offers an implementation of SQL that is generally compliant with the
current standard, which is Core SQL:2011 Full details of the compliancy are in Appendix C of the SQL Language Reference, which is part of the Oracle Database Documentation Library As a rule, compliancy can be assumed
Throughout this book, two tools are used extensively for exercises: SQL*Plus and SQL Developer These are tools that developers use every day in their work The exercises and many of the examples are based on two demonstration sets of data, known as the HR and OE schemas There are instructions on how to launch the tools and create the demonstration schemas, though you may need assistance from your local database administrator to get started
This chapter consists of summarized descriptions of the Oracle server technologies, the SQL language, the client tools, and the demonstration schemas Several real-world data organization scenarios are considered while discussing the concepts behind the relational paradigm and normalizing of data into relational structures
Trang 32CERTIFICATION OBJECTIVE 1.01
Position the Server Technologies
There is a family of products that makes up the Oracle server technologies:
■ The Oracle database
■ The Oracle WebLogic Server
■ The Oracle Enterprise Manager
■ Various application development tools and languagesThese products each have a position in the Oracle product set The database
is the repository for data and the engine that manages access to it The Oracle WebLogic Server runs software that generates the web user interfaces that submit calls for data retrieval and modification to the database for execution The Oracle Enterprise Manager is a comprehensive administration tool for monitoring, managing, and tuning the Oracle processes and also (through plug-ins) third-party products
Lastly, there are tools and languages for developing applications; either applications that run on end users’ machines in the client-server model or applications that run centrally on application servers
The combination of the server technologies and the development tools make up
a platform for application development and delivery that enables the cloud The cloud is an approach to the delivery of IT services that maximizes the cost efficiency
of the whole environment by delivering computing power from a pool of available resources to wherever it is needed, on demand
The Oracle Server Architecture
An Oracle database is a set of files on disk It exists until these files are deliberately deleted There are no practical limits to the size and number of these files, and therefore no practical limits to the size of a database Access to the database is through the Oracle instance The instance is a set of processes and memory structures: it exists on the CPU(s) and in the memory of the server node, and this existence is temporary An instance can be started and stopped Users of the database establish sessions against the instance, and the instance then manages all access to the database It is absolutely impossible in the Oracle environment for any user to have direct contact with the database An Oracle instance with an Oracle database makes
up an Oracle server
Trang 33The processing model implemented by the Oracle server is that of client-server
processing, often referred to as two-tier In the client-server model, the generation
of the user interface and much of the application logic is separated from the management of the data For an application developed using SQL (as all relational database applications will be), this means that the client tier generates the SQL commands, and the server tier executes them This is the basic client-server split, with (as a general rule) a local area network between the two sides The network communications protocol used between the user process and the server process is Oracle’s proprietary protocol, Oracle Net
The client tier consists of two components: the users and the user processes
The server tier has three components: the server processes that execute the SQL, the instance, and the database itself Each user interacts with a user process Each user process interacts with a server process, usually across a local area network The server processes interact with the instance, and the instance with the database
Figure 1-1 shows this relationship diagrammatically A session is a user process in
communication with a server process There will usually be one user process per user and one server process per user process The user and server processes that make up sessions are launched on demand by users and terminated when no longer required;
this is the log-on and log-off cycle The instance processes and memory structures are launched by the database administrator and persist until the administrator deliberately terminates them; this is the database startup and shutdown cycle
The user process can be any client-side software that is capable of connecting
to an Oracle server process Throughout this book, two user processes will be used extensively: SQL*Plus and SQL Developer These are simple processes provided by Oracle for establishing sessions against an Oracle server and issuing ad hoc SQL A widely used alternative is TOAD (the Tool for Application Developers) from Quest Software, though this is licensed software End-user applications will need to be written with something more sophisticated than these tools, something capable of
Session components User
Trang 34managing windows, menus, proper onscreen dialogs, and so on Such an application could be written with the Oracle Development Tools, with Microsoft Access linked
to the Oracle ODBC drivers, with any third-generation language (such as C or Java) for which Oracle has provided a library of function calls that will let it interact with the server, or with any number of Oracle-compatible third-party tools What the user process actually is does not matter to the Oracle server at all When an end user fills in a form and clicks a Submit button, the user process will be generating an INSERT statement (detailed in Chapter 10) and sending it to a server process for execution against the instance and the database As far as the server is concerned, the INSERT statement might just as well have been typed into SQL*Plus as what is known as ad hoc SQL
Never forget that all communication with an Oracle server follows this client-server model The separation of user code from server code dates back to the earliest releases of the database and is unavoidable Even if the user process is running on the same machine as the server (as is the case if, for example, one is running a database on one’s own laptop for development or training purposes), the client-server split is still enforced Applications running in an application server environment (described in the next section) also follow the client-server model for their database access
The simplest form of the database server is one instance connected to one database, but in a more complex environment one database can be opened by many instances concurrently This is known as a RAC (Real Application Cluster) RAC can bring many potential benefits, which may include scalability, performance, and zero downtime The ability to dynamically add further instances running on supplementary nodes to a database is a major part of the database’s contribution to the cloud
The Oracle WebLogic Server
With the emergence of the Web as the standard communications platform for delivering applications to end users has come the need for application servers An application server replaces the client-side software traditionally installed on end-user terminals; it runs applications centrally, presenting them to users in windows displayed locally in web browsers The applications make use of data stored
in one or more database servers
The Oracle WebLogic Server is a platform for developing, deploying, and managing
web applications A web application can be defined as any application with which users
communicate with HTTP Web applications usually run in at least three tiers: a database tier manages access to the data, the client tier (often implemented as a web
Trang 35browser) handles the local window management for communications with the users, and an application tier in the middle executes the program logic that generates the user interface and the SQL calls to the database.
Web applications can be developed with a number of technologies, among which Java is predominant Applications written in Java should conform to the Java EE (Java Enterprise Edition) standard, which defines how such applications should
be packaged and deployed JEE and related standards are controlled by Oracle and accepted by virtually all software developers Oracle WebLogic Server is a JEE-compliant application server Oracle’s implementation of the standards allows for automatic load balancing and fault tolerance across multiple application servers
on multiple machines through JEE clustering Clustering virtualizes the provision
of the application service; users ask for an application that might be available from
a number of locations, and the cluster works out from where any one session or request can best be serviced If one location fails, others will take up the load, and more resources can be made available to an application as necessary The ability
to separate the request for a service from the location of its provision and to add
or remove JEE servers from a cluster dynamically is a major part of the Oracle WebLogic Server’s contribution to the cloud
It is important to note that Oracle’s commitment to international standards is very strong Applications running in the Oracle WebLogic Server environment can connect
to any database for which there are Java-compliant drivers; it is not necessary to use an Oracle database Applications developed with the Oracle WebLogic Server toolkits can
be deployed to any third-party JEE-compliant application server
The simplest processing model of web applications is three-tier: a client tier that manages the user interface, a middle tier that generates the interface and issues SQL statements to the data tier, and a data tier that manages the data itself In the Oracle environment, the client tier will be a browser (such as Mozilla Firefox or Windows Internet Explorer) that handles local window management, controls the keyboard, and tracks mouse movements The middle tier will be an Oracle WebLogic Server running the software (probably written in Java) that generates the windows sent to the client tier for display and the SQL statements sent to the data tier for execution
The data tier will be an Oracle server: an instance and a database In this three-tier environment, there are two types of sessions: end-user sessions from the client tier to the middle tier, and database sessions from the middle tier to the data tier The end-user sessions will be established with HTTP The database sessions are client-server sessions consisting of a user process and a server process, as described in the previous section
Trang 36It is possible for an application to use a one-for-one mapping of end-user session
to database session: each user, from their browser, will establish a session against the application server, and the application server will then establish a session against the database server on the user’s behalf However, this model has been proven to be
very inefficient when compared to the connection pooling model With connection
pooling, the application server establishes a relatively small number of persistent database sessions and makes them available on demand (queuing requests if necessary)
to a relatively large number of end-user sessions against the application server
Figure 1-2 illustrates the three-tier architecture using connection pooling
From the point of view of the database, it makes no difference whether a SQL statement comes from a client-side process such as SQL*Plus or Microsoft Access or from a pooled session to an application server In the former case, the user process all happens on one machine; in the latter, the user process has been divided into two tiers: an application tier that generates the user interface and a client tier that displays it
Oracle Enterprise Manager
The increasing size and complexity of IT installations makes management a challenging task This is hardly surprising: no one ever said that managing a powerful environment should necessarily be simple However, management tools can make the task easier and the administration staff more productive
Stateless nonpersistent sessions over HTTP
Browser
Browser
Browser
Browser
Trang 37Oracle Enterprise Manager comes in three forms:
■ Database Express
■ Fusion Middleware Control
■ Cloud ControlOracle Enterprise Manager Database Express is a graphical tool for managing one database, which may be a RAC clustered database It consists of a Java process running on the database server machine Administrators connect to Database Express from a browser, and Database Express then connects to the database server Database Express has facilities for real-time management, performance monitoring, and running scheduled jobs Oracle Enterprise Manager Fusion Middleware Control is a graphical tool for managing a Fusion Middleware deployment These deployments typically include Oracle WebLogic Server, an industry-leading application server which provides the container Java virtual machines (JVMs) that host Oracle or custom Java applications
Oracle Enterprise Manager Cloud Control globalizes the management environment
A management repository (residing in an Oracle database) and one or more management servers manage the complete environment: all the databases and application servers, wherever they may be Cloud Control can also manage the nodes, or machines, on which the servers run, as well as (through plug-ins) a wide range of third-party products Each managed node runs an agent process, which
is responsible for monitoring the managed target on the node: executing jobs against them and reporting status, activity levels, and alert conditions back to the management server(s)
Cloud Control provides a holistic view of the environment and, if well configured, makes administration staff far more productive than they are without it It becomes possible for one administrator to effectively manage hundreds of targets
Cloud Computing
Critical to the concept of cloud computing is service virtualization This means
that at all levels there is a layer of abstraction between what is requested and what
is provided End users ask for an application service and let the cloud work out which clustered JEE application server can best provide it Application servers ask for a database service and let the cloud work out from which RAC node the data can best be served Within the cloud there is a mapping of possible services to
Trang 38resources appropriately The result is that end users have neither the need nor the capacity to know from where their computing resources are actually being provided
The analogy often drawn is with delivery of domestic electricity: it is supplied on demand, and the home owner has no way of telling which power station is currently supplying him
The cloud is not exclusive to Oracle At the physical level, some operating system and hardware vendors are providing cloud-like capabilities These include the ability
to partition servers into virtual machines and dynamically add or remove CPU(s) and RAM from the virtual machines according to demand This is conceptually similar to Oracle’s approach of dynamically assigning application server and database server resources to logical services There is no reason why the two approaches cannot be combined Both are working toward the same goal and can work together
The result should be an environment where adequate resources are always available
on demand, without facing the issues of excess capacity at some times and performance at others It should also be possible to design a cloud environment with
under-no single point of failure, thus achieving the goal of 100 percent uptime that is being demanded by many users
The SQL application developer need not know how the cloud has been implemented The SQL will be invoked from an application server and executed by
an instance against a database: the cloud will take care of making sure that at any moment pools of application servers and instances sized appropriately for the current workload are available
EXERCISE 1-1
Investigate Your Database and Application Environment
This is a paper-based exercise, with no specific solution
Attempt to identify the user processes, application servers, and database servers used in your environment Try to work out where the SQL is being generated and where it is being executed Bear in mind that usually the user processes used by end users will be graphical and will frequently go through application servers; the database administration and development staff will often prefer to use client-server tools that connect to the database server directly
Trang 39Development Tools and Languages
The Oracle server technologies include various facilities for developing applications, some existing within the database, others external to it
Within the database, it is possible to use three languages The one that is unavoidable, and the subject of this book, is SQL SQL is used for data access, but
it cannot be used for developing complete applications It has no real facilities for developing user interfaces, and it also lacks the procedural structures needed for manipulating rows individually The other two languages available within the database fill these gaps They are PL/SQL and Java, although Java may also be used outside the database PL/SQL is a third-generation language (3GL) proprietary to Oracle It has the usual procedural constructs (such as if-then-else and looping) and facilities for user interface design In the PL/SQL code, one can embed calls to SQL
Thus, a PL/SQL application might use SQL to retrieve one or more rows from the database, then perform various actions based on their content, and then issue more SQL to write rows back to the database Java offers a similar capability to embed SQL calls within the Java code This is industry standard technology: any Java programmer should be able write code that will work with an Oracle database (or indeed with any other Java-compliant database)
Other languages are available for developing client-server applications that run externally to the database The most commonly used are C and Java, but it
is possible to use most of the mainstream 3GLs For all these languages, Oracle Corporation provides OCI (Oracle Call Interface) libraries that let code written
in these languages establish sessions against an Oracle database and invoke SQL commands
Many organizations will not want to use a 3GL to develop database applications
Oracle Corporation provides rapid application development tools such as Oracle Application Express, JDeveloper, ADF, and many other products These can make programmers far more productive than if they were working with a 3GL Like the languages, all these application development tools end up doing the same thing:
constructing SQL statements that are sent to the database server for execution
All developers and administrators working in the Oracle environment must know PL/SQL C and Java are not necessary, unless the project specifically uses them.
Trang 40CERTIFICATION OBJECTIVE 1.02
Understand Relational Structures
Several real-world data organization scenarios are introduced to discuss the relational paradigm and introduce some practical modeling techniques Critical
to an understanding of SQL is an understanding of the relational paradigm and
the ability to normalize data into relational structures Normalization is the work
of systems analysts, as they model business data into a form suitable for storing in relational tables It is a science that can be studied for years, and there are many schools of thought that have developed their own methods and notations
Real-World Scenarios
This guide uses several hypothetical scenarios, including the two canned scenarios called HR and OE provided by Oracle and frequently used as the context for exam questions to illustrate various SQL concepts The following scenarios evolve further
as new concepts are discussed
Car Dealership
Sid runs a car dealership and needs a system to keep track of the cars that she buys and sells She has noticed business taking a dive and wants to move into the twenty-first century and create a website that advertises available stock She needs a system to keep records of the cars she has bought and sold and the details of these transactions
Geological Cores
Core samples of the earth have been collected by your local geological survey agency
To ensure scientific rigor, the developers at GeoCore have determined that the system must track the exact geographical location, the elemental content of the core samples, and the dates of collection
Order Entry
The Order Entry (OE) scenario provided as a sample by Oracle contains information for a fictitious commercial system that tracks products, customers, and the sales orders that have been placed