OCP - SQL&PL - SQL (Vol1)
OCP - SQL&PL - SQL (Vol1)
Edition 1.1
M03989
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.
All other products or company names are used for identification purposes only,
and may be trademarks of their respective owners.
Publishers
Stephanie Jones
Kimberly Lee
Jennifer Robertson
Mark Turangan
Contents
Volume 1
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Related Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Typographic Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
I Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ1
Course Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ3
Course Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ5
The Relational Database Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ9
System Development Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ17
What Is Oracle? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ19
The Oracle Product Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ21
SQL, SQL*Plus, and PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ23
Summit Sporting Goods Demonstration Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ29
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IĆ33
iii
Negating Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć17
SQL Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć19
Querying Data with Multiple Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć27
Rules of Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć29
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć33
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć35
Practice 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć37
iv
The GROUP BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć13
Illegal Queries Using Group Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć19
Groups Within Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć23
The HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć25
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć31
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć33
Practice 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć34
6. Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć1
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć5
Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć7
How Are Nested Subqueries Processed? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć9
Single Row Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć11
Errors with Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć15
Multiple Row Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć17
HAVING Clause with Nested Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć19
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć21
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć23
Practice 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Ć25
Volume 2
7. Specifying Variables at Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć1
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć5
Substitution Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć7
Single Ampersand Substitution Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć9
Defining User Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć15
Passing Values into a Script File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć21
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć23
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć25
Practice 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Ć26
v
9. Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć1
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć5
Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć7
Oracle7 Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć13
Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć15
Creating a Table from a Table Instance Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć25
Creating a Table from Rows in Another Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć31
Confirming Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć33
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć35
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć37
Practice 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Ć39
vi
Disabling and Enabling a Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć15
Dropping a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć17
Renaming and Truncating a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć19
Adding a Comment to a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć21
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć23
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć25
Practice 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć27
vii
System Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć7
What Is a Role? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć11
Changing Your Password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć13
Granting Object Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć15
Confirming Privileges Granted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć21
Revoking Object Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć23
Creating a Synonym for an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć25
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć29
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć31
Practice 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć33
Volume 3
18. Overview of PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Ć1
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Ć5
PL/SQL Block Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Ć9
The PL/SQL Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Ć15
About Procedure Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Ć17
viii
Creating a Subprogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć7
Creating a Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć9
Comparing Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć15
Creating a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć17
Invoking Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć21
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć29
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć31
Practice 20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć33
ix
24. Processing Queries by Using Explicit Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć1
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć5
Controlling Explicit Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć7
Explicit Cursor Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć17
Cursors and Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć21
Cursors with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć23
Cursor FOR Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć25
Applying the WHERE CURRENT OF Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć27
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć29
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć31
Practice 24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Ć33
Volume 4
A Practice Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ1
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ3
Practice 1 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ4
Practice 2 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ8
Practice 3 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ20
Practice 4 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ29
Practice 5 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ39
Practice 6 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ46
Practice 7 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ55
Practice 9 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ59
Practice 10 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ63
x
Practice 11 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ68
Practice 12 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ82
Practice 13 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ88
Practice 14 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ97
Practice 15 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ105
Practice 16 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ109
Practice 17 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ116
Practice 19 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ154
Practice 20 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ155
Practice 21 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ158
Practice 22 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ163
Practice 23 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ170
Practice 24 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ177
Practice 25 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ186
Practice 26 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AĆ192
xi
Practice C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ45
Practice C Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ47
Glossary
Index
xii
Preface
Profile
Lesson Aim
Lesson 1: Selecting Rows In order to extract data from the database
you need to use the Structured Query
Language (SQL) SELECT command.
Lesson Aim
Lesson 3: Single Row Functions Functions make the basic query block
more powerful and are used to
manipulate data values. This is the first
of two lessons that explore functions.
You will focus on single row character,
number, and date functions, as well as
those functions that convert data from
one type to another, for example,
character data to numeric.
Lesson 4: Displaying Data from Multiple This lesson will cover how to obtain data
Tables from more than one table, using the
many different methods available.
Lesson 5: Group Functions This lesson further addresses functions.
You will focus on obtaining summary
information, such as averages, for groups
of rows. You will discuss how to group
rows in a table into smaller sets, and how
to specify search criteria for groups of
rows.
Lesson 6: Subqueries This lesson covers more advanced
features of the SELECT statement. You
can write subqueries in the WHERE
clause of another SQL statement to
obtain values based on an unknown
conditional value.
Lesson 7: Specifying Variables at You can create a command file
Runtime containing a WHERE clause to restrict
the rows displayed. To change the
condition each time the command file is
run, you use substitution variables.
Substitution variables can replace values
in the WHERE clause, a text string, and
even a column or a table name.
Preface xv
Profile continued
Lesson Aim
Lesson 8: Overview of Data Modeling Before you build your tables, you design
and Database Design your database. You examine the data
modeling process and relational database
concepts, and define normalization. You
also translate an entity relationship
model into a relational database design.
Lesson 9: Creating Tables You will create tables. You will also
build integrity constraints, which are
rules governing what can and cannot be
done with the data.
Lesson 10: Oracle Data Dictionary The Oracle data dictionary is one of the
most important components of the
Oracle7 Server. It consists of a set of
tables and views that provide a read-only
reference to the database.
Lesson 11: Manipulating Data Once your tables have been created, you
will need to add new rows, make
changes to rows in a table, or delete rows
by using data manipulation commands.
This lesson covers using SQL commands
to make changes to data. A number of
these data manipulation commands make
up a transaction, which you may either
save or delete using transaction controls.
Lesson 12: Altering Tables and After you create your tables, you may
Constraints need to change the table structures
because you omitted a column, your
column definition needs to be changed,
or you want to enable or disable
constraints. This lesson will demonstrate
how you can amend table structures as
well as add and remove constraints.
Lesson Aim
Lesson 13: Creating Sequences Many applications require the use of
unique numbers as primary key values.
You can either build code into the
application to handle this requirement or
use a sequence to generate unique
numbers. This lesson covers creating and
using sequences that crate unique
numbers.
Lesson 14: Creating Views In this lesson, you will see how views
can be used to present data to users in a
variety of ways. In addition, you will see
how integrity constraints can be
enforced, if using a view to insert,
update, or delete data.
Lesson 15: Creating Indexes If you want to improve the performance
of some queries, you should consider
creating an index. You can also use
indexes to enforce uniqueness on a
column or a collection of columns.
Lesson 16: Controlling User Access This lesson describes the Oracle7 Server
decentralized security system. Using the
commands covered in this lesson, you
can control database access to specific
objects and add new users with different
levels of access privileges. You can
provide alternative names for objects by
using the CREATE SYNONYM
command.
Preface xvii
Profile continued
Lesson Aim
Lesson 17: Summary of SQL and This lesson reviews the basic commands
SQL*Plus (optional) covered in the course so far.
Lesson 18: Overview of PL/SQL Overview lesson of how to create and
use PL/SQL program units and
subprograms using Oracle Procedure
Builder.
Lesson 19: Basics of Procedure Builder A key feature of procedural
programming is the ability to create and
debug code quickly and easily.
Procedure Builder provides all of the
functionality necessary for you to
successfully develop and debug PL/SQL
programs. This lesson enables you to
manipulate PL/SQL code using
Procedure Builder.
Lesson 20: Modularizing Programming Modularity allows you to break your
with Subprograms code into manageable, well-defined
units. Each of these units in PL/SQL has
two types of subprograms called
procedures and functions. You will learn
the structure of subprograms and how to
invoke them.
Lesson 21: Developing a Simple Create a simple PL/SQL block after
PL/SQL Block learning the various elements that
compose a block.
Lesson 22: Interacting with Oracle Access the database and control
transactions through SQL statements in
PL/SQL.
Lesson Aim
Lesson 23: Using Control Structures Control the flow of your PL/SQL block
by using conditional statements and
loops.
Lesson 24: Processing Queries with Use a multiple row SELECT statement
Explicit Cursors within PL/SQL to process many rows.
Declare and control explicit cursors,
which are used in loops, including the
cursor FOR loop.
Lesson 25: Error Handling When you execute PL/SQL code, you
may encounter errors. The error causes
the PL/SQL block to halt with an
exception. You can trap the exception
and perform actions conditionally using
exception handlers.
Lesson 26: Summary of PL/SQL Review the topics covered in the course.
(optional) Create a PL/SQL-based application for
manipulating and maintaining
information in your database.
Preface xix
Related Publications
Oracle Publications
Additional References
D System Release Bulletins
D Installation and User’s Guides
D read.me Files
D International Oracle User’s Group (IOUG) Articles
D Oracle Magazine
Preface xxi
Typographic Conventions continued
This icon indicates a warning relating to the subject matter. An example warning
might be “When deleting rows, word your WHERE clause carefully.”
Preface xxiii
xxiv Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
I
Introduction
IĆ2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Course Objectives
At the end of this course, you should be able to
D Describe the relational database approach, concepts, terminology, and operators.
D Create database structures such as tables and views using Structured Query
Language (SQL).
D Store, retrieve, and update data in the database.
D Develop PL/SQL blocks of application code using Procedure Builder to
manipulate data.
Introduction IĆ3
IĆ4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Course Outline
The course starts with an overview. The first module ends on Day 3 with an
optional summary covering the SQL and SQL*Plus content. The second module
ends on Day 5 with an optional summary of the PL/SQL section.
DAY 1
Lesson 1 Selecting Rows
Lesson 2 Limiting Selected Rows
Lesson 3 Single Row Functions
Lesson 4 Displaying Data from Multiple Tables
DAY 2
Lesson 5 Group Functions
Lesson 6 Subqueries
Lesson 7 Specifying Variables at Runtime
Lesson 8 Overview of Data Modeling and Database Design
Lesson 9 Creating Tables
Lesson 10 Oracle Data Dictionary
DAY 3
Lesson 11 Manipulating Data
Lesson 12 Altering Tables and Constraints
Lesson 13 Creating Sequences
Lesson 14 Creating Views
Lesson 15 Creating Indexes
Lesson 16 Controlling User Access
Lesson 17 Summary of SQL and SQL*Plus
(optional)
Introduction IĆ5
IĆ6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Course Outline continued
DAY 4
Lesson 18 Overview of PL/SQL
Lesson 19 Basics of Procedure Builder
Lesson 20 Modularizing Programming with Subprograms
Lesson 21 Developing a Simple PL/SQL Block
Lesson 22 Interacting with Oracle
DAY 5
Lesson 23 Controlling Flow in PL/SQL Blocks
Lesson 24 Processing Queries by Using Explicit Cursors
Lesson 25 Error Handling
Lesson 26 Summary of PL/SQL
(optional)
Introduction IĆ7
IĆ8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Relational Database Concept
The principles of the relational model were first outlined by Dr. E. F. Codd in a June
1970 paper called “A Relational Model of Data for Large Shared Data Banks.” In this
paper, Dr. Codd proposed the relational model for database systems.
The more popular models used at that time were hierarchical and network, or even
simple flat file data structures. Relational database management systems (RDBMS)
soon became very popular, especially for their ease of use and flexibility in structure.
In addition, there were a number of innovative vendors, such as Oracle, who
supplemented the RDBMS with a suite of powerful application development and user
products, providing a total solution.
Introduction IĆ9
IĆ10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Relational Database Concept continued
Database Terminology
Concept Description
Table A table is the basic storage structure of an RDBMS, consisting
of one or more columns and zero or more rows.
Row A row is a combination of column values in a table; for
example, the information about one department in the table
S_DEPT. A row is sometimes called a “record”.
Column A column represents one kind of data in a table; for example,
the department name in the example table S_DEPT. It is
described with a column name and holds data of a specific type
and size.
Field At the intersection of a row and a column, you find a field. The
field can contain data. If there is no data in the field, it is said to
contain a null value.
Primary Key A primary key is the column or set of columns that uniquely
identifies each row in a table; for example a department
number. It must contain a value.
Foreign Key A foreign key is a column or set of columns that refers to a
primary key in the same table or in another table. You create
them to enforce relational database design rules.
Guidelines
D No duplicate values are allowed in a primary key.
D Primary keys generally cannot be changed.
D Foreign keys are based on data values and are purely logical, not physical
pointers.
D A foreign key value must match an existing primary key value or else be NULL.
Introduction IĆ11
IĆ12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Relational Database Concept continued
Object Description
Table Basic unit of storage composed of rows and columns.
View Logically represents subsets of data from one or more tables.
Sequence Generates primary key values.
Index Improves the performance of queries.
Synonym Alternate name for an object.
Program unit Procedure, function, or package of SQL and PL/SQL statements
grouped together.
Table Properties
A single table is composed of rows and columns. The intersection of the rows and
columns are the field values. Each row should be identified by a primary key, which
allows no duplicate rows. The order of the rows is insignificant; by default, the data is
ordered in the order in which it was inserted. Each column is uniquely named.
Column order is insignificant when storing data; specify the column order when the
data is retrieved. Field values cannot be broken into smaller components.
Introduction IĆ13
IĆ14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Relational Database Concept continued
Introduction IĆ15
IĆ16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
System Development Cycle
From concept to production, develop a database by using the system development
cycle. The cycle contains multiple stages of development. This top-down, systematic
approach to database development transforms business information requirements into
an operational database.
Stages of Development
Stage Action
Strategy and Analysis Study and analyze the business requirements. Build
models of the system.
Design Build a database design based on the model.
Build and Document Produce the working, tested software. Write user
documentation, help screens, and operations manual.
Transition Engage in a user acceptance testing phase.
Production Operate the production system.
Introduction IĆ17
Server
É ÉÉ
Introduction IĆ19
DSS Tools
Discoverer/2000
A set of products for end users and decision support analysts that supports rapid
querying and reporting, multi-dimensional analysis of Data Warehousing, and
powerful data mining through a low maintenance meta-layer.
Developer/2000
A set of application development tools that allow developers to create screen-based
applications for users, reporting features, and graphical displays of charts, images,
and drawings.
Designer/2000
A family of tools to aid the analysis, design, and generation of Oracle applications.
For more information, see
Guide to Oracle Products and Services.
Introduction IĆ21
Server
ÉÉÉÉ
SQL and
PL/SQL
Scripts
Features of SQL
D Can be used by a range of users, including those with little or no programming
experience
D Is a non-procedural language
D Reduces the amount of time required for creating and maintaining systems
D Is an English-like language
Features of SQL*Plus
D Accepts ad hoc entry of statements
D Accepts SQL and PL/SQL input from files
D Edits SQL statements with a line editor
D Controls environmental settings
D Formats query results into basic reports
D Interacts with end users
D Accesses remote databases
Introduction IĆ23
IĆ24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL, SQL*Plus, and PL/SQL continued
SQL is the industry standard language for relational databases. The American
National Standards Institute (ANSI) adopted it in 1986. The International Standards
Organization (ISO) has also adopted it. All major RDBMSs support some form of
SQL and most RDBMS vendors intend to comply with the ANSI standard.
SQL Commands
There are many commands available in SQL. The table below describes the
commands covered in this course.
Command Description
SELECT Retrieves data from the database. Most commonly used
command.
INSERT Enters new rows, changes existing rows, and removes unwanted
UPDATE rows from tables in the database, respectively. Collectively
DELETE known as Data Manipulation Language (DML) commands.
CREATE Sets up, changes, and removes data structures from tables.
ALTER Collectively known as Data Definition Language (DDL)
DROP commands.
RENAME
TRUNCATE
COMMIT Manage the changes made by DML statements. Changes to the
ROLLBACK data can be grouped together into logical transactions.
SAVEPOINT
GRANT Gives or removes access rights to both the Oracle database and
REVOKE the structures within it. Collectively known as Data Control
Language (DCL) commands.
Introduction IĆ25
IĆ26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL, SQL*Plus, and PL/SQL continued
Category Purpose
Environment Affects the general behavior of SQL statements for the
session.
Format Formats query results.
File manipulation Saves, loads, and runs script files.
Execution Sends SQL or PL/SQL commands from SQL buffer to
Oracle7 Server.
Edit Modifies SQL commands in the buffer.
Interaction Allows users to create and pass variables to SQL
statements, print variable values, and print messages to
the screen.
Miscellaneous Various commands to connect to the database,
manipulate the SQL*Plus environment, and display
column definitions.
Introduction IĆ27
IĆ28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summit Sporting Goods Demonstration Tables
The course is based on the fictitious Summit Sporting Goods Company. The diagram
on the facing page is an entity relationship (ER) model for Summit Sporting Goods
Company. In an effective business system data is divided into discrete categories or
entities. An ER model is an illustration of various entities in a business and the
relationships between them. The entity relationship model on the facing page
represents the main tables and relationships covered in the course. The business
narrative describes the company’s database needs.
Business Narrative
Introduction IĆ29
IĆ30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summit Sporting Goods Demonstration Tables continued
Business NarrativeĊcontinued
My department just ensures that our customers have the correct billing information
and verifies that their account is in good credit standing. We may also record general
comments about a customer.”
“We do make sure all the items the customers have requested are in stock. For each
item, we track an item number. We may also track the item price, quantity, and
quantity shipped if the information is available. If they are in stock, we want to
process the order and tell our clients what the order number is and how much their
order total is. If the goods are not in stock, the customer tells us whether we should
hold the entire order for a full shipment, or to process the partial order.”
“The accounting department is responsible for maintaining the customer information,
especially for assigning new customer numbers. My department is allowed to update
the customer information only when a customer places an order and their billing or
ship to addresses have changed. No, we are not responsible for collections. That’s all
handled by accounts receivable. I also think that the sales representatives get involved
as their commission depends on customers who pay! For each sales representative, or
employee, we must know the employe number and last name. Occasionally, we need
to know the first name, user name, start date, title, and monthly salary. We may also
track the employee’s commission percent and any comments about the individual.”
“Our order entry personnel are well versed in our product line. We hold frequent
meetings with marketing so they can inform us of new products. This results in
greater customer satisfaction because our order entry operators can answer a lot of
questions. This is possible because we deal with a few select customers and maintain
a specialty product line. For each product, we must know the product number and
name. Occasionally, we must also know the description, suggested price, and unit of
sale. We would also like to track very long descriptions of our products and pictures
of our products, when necessary.”
Introduction IĆ31
IĆ32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Relational database management systems are composed of objects. They are managed
by operations and governed by data integrity constraints.
Oracle Corporation produces products and services to meet your relational database
management system needs. The main product is the Oracle7 Server. The Server
allows you to store and manage information by using SQL and the PL/SQL engine
for procedural constructs.
SQL
Oracle7 Server supports ANSI standard SQL and contains extensions. SQL is the
language used to communicate with the Server to access, manipulate, and control data
access.
SQL*Plus
SQL*Plus is an Oracle tool to execute SQL and PL/SQL statements. It also contains
supporting commands to format queries, set the environment, and edit SQL
commands in the SQL buffer.
PL/SQL
The PL/SQL language extends the SQL language by offering block structured
procedural constructs combined with SQL non-procedural capabilities.
Introduction IĆ33
IĆ34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
1
Selecting Rows
1Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives
In order to extract data from the database you need to use the Structured Query
Language (SQL) SELECT command. You may need to restrict the columns that
are displayed. This lesson explains all of the commands you will use to perform
these actions.
You will want to create SELECT statements that can be used time and time
again. In this lesson you will also see how to save your statements for later use.
At the end of this lesson, you should be able to
D Write a SELECT statement to query the database.
D Perform arithmetic calculations using SQL arithmetic operators.
D Handle null values.
D Specify alternative column headings using aliases.
D Concatenate columns.
D Edit SQL statements in the SQL*Plus buffer and create command files.
Syntax
Example
List all columns and all rows from the S_DEPT table.
SQL> SELECT *
2 FROM s_dept;
ID NAME REGION_ID
------- --------------- ---------
10 Finance 1
31 Sales 1
32 Sales 2
33 Sales 3
34 Sales 4
35 Sales 5
41 Operations 1
42 Operations 2
43 Operations 3
44 Operations 4
45 Operations 5
50 Administration 1
12 rows selected.
Example
Display all department numbers, employee last names, and manager numbers in the
S_EMP table.
25 rows selected.
Specify the columns you want to see, in the order in which you want to see them, in
the SELECT clause. Do not forget to use the comma as a column name separator.
Arithmetic Operators
These are the arithmetic operators available in SQL. You may use arithmetic
operators in any clause of a SQL statement except the FROM clause.
Operators Description
+ Add
- Subtract
* Multiply
/ Divide
Example
Use the multiplication operator to display annual salary figures and their commission
percentage for all employees.
Notice that the resultant calculated column SALARY*12 is not a new column in the
originating table, but is for display only.
Operator Precedence
If an arithmetic expression contains more than one operator, multiplication and
division are evaluated first. If operators within an expression are of the same priority,
then evaluation is from left to right.
Example
Display the last name, salary, and annual compensation of employees. Calculate the
annual compensation as 12 multiplied by the monthly salary, plus a one-time bonus of
$100.
Note: Use parentheses to reinforce the standard order of precedence and to improve
clarity. For example, the expression above can be written as (12 * salary) +
100 with no change in the result.
Override the rules of precedence with parentheses to specify the order in which
operators are executed.
Example
Display the last name, salary, and annual compensation of employees. Calculate the
annual compensation as monthly salary plus a monthly bonus of $100, multiplied by
12.
Example
Display the last name, salary, and annual compensation of employees. Calculate the
annual compensation as monthly salary plus a monthly bonus of $100, multiplied by
12. Name the column ANNUAL_SALARY.
Note: You can include the AS keyword before the alias name to comply with ANSI
SQL 92 standards.
Example
Display the full names of the employees with the heading Employees.
Employees
--------------------------------------------------
CarmenVelasquez
LaDorisNgao
MidoriNagayama
MarkQuick-To-See
AudryRopeburn
MollyUrguhart
...
The AS keyword before the alias name makes the SELECT clause easier to read.
Example
Display the full names of the employees and their titles with the heading Employees.
Be sure to add punctuation.
Employees
---------------------------------
Carmen Velasquez, President
LaDoris Ngao, VP, Operations
Midori Nagayama, VP, Sales
Mark Quick-To-See, VP, Finance
Audry Ropeburn, VP, Administration
Molly Urguhart, Warehouse Manager
...
Example
Display the last name, salary, title, and calculated commission.
NVL Function
In order to convert a null value to an actual value, use the NVL function.
Syntax
Example
To calculate values for all employees from the previous example, use the NVL
function to convert null values to zero.
NAME
------------------
Finance
Sales
Sales
Sales
Sales
Sales
Operations
. . .
12 rows selected
NAME
-----------------------
Administration
Finance
Operations
Sales
Example
Display all the different combinations of job titles and department numbers.
DEPT_ID TITLE
------- ---------------------
10 VP, Finance
31 Sales Representative
31 VP, Sales
32 Sales Representative
33 Sales Representative
34 Sales Representative
34 Stock Clerk
35 Sales Representative
41 Stock Clerk
41 VP, Operations
41 Warehouse Manager
42 Stock Clerk
42 Warehouse Manager
43 Stock Clerk
43 Warehouse Manager
44 Stock Clerk
44 Warehouse Manager
45 Stock Clerk
45 Warehouse Manager
50 President
50 VP, Administration
21 rows selected.
SQL>
DESC[RIBE] tablename
Example
Display information about the structure of the S_DEPT table.
Datatype Description
NUMBER (p,s) Number value having a maximum number of digits p, and
the number of digits to the right of the decimal point s.
VARCHAR2(s) Variable length character value of maximum size s.
DATE Date and time value between January 1, 4712 B.C. and
December 31, 4712 A.D.
CHAR(s) Fixed length character value of size s.
Guidelines
D If you press [RETURN] before completing a command, SQL*Plus will prompt
you with a line number.
D You terminate the SQL buffer by either entering one of the terminator characters
(semicolon or slash), or pressing [RETURN] twice. You will now see the SQL
prompt.
Command Description
A[PPEND] text Adds text to the end of the current line.
C[HANGE] / old / new / Changes old text to new in the current line.
C[HANGE] / text / Deletes text from the current line.
CL[EAR] BUFF[ER] Deletes all lines from the SQL buffer.
DEL Deletes current line.
DEL n Deletes one line (specified by n)
DEL m n Deletes a range of lines (m to n)
I[NPUT] Inserts an indefinite number of lines.
I[NPUT] text Inserts a line consisting of text.
L[IST] Lists all lines in the SQL buffer.
L[IST] n Lists one line (specified by n).
L[IST] m n Lists a range of lines (m to n).
R[UN] Displays and runs the current SQL command in the
buffer.
n Specifies the line to make the current line.
n text Replaces line n with text.
0 text Inserts a line before line 1.
File Commands
Command Description
SAV[E] filename [.ext] Saves current contents of SQL buffer to a file. Use
[REP[LACE]|APP[END]] APPEND to add to an existing file; use REPLACE to
overwrite an existing file. The default file extension is
.sql.
GET filename [.ext] Writes the contents of a previously saved file to the
SQL buffer. The default extension for the filename is
.sql.
STA[RT] filename [.ext] Runs a previously saved command file.
@ filename Runs a previously saved command file (same as
START).
EDIT Invokes the editor and saves the buffer contents to a
file named afiedt.buf.
ED[IT] [filename[.ext]] Invokes editor to edit contents of a saved file.
SPO[OL] [filename[.ext]| Stores query results in a file, OFF closes the spool
OFF|OUT] file. OUT closes the spool file and sends the file
results to the system printer.
EXIT Leaves SQL*Plus.
Note: You can change the text editor invoked by changing the value of the
SQL*Plus variable _EDITOR by using the DEFINE command.
You can enter only one SQL*Plus command per SQL prompt. SQL*Plus commands
are not stored in the buffer. To continue a SQL*Plus command on the next line, end
the current line with a hyphen (-).
COLUMN Command
Control the display of a column in a report by using the COLUMN command. For
example, you can change the heading, width, and format.
Syntax
Option Description
CLE[AR] Clears any column formats.
FOR[MAT] format Changes the display of the column data.
HEA[DING] text Sets the column heading. A vertical line (|) will force a
line feed in the heading if you do not use justification.
JUS[TIFY] {align} Justifies the column heading (not the data) to be left,
center, or right.
NOPRI[NT] Hides the column.
NUL[L] text Specifies text to be displayed for null values.
PRI[NT] Shows the column.
TRU[NCATED] Truncates the string at the end of the first line of display.
WRA[PPED] Wraps the end of the string to the next line.
WOR[D_WRAPPED] Same as WRAPPED, but ensures that words do not split.
Format elements used in the FORMAT option are discussed on the next page.
If you have a lengthy command, you can continue it on the next line by ending the
current line with a hyphen (-).
Command Description
COL[UMN] column Displays the current settings for the specified
column.
COL[UMN] Displays the current settings for all columns.
COL[UMN] column CLE[AR] Clears the settings for the specified column.
CLE[AR] COL[UMN] Clears the settings for all columns.
The Oracle7 Server displays a string of pound signs (#) in place of a whole number
whose digits exceed the number of digits provided in the format model. It will also
display pound signs in place of a value whose format model is alphanumeric, but
whose actual value is numeric.
SQL*Plus
SQL*Plus is an execution environment you can use to send SQL commands to the
database server and to edit and to save SQL commands. Commands may be executed
from the SQL prompt or from a script file.
Practice Contents
D Selecting all data from different tables.
D Describing the structure of tables.
D Performing arithmetic calculations and specifying different column names.
D Editing commands in the buffer.
Please take this practice slowly and precisely. You can experiment with saving and
running command files. If you have any questions at any time, please attract the
instructor’s attention.
Paper-Based Questions
For questions 1–2 circle either True or False.
ID NAME REGION_ID
--------- ------------------------- ---------
10 Finance 3
31 Sales 1
32 Sales 2
33 Sales 3
34 Sales 4
35 Sales 5
41 Operations 1
42 Operations 2
43 Operations 3
44 Operations 4
45 Operations 5
50 Administration 1
12 rows selected.
4. Show the structure of the S_CUSTOMER table. Using this table, perform the
following actions.
a. Retrieve all information from the S_CUSTOMER table.
b. Display the name and phone number for each customer.
4.—Continued
c. Display the phone number and name for each customer, with phone number
appearing first.
PHONE NAME
-------------------- -------------------------
55-2066101 Unisports
81-20101 Simms Atheletics
91-10351 Delhi Sports
1-206-104-0103 Womansport
852-3692888 Kam’s Sporting Goods
33-2257201 Sportique
234-6036201 Sweet Rock Sports
49-527454 Muench Sports
809-352689 Beisbol Si!
52-404562 Futbol Sonora
42-111292 Kuhn’s Sports
20-1209211 Hamada Sport
1-415-555-6281 Big John’s Sports Emporium
1-716-555-7171 Ojibway Retail
7-3892456 Sporta Russia
15 rows selected.
While retrieving data from the database, you may need to restrict the rows of
data that are displayed or specify the order in which the rows are displayed.
This lesson explains the commands you will use to perform these actions.
At the end of this lesson you should be able to
D Sort row output using the ORDER BY clause.
D Enter search criteria using the WHERE clause.
Syntax
SELECT expr
FROM table
[ORDER BY {column,expr} [ASC|DESC]];
Example
Query the employee table for employee last name, department number, and the hire
date for all employees. Sort the results by employee last name.
Example
Query the employee table for employee last name, department number, and the hire
date for all employees. Sort the results by the most recently hired employee.
Ordering by Position
Another method for sorting query results is to sort by position. This is especially
useful when sorting by a long expression. Rather than typing the expression again,
you can specify its position in the SELECT list.
Example
Display the last name, department number, and salary of all employees. Order the
result by the department number, then in descending order by salary.
Syntax
SELECT expr
FROM table
[WHERE condition(s)]
[ORDER BY expr];
Comparison Operators
Comparison operators are divided into two categories: logical and SQL. They are
used in the WHERE clause to compare one expression to another using the following
format.
Syntax
...WHERE dept_id = 42
Example
Write a query to show the first and last names, and title for the employee named
“Magee.”
All character strings are case sensitive. Therefore, change the last name to be initial
capitals in order to acquire a match.
Comparison Operators
Logical operators test the following conditions:
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
SQL Operators
There are four SQL operators that operate with all datatypes:
Operator Meaning
BETWEEN...AND... Between two values (inclusive)
IN(list) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
Logical Operators
Operator Meaning
AND If both component conditions return TRUE, then the
result is TRUE.
OR If either component condition returns TRUE, then the
result is TRUE.
NOT Returns the opposite condition.
If you want to compare a known value to a null value, use either IS or IS NOT NULL
comparison operators. If you compare null values using the other operators, the result
is always FALSE.
Example
Display the first name, last name, and start date of employees whose start date is
between May 9, 1991 and June 17, 1991, inclusive.
Values specified with the BETWEEN operator are inclusive. You must specify the
lower limit first.
The IN Operator
To test for values in a specified list, use the IN operator.
Example
Display the department number, name, and region number of departments in regions
1 or 3.
If characters or dates are used in the list, they must be enclosed in single quotation
marks (‘ ’).
Symbol Description
% Represents any sequence of zero or more characters.
_ Represents any single character.
Example
Display all employee last names beginning with “M.”
LAST_NAME
------------
Menchu
Magee
Maduro
Markarian
Example
Display all employee last names that do not contain an “a” within the name.
The LIKE operator can be used as a shortcut for some BETWEEN comparisons.
Example
Display the last name and start date for employees who started with the company in
1991.
Example
Display the last names of employees whose last name has an “a” as the second letter.
Example
Display the names of companies whose name contains “X_Y.”
IS NULL Operator
The IS NULL operator tests for values that are null. A null value means the value is
unavailable, unassigned, unknown, or inapplicable. Therefore, you cannot test with
“=” because a null value cannot be equal or unequal to any value.
Example
Display the customer number, name, and credit rating of all customers who do not
have a sales representative.
ID NAME CREDIT_RA
------- -------------------- ---------
207 Sweet Rock Sports GOOD
Example
Display all employee last names, titles, and commission percentages who make a
commission.
Example 1
Display the last name, salary, department number, and title for all stock clerks in
department 41.
Example 2
Display the last name, salary, department number, and title for all employees who are
either stock clerks or who are in department 41.
Rules of Precedence
Note: When using a negating expression, comparison operators still evaluate first.
Override precedence rules by placing part of an expression in parentheses; the Oracle
Server evaluates expressions in parentheses first.
Whenever you are in doubt about which of two operations will be performed first
when an expression is evaluated, use parentheses to clarify your statements.
Example 1
Display the last name, salary, and department number for those employees in
department 44 who earn 1000 or more, as well as all employees in department 42.
Example 2
Display the last name, salary, and department number for those employees in
department 44 or 42 who earn 1000 or more.
Syntax
Practice Contents
D Selecting data and changing the order of rows displayed.
D Using the WHERE clause to restrict rows, with a combination of logical and
SQL operators.
D Using column aliases.
PaperĆBased Questions
For questions 1–3, circle either True or False.
SQL> select *
2 from s_emp
3 where salary*12 = 9600;
4. There are four coding errors in this statement. Can you identify them?
d. Retrieve p2q5 into the SQL buffer. Order the query results in descending
order by customer number. Run your query.
6. Show the structure of the S_EMP table.
a. Display the user name for employee 23.
b. Display the first name, last name, and department number of the employees in
departments 10 and 50 in alphabetical order of last name. Merge the first
name and last name together, and title the column Employees.
Employees DEPT_ID
----------------------------------- ---------
Mark Quick-To-See 10
Audry Ropeburn 50
Carmen Velasquez 50
Functions make the basic query block more powerful and are used to
manipulate data values. This is the first of two lessons that explore functions.
You will focus on single row character, number, and date functions, as well as
those functions that convert data from one type to another, for example,
character data to numeric.
At the end of this lesson, you should be able to
D Explain the various types of functions available in SQL.
D Identify the basic concepts of using functions.
D Use a variety of character, number, and date functions in SELECT statements.
D Explain the conversion functions and how they might be used.
Syntax
Function Purpose
LOWER(column|expression) Converts alpha character values to lowercase.
UPPER(column|expression) Converts alpha character values to uppercase.
INITCAP(column|expression) Converts alpha character values to uppercase
for the first letter of each word, all other
letters in lowercase.
CONCAT(column1|expression1, Concatenates the first character value to the
column2|expression2) second character value. Equivalent to
concatenation operator (||).
SUBSTR(column|expression,m[,n]) Returns specified characters from character
value starting at character position m, n
characters long. If m is negative, the count
starts from the end of the character value.
LENGTH(column|expression) Returns the number of characters in value.
NVL(column|expression1,column|ex Converts the the first value if null to the
pression2) second value.
Example
Display the first and last name in lowercase, userid in initial capitalization, and title in
uppercase for all vice presidents.
VP USERID TITLE
--------------------- -------- -------------------
ladoris ngao Lngao VP, OPERATIONS
midori nagayama Mnagayam VP, SALES
mark quick-to-see Mquickto VP, FINANCE
audry ropeburn Aropebur VP, ADMINISTRATION
Example
Display the first name and last name of all employees with the last name of Patel.
FIRST_NAME LAST_NAME
-------------------- --------------------
Vikram Patel
Radha Patel
Note: The name is displayed as it was stored in the database. To display the name in
uppercase, the UPPER function must be used in the SELECT clause as well.
Example
Display the name and country of all customers with a good credit rating. Concatenate
name and country.
CUSTOMER
-------------------------------------------------
Delhi SportsIndia
Sweet Rock SportsNigeria
Example
Display the product name and length of name for all products where the first three
characters are Ace.
NAME LENGTH(NAME)
-------------------- ------------
Ace Ski Boot 12
Ace Ski Pole 12
Function Purpose
ROUND(column|expression,n) Rounds the column, expression, or value to n
decimal places. If n is omitted, no decimal
places. If n is negative, numbers to left of the
decimal point are rounded.
TRUNC(column|expression,n) Truncates the column or value to n decimal
places, or if n is omitted, no decimal places. If n
is negative, numbers left of the decimal point
are truncated to zero.
MOD(m,n) Returns the remainder of m divided by n.
The TRUNC and ROUND functions work with similar arguments. If the second
argument is 0 or is missing, then the value is truncated or rounded to zero decimal
places. If the second argument is 2, then the value is truncated or rounded to two
decimal places, or to the hundredths. Conversely, if the second argument is -2, then
the value is truncated or rounded to two decimal places to the left, or to the hundreds.
Note: ROUND and TRUNC may also be used with date functions. You will see
examples later in this lesson.
Example
Display the value 45.923 rounded to the hundredth, no, and ten decimal places.
Example
Display the value 45.923 truncated to the hundredth, no, and ten decimal places.
Example
Calculate the remainder of the ratio of salary to commission for all employees whose
salary is more than 1400.
LAST_NAME MOD(SALARY,COMMISSION_PCT)
------------ --------------------------
Velasquez
Ngao
Quick-To-See
Ropeburn
Giljum 2.5
Sedeghi 5
Nguyen 10
Dumas 15
8 rows selected.
SYSDATE
SYSDATE is a date function that returns the current date and time. You can use
SYSDATE just as you would use any other column name. For example, you can
display the current date by selecting SYSDATE from a table. It is customary to select
SYSDATE from a dummy table called DUAL.
DUAL
The DUAL table is owned by the user SYS and may be accessed by all users. It
contains one column, DUMMY, and one row with the value “X.” The DUAL table is
useful when you want to return a value once only, for instance, the value of a
constant, pseudo-column, or expression that is not derived from a table with user
data.
Example
Display the current date using the DUAL table.
Example
For employees in department 43, display the last name and number of weeks
employed.
LAST_NAME WEEKS
------------ ----------
Biri 297.226498
Markarian 238.083641
Newman 230.083641
Note: SYSDATE is a SQL function that returns the current date and time. Your
results may differ from the examples.
Date functions operate on Oracle dates. All date functions return a value of DATE
datatype except MONTHS_BETWEEN, which returns a numeric value.
Function Purpose
MONTHS_BETWEEN(date1, date2) Finds the number of months between
date1 and date2. The result can be
positive or negative. If date1 is later than
date2, the result is positive; if date1 is
earlier than date2, the result is negative.
The non-integer part of the result
represents a portion of the month.
ADD_MONTHS(date,n) Adds n number of calender months to
date. n must be an integer and can be
negative
NEXT_DAY(date,‘char’) Finds the date of the next specified day
of the week (‘char’) following date.
char may be a number representing a
day or a character string.
LAST_DAY(date) Finds the date of the last day of the
month that contains date.
ROUND(date[,‘fmt’]) Finds the date of first day of the month
contained in date when no format model
fmt is specified. If fmt = YEAR, finds
first day of year containing date. This is
useful when comparing dates that may
have different times.
TRUNC(date[,‘fmt’]) Returns date with the time set to
midnight if no format model fmt is
specified. This function is useful when
you want to remove the time portion of
the date.
Note: This list is a subset of the available date functions. The format models are
covered later in this chapter. Examples of format models are month or year.
Example
For all employees employed less than 48 months, display the employee number, start
date, number of months employed, and the 6 month review date.
Example
For inventory items that have been restocked, display in chronological order the
product number, first Friday after the restock date, and the last day of the month when
it was restocked.
The ROUND and TRUNC functions can be used for number and date values. When
using these functions with dates, they round or truncate to the specified format model.
Therefore, you can round dates to the nearest year or month.
Example
Compare the start dates for all employees who started in 1991. Display the employee
number, start date, and month started using both the ROUND and TRUNC functions.
11 rows selected.
Function Purpose
TO_CHAR(number|date,[‘fmt’]) Converts a number or date value to a
VARCHAR2 character string with
format model fmt.
TO_NUMBER(char) Converts a character string containing
digits to a number.
TO_DATE(char,[‘fmt’]) Converts a character string representing
a date to a date value according to the
fmt specified. If fmt is omitted, format is
DD-MON-YY.
Note: This list is a subset of the available conversion functions.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Conversion Functions.”
Guidelines
D The format model must be enclosed in single quotation marks and is
case-sensitive.
D The format model can include any valid date format element. Be sure to separate
the date value from the format model by a comma.
D The names of days and months in the output are automatically padded with
blanks.
D To remove padded blanks or to suppress leading zeros, use the fill mode fm
element.
D You can resize the display width of the resulting character field with the
SQL*Plus COLUMN command.
D The resultant column width is 80 characters by default.
Example
Display the order number and date ordered for all orders taken by sales representative
11. Format the date to display the date as 08/92.
ID ORDERED
------- -------------------
100 08/92
105 09/92
109 09/92
110 09/92
111 09/92
Element Description
SCC or CC Century; S prefixes BC date with -.
Years in dates YYYY or SYYYY Year; S prefixes BC date with -.
YYY or YY or Y Last 3, 2, or 1 digit(s) of year.
Y,YYY Year with comma in this position.
IYYY, IYY, IY, I 4, 3, 2, or 1 digit year based on the ISO
standard.
SYEAR or YEAR Year spelled out; S prefixes BC date with -.
BC or AD BC/AD indicator.
B.C. or A.D. BC/AD indicator with periods.
Q Quarter of year.
MM Month, 2-digit value.
MONTH Name of month padded with blanks to
length of 9 characters.
MON Name of month, 3-letter abbreviation.
RM Roman numeral month.
WW or W Week of year or month.
DDD or DD or D Day of year, month, or week.
DAY Name of day padded with blanks to length
of 9 characters.
DY Name of day; 3-letter abbreviation.
J Julian day; the number of days since 31
December 4713 BC.
Time Formats
Use the formats listed in the following tables to display time information and literals,
and to change numerals to spelled numbers.
Element Description
AM or PM Meridian indicator.
A.M. or P.M. Meridian indicator with periods.
HH or HH12 or HH24 Hour of day or hour (1-12) or hour (0-23)
MI Minute (0-59).
SS Second (0-59).
SSSSS Seconds past midnight (0-86399).
Other Formats
Element Description
/ . , Punctuation is reproduced in the result.
“ of the ” Quoted string is reproduced in the result.
Suffix Description
TH Ordinal number (for example, DDTH for 4TH).
SP Spelled-out number (for example, DDSP for FOUR).
SPTH or THSP Spelled-out ordinal numbers (for example, DDSPTH
for FOURTH).
Example
Display the names and hire dates for all employees hired in 1991. The hire date
should look like 7 of February 1991.
LAST_NAME HIREDATE
------------ --------------------
Nagayama 17 of June 1991
Urguhart 18 of January 1991
Havel 27 of February 1991
...
Example
Modify the above example to display the dates in a format that looks like Seventh of
February 1991 08:00:00 AM.
LAST_NAME HIREDATE
------------ ------------------------------------
Nagayama Seventeenth of June 1991 12:00:00 AM
Urguhart Eighteenth of January 1991 12:00:00 AM
Havel Twenty-Seventh of February 1991 12:00:00
...
Example
Display a message indicating that the order, represented by its number, was filled for
all orders shipped on September 21, 1992. Be sure to include the total for the order.
NOTE
------------------------------------------------------
Order 107 was filled for a total of $142,171
Order 110 was filled for a total of $1,539
Order 111 was filled for a total of $2,770
Guidelines
D The Oracle7 Server displays a string of pound signs (#) in place of a whole
number whose digits exceed the number of digits provided in the format model.
D The Oracle7 Server rounds the stored decimal value to the number of decimal
spaces provided in the format model.
Example
Show all orders placed on September 7, 1992. Convert the date string you see here to
the date format.
ID TOTAL DATE_ORDE
------ ---------- ---------
106 15634 07-SEP-92
107 142171 07-SEP-92
108 149570 07-SEP-92
Step 2 = Result 2
Step 3 = Result 3
Nesting Functions
Single row functions can be nested to any depth. Nested functions are evaluated from
the innermost level to the outermost level. Some examples follow to show you the
flexibility of these functions.
Example
Display the last name in upper case and part of the department name of all vice
presidents as a string under the title Vice Presidents.
Vice Presidents
----------------------------------------------------
NGAO, Operations
NAGAYAMA, Sales
QUICK-TO-SEE, Finance
ROPEBURN, Administration
Example
Display the head of the company, who has no manager. Display that there is no
manager number for that name.
LAST_NAME NVL(TO_CHAR(MANAGER_ID),’NOMANAGER’)
------------ ----------------------------------------
Velasquez No Manager
Notice that the entire expression becomes the column heading since no column alias
was given.
Example
Display the date of the next Friday that is six months from the order date. The
resultant date should look like Friday, March 12th, 1993.
Practice Contents
D Creating queries that require the use of numeric, character, and date functions
D Using concatenation with functions
D Writing case-insensitive queries to test the usefulness of character functions if you
are unsure exactly how character date is stored
D Performing calculations of years and months of service for an employee
D Determining the review date for an employee
Remember that for nested functions, the results are evaluated from the innermost
function to the outermost function.
4. Display the employee number, last name, and salary increased by 15% and
expressed as a whole number.
25 rows selected.
5. Display the employee last name and title in parentheses for all employees. The
report should look like the output below.
EMPLOYEE
----------------------------------------------------
Biri(Warehouse Manager)
Catchpole(Warehouse Manager)
Chang(Stock Clerk)
Dancs(Stock Clerk)
Dumas(Sales Representative)
Giljum(Sales Representative)
Havel(Warehouse Manager)
Maduro(Stock Clerk)
Magee(Sales Representative)
Markarian(Stock Clerk)
Menchu(Warehouse Manager)
Nagayama(Vp, Sales)
Newman(Stock Clerk)
Ngao(Vp, Operations)
Nguyen(Sales Representative)
Nozaki(Stock Clerk)
Patel(Stock Clerk)
Patel(Stock Clerk)
Quick-To-See(Vp, Finance)
Ropeburn(Vp, Administration)
Schwartz(Stock Clerk)
Sedeghi(Sales Representative)
Smith(Stock Clerk)
Urguhart(Warehouse Manager)
Velasquez(President)
25 rows selected.
6. Display each employee’s last name, hire date, and salary review date, which is the
first Monday after six months of service. Format the dates to appear in the format
similar to Eighth of May 1992.
25 rows selected.
7. Display the product name for products that have “ski” in the name.
NAME
--------------------
Ace Ski Boot
Pro Ski Boot
Bunny Ski Pole
Ace Ski Pole
Pro Ski Pole
LAST_NAME MONTHS_WORKED
------------ -------------
Catchpole 46
Maduro 46
Nguyen 47
Giljum 47
Dumas 50
Patel 52
Newman 53
Nagayama 54
Markarian 55
Schwartz 55
Dancs 57
Havel 58
Sedeghi 58
Nozaki 58
Urguhart 59
Chang 61
Patel 62
Menchu 67
Magee 67
Quick-To-See 68
Biri 68
Ngao 69
Smith 69
Ropeburn 69
Velasquez 69
25 rows selected.
Note: Your MONTHS_WORKED may differ from the solution because your
SYSDATE may return a different value.
9. Display the last name for all employees and the day of the week they started.
Order the results by the day of the week starting with Monday.
25 rows selected.
10. Write a query that produces the following for each employee:
<employee name> earns <salary> monthly but wants<3 times salary>.
For example: ALLEN earns $1,100 monthly but wants $3,300.
Dream Salaries
---------------------------------------------------
VELASQUEZ earns $2,500 monthly but wants $7,500.
NGAO earns $1,450 monthly but wants $4,350.
NAGAYAMA earns $1,400 monthly but wants $4,200.
QUICK-TO-SEE earns $1,450 monthly but wants $4,350.
ROPEBURN earns $1,550 monthly but wants $4,650.
URGUHART earns $1,200 monthly but wants $3,600.
MENCHU earns $1,250 monthly but wants $3,750.
BIRI earns $1,100 monthly but wants $3,300.
CATCHPOLE earns $1,300 monthly but wants $3,900.
HAVEL earns $1,307 monthly but wants $3,921.
MAGEE earns $1,400 monthly but wants $4,200.
GILJUM earns $1,490 monthly but wants $4,470.
SEDEGHI earns $1,515 monthly but wants $4,545.
NGUYEN earns $1,525 monthly but wants $4,575.
DUMAS earns $1,450 monthly but wants $4,350.
MADURO earns $1,400 monthly but wants $4,200.
NOZAKI earns $1,200 monthly but wants $3,600.
MARKARIAN earns $850 monthly but wants $2,550.
PATEL earns $795 monthly but wants $2,385.
SMITH earns $1,000 monthly but wants $3,000.
PATEL earns $795 monthly but wants $2,385.
NEWMAN earns $750 monthly but wants $2,250.
CHANG earns $800 monthly but wants $2,400.
DANCS earns $860 monthly but wants $2,580.
SCHWARTZ earns $1,100 monthly but wants $3,300.
25 rows selected.
This lesson will cover how to obtain data from more than one table, using the
many different methods available.
At the end of this lesson, you should be able to
D Write SELECT statements to access data from more than one table using equality
and non-equality joins.
D View data that would not normally meet a join condition by using outer joins.
D Join a table to itself.
Syntax
where: table.column denotes the table and column from which data is
retrieved.
table1.column1 = is the condition that joins (or relates)
table2.column2 the tables together.
Guidelines
D When writing a SELECT statement that joins tables, precede the column name
with the table name for clarity and to enhance database access.
D If the same column name appears in more than one table, then the column name
must be prefixed with the table name.
D To join tables together, you need a minimum of the number of join conditions
summarized as the number of tables minus one. Therefore, to join four tables, a
minimum of three joins would be required. This rule may not apply if your table
has a concatenated primary key, in which case more than one column is required
to uniquely identify each row.
For more information, see
Oracle7 Server SQL Language Reference Manual, “SELECT.”
ÉÉÉÉ
Equijoin
In order to determine the name of an employee’s department, you compare the value
in the DEPT_ID column in the S_EMP table with the ID values in the S_DEPT table.
The relationship between the S_EMP and S_DEPT tables is an equijoin, that is
values in the DEPT_ID column on both tables must be equal. Frequently, these
columns are primary and foreign key complements.
Example
Join together the employee and department tables to display the employee name,
department number, and department name.
25 rows selected.
Every employee now has their respective department name displayed. The rows of
the S_EMP table are combined with the rows of the S_DEPT table, and rows are only
returned if the values of S_EMP.DEPT_ID and S_DEPT.ID are equal.
Example
Display the department number, region number, and region name for all departments.
12 rows selected.
ÉÉ ÉÉ
Example
Display employee Menchu’s last name, department number, and department name.
Display the last name, region name, and commission percent of all employees who
earn a commission.
Example
Display the customer name, region number, and region name for all customers.
Provide column aliases, and use a table alias to shorten the table references.
Guidelines
D Table aliases can be up to 30 characters in length, but the shorter they are the
better.
D If a table alias is used for a particular table name in the FROM clause, then that
table alias must be substituted for the table name throughout the SELECT
statement.
D Table aliases should be meaningful.
D The table alias is only valid for the current SELECT statement.
Example
Create a non-equijoin to evaluate an employee’s salary grade. The salary must be
between any pair of the low and high salary ranges.
14 rows selected.
Other operators such as <= and >= could be used, however BETWEEN is the
simplest. Remember to specify the low value first and the high value last when using
BETWEEN. Table aliases have been specified for performance reasons, not because
of possible ambiguity.
Outer Join
The missing row(s) can be returned if an outer join operator is used in the join
condition. The operator is a plus sign enclosed in parentheses (+), and is placed on
the “side” of the join that is deficient in information. The operator has the effect of
creating one or more NULL rows, to which one or more rows from the non-deficient
table can be joined.
Syntax
or
where: table1.column = is the condition that joins (or relates) the tables
table2.column together.
(+) is the outer join symbol; it can be placed on
either side of the WHERE clause condition, but
not on both sides. Place the outer join symbol
following the name of the table without the
matching rows.
ÉÉ É
Example
Display the sales representative name and employee number and the customer name
for all customers. Include the customer name even if the customer has not been
assigned a sales representative.
LAST_NAME ID NAME
–––––––– ––– ––––––––––––––––––––––––––––––––––––
Magee 11 Womansport
Magee 11 Beisbol Si!
Magee 11 Ojibway Retail
Magee 11 Big John’s Sports Emporium
Giljum 12 Unisports
Giljum 12 Futbol Sonora
Sedeghi 13 Hamada Sport
Nguyen 14 Simms Atheletics
Nguyen 14 Delhi Sports
Dumas 15 Kam’s Sporting Goods
Dumas 15 Sportique
Dumas 15 Muench Sports
Dumas 15 Sporta Russia
Dumas 15 Kuhn’s Sports
Sweet Rock Sports
15 rows selected.
ÉÉ É
Self Join
In order to simulate two tables in the FROM clause, the example contains an alias for
the same table, S_EMP. This is an example of good naming conventions.
In this example, the WHERE clause contains the join that means “where a worker’s
manager number matches the employee number for the manager.”
Example
Display the names of employees and their respective managers.
Syntax
Types of Joins
D Equijoin
D Non-equijoin
D Outer join
D Self join
Cartesian Products
Omission of the WHERE clause will result in a Cartesian product, in which all
combinations of rows will be displayed.
Table Aliases
D Table aliases speed up database access. You tell the Oracle Server exactly where
to go to find columns.
D Table aliases can help to keep SQL code smaller, therefore conserving memory.
Practice Contents
D Joining tables using an equijoin
D Performing outer and self joins
D Adding additional conditions
25 rows selected.
2. Write a query to display the last name, department name, and region name of all
employees who earn a commission.
LAST_NAME NAME
------------ ----------------------
Smith Operations
4. Display the product name, product number, and quantity ordered of all items in
order number 101. Label the quantity column ORDERED.
NAME ID ORDERED
--------------------------------- ----- -------
Grand Prix Bicycle Tires 30421 15
Pro Curling Bar 40422 30
Prostar 10 Pound Weight 41010 20
Prostar 100 Pound Weight 41100 35
Major League Baseball 50169 40
Griffey Glove 50417 27
Cabrera Bat 50530 50
7 rows selected.
5. Display the customer number and the last name of their sales representative.
Order the list by last name.
ID LAST_NAME
----- ---------------
205 Dumas
206 Dumas
208 Dumas
211 Dumas
215 Dumas
201 Giljum
204 Magee
214 Magee
209 Magee
213 Magee
202 Nguyen
203 Nguyen
212 Sedeghi
13 rows selected.
18 rows selected.
7. Display all employees by last name name and employee number along with their
manager’s last name and manager number.
24 rows selected.
8. Modify the solution to exercise 7 to also display Velasquez, who has no manager.
25 rows selected.
9. Display all customers and the products and quantities they ordered for those
customers whose order totaled more than 100,000.
26 rows selected.
Group Functions
5Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives
This lesson further addresses functions. You will focus on obtaining summary
information, such as averages, for groups of rows. You will discuss how to group
rows in a table into smaller sets, and how to specify search criteria for groups of
rows.
At the end of this lesson, you should be able to
D Identify the available group functions.
D Explain the use of group functions.
D Use the GROUP BY clause to force statistics to be displayed for different groups.
D Use the HAVING clause to include or exclude grouped rows.
Group Functions
D AVG
D COUNT
D MAX
D MIN
D STDDEV
D SUM
D VARIANCE
Syntax
Function Description
AVG(DISTINCT|ALL|n) Average value of n, ignoring null values.
COUNT(DISTINCT|ALL|expr|*) Number of rows, where expr evaluates to
something other than null. Count all selected
rows using *, including duplicates and rows
with nulls.
MAX(DISTINCT|ALL|expr) Maximum value of expr.
MIN(DISTINCT|ALL|expr) Minimum value of expr.
STDDEV(DISTINCT|ALL|n) Standard deviation of n, ignoring null values.
SUM(DISTINCT|ALL|n) Sum values of n, ignoring null values.
VARIANCE(DISTINCT|ALL|n) Variance of n, ignoring null values.
Guidelines
D DISTINCT makes the function consider only non-duplicate values; ALL makes it
consider every value including duplicates. The default is ALL and therefore does
not need to be specified.
D The datatypes for the arguments may be CHAR, VARCHAR2, NUMBER, or
DATE where expr is listed.
D All group functions except COUNT(*) ignore null values. To substitute a value
for null values, use the NVL function.
Example
Display the average, highest, lowest, and sum of the monthly salaries for all sales
representatives.
Note: You can use AVG and SUM functions against columns that store numeric
data.
Example
Display the employee last name that is the first and the employee last name that is the
last in an alphabetized list of all employees.
MIN(LAST_NAME) MAX(LAST_NAME)
------------------------- -------------------------
Biri Velasquez
Note: You can use MAX and MIN functions for any datatype.
COUNT Function
The COUNT function has two formats: COUNT(*) and COUNT(expr). COUNT(*)
returns the number of rows in a table, including duplicate rows and rows containing
null values.
Example
Display the number of employees in department 31.
COUNT(*)
----------
2
Example
Display the number of employees in department 31 who can earn a commission.
COUNT(COMMISSION_PCT)
---------------------
1
Syntax
Guidelines
D If you include a group function in a SELECT clause, you cannot select individual
results as well unless the individual column appears in the GROUP BY clause.
You will receive an error message if you fail to include the column list.
D Using a WHERE clause, you can pre-exclude rows before dividing them into
groups.
D You must include the columns in the GROUP BY clause.
D You cannot use the positional notation or column alias in the GROUP BY clause.
D By default, rows are sorted by ascending order of the GROUP BY list. You can
override this by using the ORDER BY clause.
Example
Display each possible customer credit rating and the number of customers in each
credit rating category. Label the column # Cust.
CREDIT_RA # Cust
--------- ----------
EXCELLENT 9
GOOD 3
POOR 3
Example
Display the job titles and total monthly salary for each job title, excluding vice
presidents. Sort the list by the total monthly salary.
TITLE PAYROLL
--------------------- ----------
President 2500
Warehouse Manager 6157
Sales Representative 7380
Stock Clerk 9490
The GROUP BY column does not have to be in the SELECT clause as the following
examples shows, but the results are not very meaningful. Add the TITLE column so
that the results are more meaningful.
Example
Display the maximum salary for each title group, without displaying the title.
MAX(SALARY)
-----------
2500
1525
1400
...
8 rows selected.
Example
Display the maximum salary for each title group and display the title.
TITLE MAX(SALARY)
--------------------- -----------
President 2500
Sales Representative 1525
Stock Clerk 1400
...
8 rows selected.
Example
Display each region and the number of departments in that region.
Correct the above error by adding the GROUP BY clause. Now, REGION_ID is the
name of a group.
REGION_ID COUNT(NAME)
--------- -----------
1 4
2 2
3 2
4 2
5 2
Any column or expression in the SELECT list that is not an aggregate function must
be in the GROUP BY clause.
Example
Display the department number and average salary for those departments that have an
average salary more than 2000.
DEPT_ID AVG(SALARY)
------- -----------
50 2025
Example
Display the number of employees for each department within each job category.
Syntax
Example
Display the job titles and total monthly salary for each job title with a total payroll
exceeding 5000. Do not include vice presidents, and sort the list by the total monthly
salary.
TITLE PAYROLL
--------------------- ----------
Warehouse Manager 6157
Sales Representative 7380
Stock Clerk 9490
In the following example, there is no group function in the SELECT list, but there are
HAVING and GROUP BY clauses. Since a group function is referenced in the
HAVING clause, the GROUP BY clause is required.
Example
Display all department numbers for departments with a total monthly payroll more
than 4000.
DEPT_ID
-------
41
50
Syntax
You can create subgroups by using the GROUP BY clause. Groups can be excluded
using the HAVING clause.
Place the HAVING and GROUP BY clauses after the WHERE clause in a statement.
Place the ORDER BY clause last.
Oracle7 Server evaluates the clauses in the following order:
1. If the statement contains a WHERE clause, the server establishes the candidate
rows.
2. The server identifies the groups specified in the GROUP BY clause.
3. The HAVING clause further restricts result groups that do not meet the group
criteria in the HAVING clause.
Practice Contents
D Showing different queries that use all group functions, with the exception of
STDDEV and VARIANCE
D Grouping by rows to achieve more than one result
D Excluding groups by using the HAVING clause
Note: Column aliases used for the queries.
Highest Lowest
---------- ----------
1020935 377
3. Write a query to display the minimum and maximum salary for each job type
ordered alphabetically.
8 rows selected.
Number of Managers
------------------
8
5. Display the number of line items in each order under each order number, labeled
Number of Items.
16 rows selected.
6. Display the manager number and the salary of the lowest paid employee for that
manager. Exclude any groups where the minimum salary is less than 1000. Sort
the output by salary.
DIFFERENCE
----------
1750
8 rows selected.
9. Retrieve the region number, region name, and the number of departments within
each region.
ID NAME # OF DEPT
----- --------------------------- ----------------
1 North America 4
2 South America 2
3 Africa / Middle East 2
4 Asia 2
5 Europe 2
10. Display the order number and total item count for each order of 100 or more
items. For example, if order number 99 contains quantity 30 of one item, and
quantity 75 of another item, then the total item count for that order is 105.
9 rows selected.
11. Display the customer name and the number of orders for each customer.
13 rows selected.
Subqueries
6Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives
This lesson covers more advanced features of the SELECT statement. You can
write subqueries in the WHERE clause of another SQL statement to obtain
values based on an unknown conditional value.
At the end of this lesson, you should be able to
D Write nested subqueries to query data based on unknown criteria.
D Use subqueries in data manipulation statements.
D Order data with subqueries.
Subqueries 6Ć3
Server
ÉÉ
ÉÉÉÉ
ÉÉ
Subqueries 6Ć5
6Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Subqueries
Subqueries are very useful for writing SELECT statements that query values based on
an unknown conditional value. You can use the subquery to find out the values of the
unknown data.
Syntax
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Guidelines
D Enclose a subquery within parentheses.
D Place the subquery after the comparison operator.
D Do not add an ORDER BY clause to a subquery. You can have only one ORDER
BY clause for a SELECT statement, and if specified, it must be the last clause in
the main SELECT statement.
Subqueries 6Ć7
43
Example
Retrieve the last name and title of the employees in the same department as Biri.
1. The nested SELECT statement or query block is executed first, producing a query
result: 43.
2. The main query block is then processed and uses the value returned by the nested
subquery to complete its search condition.
In fact, the main query would finally look like this to the Oracle7 Server:
Subqueries 6Ć9
6Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Single Row Subqueries
A single row subquery returns only one row from the nested SELECT statement. This
type of subquery uses a single row operator.
Example
Display the last name of employees who have the same title as Smith.
LAST_NAME TITLE
----------------------- --------------------
Maduro Stock Clerk
Smith Stock Clerk
Nozaki Stock Clerk
Patel Stock Clerk
Newman Stock Clerk
Markarian Stock Clerk
Chang Stock Clerk
Patel Stock Clerk
Dancs Stock Clerk
Schwartz Stock Clerk
10 rows selected.
Note: The subquery that returned the value of Stock Clerk is called a single row
subquery. When a subquery returns only one row, you should use a single row
comparison or logical operator such as:
Subqueries 6Ć11
Server
ÉÉÉÉ
You can display data from a main query by using a group function in a subquery to
return a single row. The subquery is in parentheses and is placed after the comparison
operator.
Example
Display the last name, job title, and salary for all employees who make less than the
average salary.
12 rows selected.
Subqueries 6Ć13
6Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Errors with Subqueries
One common error with subqueries is more than one row returned for a single row
subquery.
Example
The subquery returns more than one row and uses a single row comparison operator.
To correct this error, change the = to IN.
Subqueries 6Ć15
6Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Multiple Row Subqueries
Subqueries that return more than one row are called multiple row subqueries. Be sure
to use a multiple row operator, such as IN, instead of a single row operator. The IN
operator expects one or more values.
Example
Find all employees who are in the finance department or in region 2.
You use a multiple row comparison operator, such as IN, because a list of values is
returned from the subquery.
Subqueries 6Ć17
6Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
HAVING Clause with Nested Subqueries
You can use subqueries not only in the WHERE clause, but also in the HAVING
clause. The Oracle7 Server executes the subquery, and the results are returned into
the main query’s HAVING clause.
Example
Display all the departments that have an average salary bill greater than that of
department 32.
DEPT_ID AVG(SALARY)
------- -----------
33 1515
50 2025
Example
Find the job with the lowest average salary.
TITLE AVG(SALARY)
--------------------- -----------
Stock Clerk 955
Subqueries 6Ć19
6Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
Subqueries are useful when a query is based on unknown criteria.
Syntax
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Subqueries
D Can pass one row of data to a main statement that contains a single row operator,
such as =, <>, >, >=, <, or <=.
D Can pass multiple rows of data to a main statement that contains a multiple row
operator, such as IN.
D Are processed first by the Oracle7 Server, and the WHERE or HAVING clause
uses the results.
D Can contain group functions.
Subqueries 6Ć21
6Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
In this practice, you will write complex queries using nested SELECT statements.
Practice Contents
D Creating subqueries to query values based on unknown criteria
D Identifying what values exist in one set of data and not in another by using
subqueries
You may want to consider creating the inner query first for these questions. Make
sure that it runs and produces the data you anticipate before coding the outer query.
Subqueries 6Ć23
6Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 6
1. Answer the following questions
a. Which query runs first with a subquery?
c. You cannot use the equality (=) operator if the inner query returns more than
one value.
True / False
i. If the answer is True, why and what operator should be used?
These exercises use the S_EMP, S_DEPT, S_ORD, S_ITEM, and S_PRODUCT
tables.
2. Display the first name, last name, and start date for all employees in the same
department as Magee.
3. Display the employee number, first name, last name, and user name for all
employees with salaries above the average salary.
4. Display last name, department number, and title for all employees assigned to
region 1 or region 2.
5. Display the last name and salary for all employees that report to LaDoris Ngao.
If you have time, complete the following exercises.
6. Display the employee number, first name, and last name for all employees with a
salary above the average salary and that work with any employee with a last name
that contains a “t.”
7. Display the customer number, customer name, credit rating, and sales
representative last name for all customers who are located in the North America
region or have Nguyen as their sales representative.
Subqueries 6Ć25
Practice 6 continued