You are on page 1of 322

Introduction to Oracle: SQL

and PL/SQL Using Procedure


Builder
Volume One S Participant Guide

Edition 1.1
M03989
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.

Neena Kochhar This documentation contains proprietary information of Oracle Corporation; it is


provided under a license agreement containing restrictions on use and discloĆ
Debby Kramer sure and is also protected by copyright law. Reverse engineering of the software
is prohibited. If this documentation is delivered to a U.S. Government Agency of
the Department of Defense, then it is delivered with Restricted Rights and the folĆ
lowing legend is applicable:
Technical Contributors Restricted Rights Legend
and Reviewers
Use, duplication or disclosure by the Government is subject to restrictions for
Christian Bauwens commercial computer software and shall be deemed to be Restricted Rights softĆ
ware under Federal law, and as set forth in subparagraph (c) (1) (ii) of DFARS
Debra Bowman 252.227Ć7013, Rights in Technical Data and Computer Software (October 1988).
Lenny Brunson
Jackie Collins This material or any portion of it may not be copied in any form or by any means
without the express prior written permission of the Worldwide Education Services
Ralf Durben group of Oracle Corporation. Any other copying is a violation of copyright law and
Brian Fry may result in civil and/or criminal penalties.
Anthony Holbrook If this documentation is delivered to a U.S. Government Agency not within the DeĆ
Karlene Jensen partment of Defense, then it is delivered with Restricted Rights," as defined in
Sarah Jones FAR 52.227Ć14, Rights in DataĆGeneral, including Alternate III (June 1987).
Glenn Maslen The information in this document is subject to change without notice. If you find
Sundar Nagarathnam any problems in the documentation, please report them in writing to Worldwide
Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, RedĆ
Sandra Schrick wood Shores, CA 94065. Oracle Corporation does not warrant that this document
Ulrike Schwinn is error free.
Rosemarie Truman
SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle
Jenny Tsai Server, Discoverer/2000, and Designer/2000 are trademarks or registered tradeĆ
Laura Van Deusen marks of Oracle Corporation.

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

1. Selecting Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć3
The Basic Query Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć5
Arithmetic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć13
Column Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć21
The Concatenation Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć23
Literal Character String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć25
Managing Null Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć27
Preventing the Selection of Duplicate Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć31
SQL*Plus Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć35
Logging in to SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć37
Displaying Table Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć39
SQL*Plus Editing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć41
SQL*Plus File Commands and Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć43
Creating a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć45
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć51
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć53
Practice 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ć55

2. Limiting Selected Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć3
Ordering Rows with the ORDER BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć5
Limiting Selected Rows with the WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć11
Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Ć13

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

3. Single Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć5
Single Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć7
Character Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć9
Number Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć17
Oracle Date Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć23
Using Arithmetic Operators with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć25
Date Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć27
Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć33
TO_CHAR Function with Date Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć35
TO_CHAR Function with Number Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć45
TO_NUMBER and TO_DATE Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć49
Nesting Single Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć51
Nesting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć53
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć55
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć57
Practice 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ć59

4. Displaying Data from Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć5
What Is a Cartesian Product? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć7
Simple Join Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć9
Using Table Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć17
NonĆEquijoin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć19
Returning Records with No Direct Match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć21
Joining a Table to Itself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć25
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć27
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć29
Practice 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Ć31

5. Group Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć5
Group Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Ć7

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

8. Overview of Data Modeling and Database Design . . . . . . . . . . . . . . . . . . . . . . . . 8Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć5
System Development Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć7
Database Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć9
Data Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć11
Entity Relationship Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć13
Entity Relationship Model Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć15
Integrity Constraints and Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć23
Designing the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć29
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ć39

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

10. Oracle Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć5
Querying the Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć7
Checking Constraints on a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć13
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć17
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć19
Practice 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Ć21

11. Manipulating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć5
Adding a New Row to a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć7
Copying Rows from Another Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć19
Updating Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć21
Deleting Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć29
Transaction Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć35
Committing Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć39
Rolling Back Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć43
Rolling Back Changes to a Savepoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć45
Statement Level Rollback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć47
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć49
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć51
Practice 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Ć53

12. Altering Tables and Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć5
Adding a Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć7
Modifying a Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć9
Adding and Dropping a Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ć11

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

13. Creating Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć5
Creating a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć7
Using a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć13
Altering a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć17
Removing a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć19
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć21
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć23
Practice 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Ć25

14. Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć5
Creating a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć7
Performing DML Operations on a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć15
Confirming View Names and Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć21
Removing a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć23
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć25
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć27
Practice 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Ć29

15. Creating Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć5
When Is the Index Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć7
Index Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć9
Creating an Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć13
Confirming Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć17
Removing an Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć19
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć21
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć23
Practice 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Ć25

16. Controlling User Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Ć5

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

17. Summary of SQL and SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Ć1


Summary of SQL and SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Ć3
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Ć9
Practice 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Ć11

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

19. Basics of Procedure Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć5
Oracle Procedure Builder Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć7
Procedure Builder Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć9
The Object Navigator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć15
The Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć23
The Program Unit Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć27
The Stored Program Unit Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć31
Debugging a Stored Program Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć33
Performing Debug Actions in the Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć35
Setting a Breakpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć37
Examining Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć43
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć45
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć47
Practice 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Ć49

20. Modularizing Programming with Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Ć5

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

21. Developing a Simple PL/SQL Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć5
Declaring PL/SQL Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć7
Declaring Scalar Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć9
Declaring Composite Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć15
PL/SQL Block Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć25
Assigning Values to Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć29
Programming Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć43
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć49
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć51
Practice 21 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Ć53

22. Interacting with Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć5
Retrieving Data Using PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć7
SELECT Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć15
Manipulating Data Using PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć19
SQL Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć23
Controlling Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć27
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć31
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć33
Practice 22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Ć35

23. Controlling Flow in PL/SQL Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć5
The IF Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć7
Building Logical Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć13
Loop Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć17
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć29
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć31
Practice 23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Ć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

25. Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć5
Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć7
Trapping Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć9
Trapping Predefined Oracle7 Server Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć11
Trapping NonĆPredefined Oracle7 Server Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 25Ć15
Trapping UserĆDefined Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć17
Error Trapping Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć19
Propagating Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć21
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć23
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć25
Practice 25 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Ć27

26. Summary of PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Ć1


Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Ć3
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Ć9
Practice 26 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Ć11

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

B Table Descriptions and Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ1


Summit Sporting Goods Database Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ3
S_CUSTOMER Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ4
S_DEPT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ7
S_EMP Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ8
S_IMAGE Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ10
S_INVENTORY Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ11
S_ITEM Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ16
S_ORD Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ20
S_PRODUCT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ22
S_REGION Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ25
S_WAREHOUSE Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BĆ26

C Using SQL*Plus to Create Reports and Manage PL/SQL Code . . . . . . . . . . . . CĆ1


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ5
Entering Commands in SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ7
Comparison of SQL and SQL*Plus Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ9
SQL*Plus SET Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ11
Creating a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ15
Declaring and Creating PL/SQL Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ23
Entering Commands in SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ25
Passing Input and Output Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ27
Debugging in SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ31
Displaying Contents of a Subprogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ35
Executing Stored Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ37
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ41
Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ43

xi
Practice C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ45
Practice C Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CĆ47

D Related Products and Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DĆ1


Related Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DĆ3
Related Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DĆ5

Glossary

Index

xii
Preface
Profile

Before You Begin This Course


Before you begin this course, you should be able to use a graphical user interface
(GUI). Required prerequisites are familiarity with data processing concepts and
techniques.

How This Course Is Organized


Introduction to Oracle: SQL and PL/SQL Using Procedure Builder is an
instructor-led course featuring lecture and hands-on exercises. The concepts and skills
introduced are reinforced by online demonstrations and written practice sessions.

How This Book Is Organized

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.

You will want to create SELECT


statements that you can use time and
time again. You will also see how to save
your statements for later use.
Lesson 2: Limiting Selected Rows This lesson will cover how to restrict the
rows and columns that are displayed, as
well as how to specify the order in which
the rows are presented.

xiv Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Profile continued

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.

xvi Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Profile continued

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.

xviii Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Profile continued

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

Title Part Number


Oracle7 Server SQL Reference, Release 7.3 A32538
SQL*Plus User’s Guide and Reference, Release 3.3 A42562–1
PL/SQL User’s Guide and Reference, Release 2.3 A32542
Oracle7 Server SQL Language Quick Reference 5421–70–1292
SQL*Plus Quick Reference, Release 3.3 A42561
Oracle Procedure Builder 1.5 Developer’s Guide A32485
Oracle7 Server Concepts Manual, Release 7.3 A32534
Oracle Press: Oracle Beginner’s Guide A31178–1
Oracle Press: Oracle Complete Reference A10197–1

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

xx Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Typographic Conventions
Typographic Conventions Within Text

Convention Object or Term Example


Uppercase Commands, Use the SELECT command to view
functions, information stored in the LAST_NAME
column names, column of the S_EMP table.
table names,
PL/SQL objects,
schemas
Lowercase, File names, where: role is the name of the role to be
italic syntax variables, created.
usernames,
passwords
Initial cap Triggers and Assign a When–Validate–Item trigger to the
button names S_ORD block.
Press the Cancel button.
Italic Books, names of For further information on the subject see:
courses and Oracle7 Server SQL Language Reference
manuals, and Manual
emphasized
words or phrases Do not save changes to the database.
Quotation marks Lesson module This subject is covered in Lesson 3, “Working
titles referenced with Objects.”
within a course
Italic bold The first time a The algorithm inserts the new key.
glossary word is
referred to in a
section

Preface xxi
Typographic Conventions continued

Typographic Conventions Within Code

Convention Object or Term Example


Uppercase Commands, SQL> SELECT userid
functions 2 FROM s_emp;
Lowercase, Syntax variables SQL> CREATE ROLE role;
italic
Lowercase Column names, . . .
table names, file OG_ACTIVATE_LAYER
names, PL/SQL (OG_GET_LAYER (’prod_pie_layer’))
objects . . .
SQL> SELECT last_name
2 FROM s_emp;
SQLDBA> DROP USER scott
2> IDENTIFIED BY tiger;
Bold Text that must SQL> SELECT userid
be entered by a 2 FROM s_emp;
user.
Vertical bar Separates OFF | ON
alternative
syntax elements
Brackets Optional items [OFF | ON]
list in syntax
Braces Mandatory {OFF | ON}
items list in
syntax
Underlining Default value in {OFF | ON}
syntax

xxii Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Typographic Conventions continued

Symbols Used in This Document

Guidance relating to the subject matter, such as hints or advice.

For more information, see


a publication related to the subject matter

This icon indicates a warning relating to the subject matter. An example warning
might be “When deleting rows, word your WHERE clause carefully.”

Used for a series of instructions that must be followed in sequential order.

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.

Concepts of the Relational Model


D Collections of objects or relations store the data.
D A set of operators can act on the relations to produce other relations.
D A relational database must possess data integrity so that its data must be accurate
and consistent.
An example of a relation is a table. To retrieve data from the tables, use relational
operation SQL commands.

Relational Database Functions


D Manage the storage of data
D Control access to the data
D Provide a means to retrieve and modify the data
For more information, see
The Relational Model for Database Management Version 2, E. F. Codd, Addison
Wesley.

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

Relational Database Properties


A database is a collection of individual, named objects, such as tables. You do not
specify the access route to the tables, and do not need to know how the data is
arranged physically.
To access the database, you execute a Structured Query Language (SQL) command,
which is the American National Standards Institute (ANSI) standard language for
operating upon relational databases. The language contains a large set of operators for
partitioning and combining relations. The database can be easily modified by using
the SQL commands. The relational model allows for full data independence.

Abridged List of Database Objects

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

Protect Data Integrity


Ensure that users perform only operations that leave the database in a correct and
consistent state with data integrity constraints. All data integrity constraints should be
enforced by the database server or the application software.

Integrity Constraint Type Description


Entity No part of a primary key can be NULL and the
value must be unique.
Referential Foreign key values must match a primary key or be
NULL.
Column Values in the column must match the defined
datatype.
User-defined Values must comply with the business rules.

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

É ÉÉ

IĆ18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


What Is Oracle?
Oracle is a database company that offers a comprehensive set of application building
and end-user products and services aimed at providing complete information
technology solutions. Oracle applications are portable across a wide range of
platforms and operating systems, from personal computers to large parallel
processors.

About the Oracle7 Server


Oracle provides a flexible RDBMS called the Oracle7 Server. Its features allow you
to store and manage information with all the advantages of a relational structure plus
PL/SQL, an engine that provides you with the ability to store and execute database
objects, such as procedures and triggers. The Server offers users the options of
retrieving data based on optimization techniques. It includes security features that
control how a database is accessed and used. Other features are that it has consistency
and protection of data through locking mechanisms, and a two-phase commit process
for distributed databases across a network.
Oracle applications may run on the same computer as the Oracle7 Server.
Alternatively, you can run applications on a system local to the user and run the
Oracle7 Server on another system (client-server architecture). In this client-server
environment, a wide range of computing resources can be used. For example, a
form-based airline reservation application can run on a client personal computer
while accessing flight data that is conveniently managed by an Oracle7 Server on a
central computer.
For more information, see
Oracle7 Server Concepts Manual.

Introduction IĆ19
DSS Tools

IĆ20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


The Oracle Product Set
All application development and end-user products available within the Oracle
product set allow you to access the database, either directly or indirectly, through
SQL commands.

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

IĆ22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


SQL, SQL*Plus, and PL/SQL
SQL, SQL*Plus, and PL/SQL commands are used to access and manipulate data
stored in an Oracle database.

SQL*Plus, SQL, and PL/SQL

Language or Tool Description


SQL A command language for communication with the
Oracle7 Server from any tool or application. Oracle
SQL contains many extensions.
SQL*Plus An Oracle tool that recognizes and submits SQL and
PL/SQL statements to the Server for execution and
contains its own command language.
PL/SQL An Oracle procedural language for writing application
logic and manipulating data outside the database.

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.

For more information, see


Oracle7 Server SQL Reference, Release 7.3 and Oracle7 SQL Quick Reference
Guide.

Introduction IĆ25
IĆ26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL, SQL*Plus, and PL/SQL continued

SQL*Plus Command Categories

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.

PL/SQL Block Structure


PL/SQL provides a host of programming constructs to manipulate data. Each group
of commands is packaged in a PL/SQL block.

Block Section Description


Header Contains the subprogram name, type, and arguments.
Only used for subprograms.
Declarative Contains the local identifiers for the block.
Executable Contains the SQL statements and PL/SQL control
statements.
Exception Performs actions when errors occur.

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

“I’m a manager of a sporting goods wholesale company that operates worldwide to


fill orders of retail sporting goods stores. The stores are our customers (some of our
people prefer to call them our clients). Right now we have fifteen customers
worldwide, but we’re trying to expand our customer base. Our two biggest customers
are Big John’s Sports Emporium in San Francisco, CA, USA, and Womansport in
Seattle, Washington, USA. For each customer, we must track an identification
number and customer name. We may track an address (including the city, state, postal
code, and country) and phone number. We maintain warehouses in different regions
to best fill the orders of our customers. For each order, we must track an order
number. We may track the date ordered, date shipped, and payment type when the
information is available. Right now, we have the world divided into five regions:
North America, South America, Africa/Middle East, Asia, and Europe. That’s all we
track, just the region number and region name. We try to assign each customer to a
region so we’ll generally know the best location from which to fill each order. Each
warehouse must have a warehouse number. We may track an address (including city,
state, postal code, and country) and phone number. We currently have only one
warehouse per region, but we’re hoping to have more soon.”
“I manage the order entry functions for our wholesale sporting goods business. My
department is responsible for placing and tracking the orders when our customers
call. For each department, we must track the department number and name.
Sometimes, our customers just mail us the orders when they are not in a rush, but
most often they call us or fax us an order. We are hoping to expand our business by
providing immediate turnaround of order information to our clients. We can promise
to ship by the next day as long as the goods are in stock (or inventory) at one of our
warehouse locations. When the information is available, we track the amount in
stock, the reorder point, maximum stock, the reason we are out of stock, and the date
we restocked the item. When the goods are shipped, we intend to fax the shipping
information automatically through our shipping system. No, I don’t manage that area.
Continued

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.

Selecting Rows 1Ć3


1Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Basic Query Block
A SELECT statement retrieves information from the database, implementing all
algebraic operators.

Syntax

SELECT [DISTINCT] {*,column [alias],....}


FROM table;

where: SELECT is a list of at least one column.


DISTINCT suppresses duplicates.
* selects all columns.
column selects the named column.
alias gives selected columns a different heading.
FROM table specifies the table containing the columns.

Selecting Rows 1Ć5


1Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Basic Query Block continued

Writing SQL Commands


By following these simple rules and guidelines, you will be able to construct valid
statements that are easy both to read and to edit.
D SQL commands may be entered on one or many lines.
D Clauses are usually placed on separate lines for readability and ease of editing.
D Tabs and indents can be used to make code more readable.
D Command words cannot be split across lines or abbreviated.
D Keywords and commands typically are entered in uppercase; all other words,
such as table names and columns, are entered in lowercase.
D SQL commands are not case sensitive, unless indicated.
D An SQL command is entered at the SQL prompt, and subsequent lines are
numbered. This is called the SQL buffer.
D Only one statement can be current at any time within the buffer, and the
statement can be executed in a number of ways:
D Place a semicolon (;) at the end of last clause.
D Place a semicolon or slash on the last line in the buffer.
D Place a slash at the SQL prompt.
D Issue a SQL*Plus RUN command at the SQL prompt.
For more information, see
Oracle Applications: Coding Standards, Release 10G.

Selecting Rows 1Ć7


Simplest SELECT statement contains the
following two clauses:

1Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


The Basic Query Block continued

In its simplest form, a SELECT statement must include the following:


D A SELECT clause, which specifies the columns to be displayed.
D A FROM clause, which specifies the table containing the columns listed in the
SELECT clause.

Selecting All Columns and Rows


The asterisk (*) selects all columns from the table.

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.

Selecting Rows 1Ć9


1Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Basic Query Block continued

Selecting Specific Columns


You restrict the query to display only certain columns by specifying the column
names, separated by commas, in the SELECT clause.

Example
Display all department numbers, employee last names, and manager numbers in the
S_EMP table.

SQL> SELECT dept_id, last_name, manager_id


2 FROM s_emp;

DEPT_ID LAST_NAME MANAGER_ID


------- ------------ ----------
50 Velasquez
41 Ngao 1
31 Nagayama 1
10 Quick-To-See 1
50 Ropeburn 1
41 Urguhart 2
42 Menchu 2
43 Biri 2
44 Catchpole 2
...

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.

Column Heading Defaults


Character and date column headings and data are left-justified within a column and
numbers are right-justified. Character and date column headings may be truncated,
but number headings may not be truncated. The column labels appear in uppercase by
default. You can override the column label display with an alias.

Selecting Rows 1Ć11


1Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Arithmetic Expressions
You may need to modify the way data is displayed, perform calculations, or look at
what-if scenarios. This is possible using arithmetic expressions.
An arithmetic expression may contain column names, constant numeric values, and
the arithmetic operators.

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

Selecting Rows 1Ć13


1Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Arithmetic Expressions continued

Example
Use the multiplication operator to display annual salary figures and their commission
percentage for all employees.

SQL> SELECT last_name, salary * 12, commission_pct


2 FROM s_emp;

LAST_NAME SALARY*12 COMMISSION_PCT


------------ ---------- --------------
...
Havel 15684
Magee 16800 10
Giljum 17880 12.5
Sedeghi 18180 10
Nguyen 18300 15
Dumas 17400 17.5
Maduro 16800
...

Notice that the resultant calculated column SALARY*12 is not a new column in the
originating table, but is for display only.

Selecting Rows 1Ć15


1Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Arithmetic Expressions continued

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.

SQL> SELECT last_name, salary, 12 * salary + 100


2 FROM s_emp;

LAST_NAME SALARY 12*SALARY+100


------------ ---------- -------------
Velasquez 2500 30100
Ngao 1450 17500
Nagayama 1400 16900
Quick-To-See 1450 17500
Ropeburn 1550 18700
Urguhart 1200 14500
...

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.

Selecting Rows 1Ć17


1Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Arithmetic Expressions continued

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.

SQL> SELECT last_name, salary, 12 * (salary + 100)


2 FROM s_emp;

LAST_NAME SALARY 12*(SALARY+100)


------------ ---------- ---------------
Velasquez 2500 31200
Ngao 1450 18600
Nagayama 1400 18000
Quick-To-See 1450 18600
Ropeburn 1550 19800
Urguhart 1200 15600
...

Selecting Rows 1Ć19


1Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Column Aliases
When displaying the result of a query, SQL*Plus normally uses the selected column’s
name as the heading. In many cases, that heading may be difficult to understand or
even meaningless. You can change a column’s heading by using a column alias.
Specify the alias after the column in the SELECT list using a space as a separator. By
default, alias headings will be forced to uppercase and cannot contain blank spaces,
unless the alias is enclosed in double quotation marks (“ ”).

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.

SQL> SELECT last_name, salary,


2 12 * (salary + 100) AS ANNUAL_SALARY
3 FROM s_emp;

Note: You can include the AS keyword before the alias name to comply with ANSI
SQL 92 standards.

Column Aliases with Double Quotation Marks


If the alias contains spaces, special characters (such as # or $), or is case-sensitive,
enclose the alias in double quotation marks (“ ”).

SQL> SELECT last_name, salary,


2 12 * (salary + 100) ”Annual Salary”
3 FROM s_emp;

Selecting Rows 1Ć21


1Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The Concatenation Operator
You can link columns to other columns, arithmetic expressions, or constant values to
create a character expression by using the concatenation operator (||). Columns on
either side of the operator are combined to make one single output column.

Example
Display the full names of the employees with the heading Employees.

SQL> SELECT first_name||last_name AS ”Employees”


2 FROM s_emp;

Employees
--------------------------------------------------
CarmenVelasquez
LaDorisNgao
MidoriNagayama
MarkQuick-To-See
AudryRopeburn
MollyUrguhart
...

The AS keyword before the alias name makes the SELECT clause easier to read.

Selecting Rows 1Ć23


1Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Literal Character String
A literal is any character, expression, or number included in the SELECT list that is
not a column name or a column alias. It is printed for each row returned. Literal
strings of free-format text can be included in the query result and are treated like a
column in the SELECT list.
Date and character literals must be enclosed within single quotation marks (‘ ’);
number literals must not.

Example
Display the full names of the employees and their titles with the heading Employees.
Be sure to add punctuation.

SQL> SELECT first_name || ’ ’ || last_name


2 || ’, ’|| title ”Employees”
3 FROM s_emp;

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
...

Selecting Rows 1Ć25


1Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Managing Null Values
If a row lacks a data value for a particular column, that value is said to be null, or to
contain null.
A null value is a value that is unavailable, unassigned, unknown, or inapplicable. In
the COMMISSION_PCT column, you notice that only Sales Representatives earn
commission. Other employees are not entitled to earn commission. A null value
represents that fact.
A null value is not the same as zero or a space. Zero is a number, and a space is a
character.
Columns of any datatype can contain null values, unless the column was defined as
NOT NULL or as PRIMARY KEY when the table was created.

Null Values in Arithmetic Expressions


If any column value in an expression is null, the result is null. For example, if you
attempt to perform division with zero, you will get an error. However, if you divide
by null, the result is null.

Example
Display the last name, salary, title, and calculated commission.

SQL> SELECT last_name, title,


2 salary*commission_pct/100 COMM
3 FROM s_emp;

LAST_NAME TITLE COMM


------------ --------------------- ----------
...
Havel Warehouse Manager
Magee Sales Representative 140
Giljum Sales Representative 186.25
Sedeghi Sales Representative 151.5
Nguyen Sales Representative 228.75
Dumas Sales Representative 253.75
Maduro Stock Clerk
...

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “Elements of SQL.”

Selecting Rows 1Ć27


1Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Managing Null Values continued

NVL Function
In order to convert a null value to an actual value, use the NVL function.

Syntax

NVL (expr1, expr2)

where: expr1 is the source value or expression that may


contain null.
expr2 is the target value for converting null.
Note: You can use the NVL function to convert any datatype, but the return value is
always the same as the datatype of expr1.

Example
To calculate values for all employees from the previous example, use the NVL
function to convert null values to zero.

SQL> SELECT last_name, title,


2 salary * NVL(commission_pct,0)/100 COMM
3 FROM s_emp;

LAST_NAME TITLE COMM


------------ --------------------- ----------
...
Havel Warehouse Manager 0
Magee Sales Representative 186.25
Giljum Sales Representative 186.25
...

NVL Conversions for Various Datatypes

Datatype Conversion Example


NUMBER NVL(number_column,9)
DATE NVL(date_column,‘01-JAN-95’)
CHAR or VARCHAR2 NVL(character_column,‘Unavailable’)

Selecting Rows 1Ć29


SQL> SELECT DISTINCT name
2 FROM s_dept;

1Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Preventing the Selection of Duplicate Rows
Unless you indicate otherwise, SQL*Plus displays the results of a query without
eliminating duplicate rows.
Example Displaying All Rows
Display all department names in the S_DEPT table.

SQL> SELECT name


2 FROM s_dept;

NAME
------------------
Finance
Sales
Sales
Sales
Sales
Sales
Operations
. . .
12 rows selected

The DISTINCT Keyword


To eliminate duplicate rows in the result, include the DISTINCT keyword in the
SELECT clause immediately after the SELECT command word.
Example Displaying Unique Rows
Display all unique department names in the S_DEPT table.

SQL> SELECT DISTINCT name


2 FROM s_dept;

NAME
-----------------------
Administration
Finance
Operations
Sales

Selecting Rows 1Ć31


1Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Preventing the Selection of Duplicate Rows continued

DISTINCT with Multiple Columns


You can specify multiple columns after the DISTINCT qualifier. The DISTINCT
qualifier affects all selected columns.

Example
Display all the different combinations of job titles and department numbers.

SQL> SELECT DISTINCT dept_id, title


2 FROM s_emp;

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.

Selecting Rows 1Ć33


1Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL*Plus Commands
In this lesson, you saw how SQL commands are executed within a product called
SQL*Plus. SQL*Plus is a SQL and PL/SQL command execution environment with
additional features.
You can use a number of SQL*Plus commands when writing even the most basic of
SQL statements. This section covers some basic SQL*Plus commands to help you to
D Describe the table structure.
D Edit SQL in the buffer.
D Save files containing SQL for editing purposes.
D Execute saved files.
D Load SQL commands from a file into the SQL buffer.
D Obtain online help
For more information, see
SQL*Plus User’s Guide and Reference, Release 3.3.

Selecting Rows 1Ć35


1Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Logging in to SQL*Plus
How you invoke SQL*Plus depends upon which type of operating system or
windows environment you are running.

Log In Through a Windows Environment


You double-click the SQL*Plus icon in the window manager, then enter the
username, password, and database, if required.

Log In Through a Command Line Environment


Once you log on to your machine, at the operating system prompt enter the SQL*Plus
command.

sqlplus [username [/password [@database]]]

where: username is your database username.


password is your database password. If you enter your
password here, it is visible.
@database is the database connect string.
Note: To ensure the integrity of your password, do not enter it at the operating
system prompt. Instead, only enter your username. Enter your password at the
Password prompt.
Once you are successfully logged in SQL*Plus, you see the following message:

SQL*Plus: Version 3.1.2 Production on Fri May 12th 15:31:32 1995


Copyright (c) Oracle Corporation 1979, 1992, All rights reserved.

SQL>

Selecting Rows 1Ć37


SQL> DESCRIBE s_dept

1Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Displaying Table Structure
In SQL*Plus, you can display the structure of a table using the DESCRIBE
command. The result of the command is to see the column names, datatypes, and
whether a column must contain data.

DESC[RIBE] tablename

where: tablename is the name of any existing table, view, or


synonym accessible to the user.

Example
Display information about the structure of the S_DEPT table.

SQL> DESCRIBE s_dept

Name Null? Type


--------------- -------- --------------------
ID NOT NULL NUMBER(7)
NAME NOT NULL VARCHAR2(25)
REGION_ID NUMBER(7)

where: Null? indicates that a column must contain data.


Type displays the datatype for a column.

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.

For more information, see


Oracle 7 Server SQL Reference, Release 7.3.

Selecting Rows 1Ć39


1Ć40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL*Plus Editing Commands
When you enter a SQL command, it is stored in a part of memory called the SQL
buffer and remains there until you enter a new command. SQL*Plus commands are
entered one line at a time and are not stored in the SQL buffer.

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.

SQL*Plus Editing Commands

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.

Selecting Rows 1Ć41


1Ć42 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL*Plus File Commands and Online Help
SQL commands act as the vehicle to the Oracle Server. SQL*Plus commands are
used to control the environment, format query results, and manage files. You can use
the commands identified in the following table.

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 (-).

Selecting Rows 1Ć43


1Ć44 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Report

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

COL[UMN] [{column|alias} [option ...]]

COLUMN Command Options

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 (-).

Selecting Rows 1Ć45


1Ć46 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Report continued

Display or Clear Settings


To show or clear the current COLUMN command settings, use the following
commands:

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.

Selecting Rows 1Ć47


1Ć48 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Report continued

Sample Column Format Model Elements

Element Description Example Result


An Sets a display width of n for N/A N/A
character and date columns.
9 Represents a single 999999 1234
zero-suppression digit.
0 Enforces leading zero. 099999 01234
$ Represents a floating dollar sign. $9999 $1234
L Represents local currency. L9999 L1234
. Represents the position of the 9999.99 1234.00
decimal point.
, Represents the thousand separator. 9,999 1,234

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.

Selecting Rows 1Ć49


1Ć50 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
In this lesson, you have learned about retrieving information from a database table
with the SELECT statement.

SELECT [DISTINCT] {*, column [alias], ...}


FROM table;

where: SELECT is a list of at least one column.


DISTINCT suppreses duplicates.
* selects all columns.
column selects the named column.
alias gives selected column a different heading.
FROM table specifies the table containing the columns.

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.

Selecting Rows 1Ć51


1Ć52 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This is the first of many practices. In most cases, the questions show the output that is
required. The solutions (if you require them) can be found in Appendix A. Practices
are intended to introduce all topics covered in the lesson. The first six questions are
paper–based.
In any practice, there may be “if you have time” questions. Do these only if you have
completed all other questions within the allocated time and would like a further
challenge to your skills.

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.

Selecting Rows 1Ć53


1Ć54 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 1
1. SQL commands are always held in a buffer.
True / False
2. SQL*Plus commands assist with querying data.
True / False
3. Show the structure of the S_DEPT table. Select all information from the
S_DEPT table.

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.

Selecting Rows 1Ć55


Practice 1 continued

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.

1Ć56 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


2

Limiting Selected Rows


2Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

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.

Limiting Selected Rows 2Ć3


If the ORDER BY clause is not used, the sort order is undefined, and the Oracle7
Server may not fetch rows in the same order for the same query twice. Use the
ORDER BY clause to display the rows in a specific order.

2Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Ordering Rows with the ORDER BY Clause
The order of rows returned in a query result is undefined. The ORDER BY clause
may be used to sort the rows. If used, you must place the ORDER BY clause last.
You can specify an expression or use position to sort.

Syntax

SELECT expr
FROM table
[ORDER BY {column,expr} [ASC|DESC]];

where: ORDER BY specifies the order in which the retrieved rows


are displayed.
ASC orders the rows in ascending order. This is the
default order.
DESC orders the rows in descending order.

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.

SQL> SELECT last_name, dept_id, start_date


2 FROM s_emp
3 ORDER BY last_name;

LAST_NAME DEPT_ID START_DAT


------------ ------- ---------
Biri 43 07-APR-90
Catchpole 44 09-FEB-92
Chang 44 30-NOV-90
Dancs 45 17-MAR-91
Dumas 35 09-OCT-91
Giljum 32 18-JAN-92
Havel 45 27-FEB-91
...

Limiting Selected Rows 2Ć5


2Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Ordering Rows with the ORDER BY Clause continued

Default Ordering of Data


The default sort order is ascending:
D Numeric values are displayed with the lowest values first, for example 1-999.
D Date values are displayed with the earliest value first, for example 01-JAN-92
before 01-JAN-95.
D Character values are displayed in alphabetical order, for example A first and Z
last.
D In Oracle7, null values are displayed last for ascending sequences and first for
descending sequences.

Reversing the Default Order


To reverse the order in which rows are displayed, the command word DESC is
specified after the column name in the ORDER BY clause.

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.

SQL> SELECT last_name, dept_id, start_date


2 FROM s_emp
3 ORDER BY start_date DESC;

LAST_NAME DEPT_ID START_DAT


------------ ------- ---------
...
Urguhart 41 18-JAN-91
Chang 44 30-NOV-90
Patel 34 17-OCT-90
Menchu 42 14-MAY-90
...
25 rows selected.

Ordering with Column Aliases


You can use a column alias in the ORDER BY clause. This feature was made
available in Oracle7 release 7.0.16.

Limiting Selected Rows 2Ć7


2Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Ordering Rows with the ORDER BY Clause continued

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.

SQL> SELECT last_name, salary*12


2 FROM s_emp
3 ORDER BY 2;

Ordering by Many Columns


You can sort query results by more than one column. The sort limit is the number of
columns in the table.
In the ORDER BY clause, specify the columns, and separate the column names using
commas. If you want to reverse the order of a column, specify DESC after its name or
position. You can order by columns that are not 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.

SQL> SELECT last name, dept_id, salary


2 FROM s_emp
3 ORDER BY dept_id, salary DESC;

LAST_NAME DEPT_ID SALARY


------------ ------- ----------
Quick-To-See 10 1450
Nagayama 31 1400
Magee 31 1400
Giljum 32 1490
Sedeghi 33 1515
Nguyen 34 1525
Patel 34 795
...

Limiting Selected Rows 2Ć9


2Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Limiting Selected Rows with the WHERE Clause
You can restrict the rows returned from the query by using the WHERE clause. A
WHERE clause contains a condition that must be met, and directly follows the
FROM clause.

Syntax

SELECT expr
FROM table
[WHERE condition(s)]
[ORDER BY expr];

where: WHERE restricts the query to rows that meet a condition.


condition is composed of column names, expressions,
constants, and comparison operators.

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 expr operator value

Example WHERE conditions

...WHERE dept_id = 42

Limiting Selected Rows 2Ć11


2Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Comparison Operators

Character Strings and Dates


Character strings and dates in the WHERE clause must be enclosed in single
quotation marks (‘ ’). Number constants, however, must not.

Example
Write a query to show the first and last names, and title for the employee named
“Magee.”

SQL> SELECT first_name, last_name, title


2 FROM s_emp
3 WHERE last_name = ’MAGEE’;
no rows selected

All character strings are case sensitive. Therefore, change the last name to be initial
capitals in order to acquire a match.

SQL> SELECT first_name, last_name, title


2 FROM s_emp
3 WHERE last_name = ’Magee’;

FIRST_NAME LAST_NAME TITLE


------------ ------------- ---------------------
Colin Magee Sales Representative

Limiting Selected Rows 2Ć13


2Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Comparison Operators continued

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.

Limiting Selected Rows 2Ć15


2Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Negating Expressions
You may find that it is easier to find the rows that do not meet a condition, rather than
those that do. Use the comparison and SQL operators with a negative expression.

Negating Logical Operators


Operator Description
!= Not equal to (VAX, UNIX, PC)
^= Not equal to (IBM)
:=
<> Not equal to (all operating systems)
NOT colname = Not equal to
NOT colname > Not greater than

Negating SQL Operators


Operator Description
NOT BETWEEN...AND... Not between two specified values
NOT IN (list) Not in specified list of values
NOT LIKE Not like comparison string
IS NOT NULL Is not a null value

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.

For example, COMMISSION_PCT! = NULL is always FALSE because a null value


may not be either equal or unequal to any other value, even another null value. Note
that an error is not raised, the result is simply always FALSE.

Limiting Selected Rows 2Ć17


SQL> SELECT first_name, last_name, start_date
2 FROM s_emp
3 WHERE start_date BETWEEN ’09-may-91’
4 AND ’17-jun-91’;

2Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


SQL Operators
The BETWEEN Operator
You can display rows based on a range of values using the BETWEEN operator. The
range you specify contains a lower range and an upper range.

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.

SQL> SELECT first_name, last_name, start_date


2 FROM s_emp
3 WHERE start_date BETWEEN ’09-may-91’
4 AND ’17-jun-91’;

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.

SQL> SELECT id, name, region_id


2 FROM s_dept
3 WHERE region_id IN (1,3);

If characters or dates are used in the list, they must be enclosed in single quotation
marks (‘ ’).

Limiting Selected Rows 2Ć19


SQL> SELECT last_name
2 FROM s_emp
3 WHERE last_name LIKE ’M%’;

2Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


SQL Operators continued

The LIKE Operator


You may not always know the exact value to search for. You can select rows that
match a character pattern by using the LIKE operator. The character pattern matching
operation is referred to as a wildcard search. Two symbols can be used to construct
the search string.

Symbol Description
% Represents any sequence of zero or more characters.
_ Represents any single character.

Example
Display all employee last names beginning with “M.”

SQL> SELECT last_name


FROM s_emp
WHERE last_name LIKE ’M%’;

LAST_NAME
------------
Menchu
Magee
Maduro
Markarian

Example
Display all employee last names that do not contain an “a” within the name.

SQL> SELECT last_name


2 FROM s_emp
3 WHERE last_name NOT LIKE ’%a%’;

Limiting Selected Rows 2Ć21


2Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL Operators continued

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.

SQL> SELECT last_name, start_date


2 FROM s_emp
3 WHERE start_date LIKE ’%91’;

Combine Wildcard Characters


The % and _ symbols may be used in any combination with literal characters.

Example
Display the last names of employees whose last name has an “a” as the second letter.

SQL> SELECT last_name


2 FROM s_emp
3 WHERE last_name LIKE ’_a%’;

The ESCAPE Option


When you need to have an exact match for the actual “%” and “_” characters, use the
ESCAPE option. This option specifies what the ESCAPE character is.

Example
Display the names of companies whose name contains “X_Y.”

SQL> SELECT name


2 FROM s_customer
3 WHERE name LIKE ’%X\_Y%’ ESCAPE ’\’;

Limiting Selected Rows 2Ć23


2Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL Operators continued

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.

SQL> SELECT id, name, credit_rating


2 FROM s_customer
3 WHERE sales_rep_id = NULL;
no rows selected

SQL> SELECT id, name, credit_rating


2 FROM s_customer
3 WHERE sales_rep_id = ’’;
no rows selected

SQL> SELECT id, name, credit_rating


2 FROM s_customer
3 WHERE sales_rep_id IS NULL;

ID NAME CREDIT_RA
------- -------------------- ---------
207 Sweet Rock Sports GOOD

Example
Display all employee last names, titles, and commission percentages who make a
commission.

SQL> SELECT last_name, title, commission_pct


2 FROM s_emp
3 WHERE commission_pct IS NOT NULL;

Limiting Selected Rows 2Ć25


SQL> SELECT last_name, salary, dept_id, title
2 FROM s_emp
3 WHERE dept_id = 41
4 AND title = ’Stock Clerk’;

2Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Querying Data with Multiple Conditions
You may need to specify complex criteria by combining several search conditions.
The AND and OR operators may be used to make compound logical expressions.
The AND operator returns TRUE if both conditions evaluate to TRUE, whereas the
OR operator returns TRUE if either condition is TRUE.
In the following two examples, the conditions are the same, but the operator is
different. See how the result is dramatically changed.

Example 1
Display the last name, salary, department number, and title for all stock clerks in
department 41.

SQL> SELECT last_name, salary, dept_id, title


2 FROM s_emp
3 WHERE dept_id = 41
4 AND title = ’Stock Clerk’;

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.

SQL> SELECT last_name, salary, dept_id, title


2 FROM s_emp
3 WHERE dept_id = 41
4 OR title = ’Stock Clerk’;

Note: OR is a less restrictive clause. Consequently, more rows may be returned.


For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Logical Operators.”

Limiting Selected Rows 2Ć27


Order Evaluated Operator
1 All comparison operators.
2 AND
3 OR

2Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Rules of Precedence
You may combine AND and OR operators in the same logical expression. The results
of all of the conditions are combined in the order determined by the precedence of the
connecting operators. Where operators of equal precedence are used next to each
other, they are performed from left to right.
Each AND is performed first then each OR is performed. AND has a higher
precedence than OR.

Rules of Precedence

Order Evaluated Operator


1 All comparison operators
(=, <>, >, >=, <, <=, IN, LIKE, IS NULL, BETWEEN)
2 AND
3 OR

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.

Limiting Selected Rows 2Ć29


2Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Rules of Precedence continued

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.

SQL> SELECT last_name, salary, dept_id


2 FROM s_emp
3 WHERE salary >= 1000
4 AND dept_id = 44
5 OR dept_id = 42;

LAST_NAME SALARY DEPT_ID


------------ ------------ --------
Menchu 1250 42
Catchpole 1300 44
Nozaki 1200 42
Patel 795 42

Example 2
Display the last name, salary, and department number for those employees in
department 44 or 42 who earn 1000 or more.

SQL> SELECT last_name, salary, dept_id


2 FROM s_emp
3 WHERE salary >= 1000
4 AND (dept_id = 44
5 OR dept_id = 42);

LAST_NAME SALARY DEPT_ID


------------ ------------ --------
Menchu 1250 42
Catchpole 1300 44
Nozaki 1200 42

Limiting Selected Rows 2Ć31


2Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
In this lesson, you have learned about sorting rows and restricting the rows returned
by the SELECT statement. You have also learned how to implement comparison
operators.

Syntax

SELECT [DISTINCT] {*,column [alias],....}


FROM table
[WHERE condition(s)]
[ORDER BY {column,expr} [ASC|DESC]];

where: SELECT is a list of at least one column.


DISTINCT suppresses duplicates.
* selects all columns.
column selects the named column.
alias gives selected columns a different heading.
FROM table specifies the table containing the columns.
WHERE restricts the query to rows that meet a condition.
condition is composed of column names, expressions,
constants, and comparison operators.
ORDER BY specifies the order in which the retrieved rows
are displayed.
ASC orders rows in ascending order.
DESC orders the rows in descending order.

Limiting Selected Rows 2Ć33


2Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice gives you a variety of exercises using the WHERE clause and the
ORDER BY clause.

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.

Limiting Selected Rows 2Ć35


2Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 2
1. You cannot order by a column that you have not selected.
True / False
2. This SELECT statement will execute successfully.
True / False

SQL> Select last_name, title, salary Ann_sal


2 From s_emp
3 Where last_name = ’Dancs’;

3. This SELECT statement will execute successfully.


True / 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?

SQL> SELECT id, last_name,


2 salary x 12 ANNUAL SALARY
3 FROM s_emp
4 WHERE sal > 3000
5 AND start_date LIKE %84;

Limiting Selected Rows 2Ć37


Practice 2 continued

5. Use the S_CUSTOMER table and perform the following actions.


a. Create a query to display the name, customer number, and credit rating for all
companies represented by sales representative 11. Save your SQL statement to
a file named p2q5.
b. Run your query in the file p2q5.
c. Load p2q5 into the SQL buffer. Name the column headings Company,
Company ID, and Rating. Rerun your query. Re-save your query as p2q5.

Company Company ID Rating


-------------------------- ––––––––––– ––––––––
Womansport 204 GOOD
Beisbol Si! 209 GOOD
Big John’s Sports Emporium 213 GOOD
Ojibway Retail 214 GOOD

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

c. Display all employees whose last names contain an “s.”


d. Display the user names and start date of employees hired between May 14,
1990 and May 26, 1991. Order the query results by start date ascending order.

2Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 continued

If you have time, complete the following exercises.


7. Use the S_EMP table to perform the following actions.
a. Write a query to show the last name and salary of all employees who are not
making between 1000 and 2500 per month.
b. List the last name and salary of employees who earn more than 1350 who are
in department 31, 42, or 50. Label the last name column Employee Name, and
label the salary column Monthly Salary.
c. Display the last name and start date of every employee who was hired in
1991.
d. Display the full name of all employees with no manager.
8. Show the structure of S_PRODUCT table.
a. Alphabetically display all products having a name beginning with Pro.
b. Display all product names and short descriptions for all descriptions
containing the word “bicycle.”
c. Display all short descriptions. Compare the results from Exercise 8b. Did your
response in Exercise 8b return all descriptions containing bicycle?

Limiting Selected Rows 2Ć39


2Ć40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
3

Single Row Functions


3Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

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.

Single Row Functions 3Ć3


3Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
Functions are a very powerful feature of SQL and can be used to
D Perform calculations on data.
D Modify individual data items.
D Manipulate output for groups of rows.
D Alter date formats for display.
D Convert column datatypes.

There are two distinct types of functions:


D Single row functions.
D Multiple row functions.

Single Row Functions


These functions operate on single rows only, and return one result per row. There are
different types of single row functions. We will cover those listed below.
D Character
D Number
D Date
D Conversion

Multiple Row Functions


These functions manipulate groups of rows to give one result per group of rows.
For more information, see
Oracle7 Server SQL Reference, Release 7.3 for the complete list of available
functions and syntax.

Single Row Functions 3Ć5


3Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Single Row Functions
Single row functions are used to manipulate data items. They accept one or more
arguments and return one value for each row returned by the query. An argument may
be one of the following:
D A user-supplied constant
D A variable value
D A column name
D An expression

Features of Single Row Functions


D They act on each row returned in the query.
D They return one result per row.
D They may return a data value of a different type than that referenced.
D They may expect one or more user arguments.
D You can nest them.
D You can use them in SELECT, WHERE, and ORDER BY clauses.

Syntax

function_name (column|expression, [arg1, arg2,...])

where: function_name is the name of the function.


column is any named database column.
expression is any character string or calculated expression.
arg1, arg2 is any argument to be used by the function.

Single Row Functions 3Ć7


3Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Character Functions
Single row character functions accept character data as input and can return both
character and number values.

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.

Note: This list is a subset of the available character functions.


For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Character Functions.”

Single Row Functions 3Ć9


3Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Character Functions continued

Example
Display the first and last name in lowercase, userid in initial capitalization, and title in
uppercase for all vice presidents.

SQL> SELECT LOWER(first_name||’ ’||last_name) VP,


2 INITCAP(userid) USERID,
3 UPPER(title) TITLE
4 FROM s_emp
5 WHERE title LIKE ’VP%’;

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

Single Row Functions 3Ć11


3Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Character Functions continued

Example
Display the first name and last name of all employees with the last name of Patel.

SQL> SELECT first_name, last_name


2 FROM s_emp
3 WHERE last_name = ’PATEL’;
no rows returned

SQL> SELECT first_name, last_name


2 FROM s_emp
3 WHERE UPPER(last_name) = ’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.

Single Row Functions 3Ć13


3Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Character Functions continued

Example
Display the name and country of all customers with a good credit rating. Concatenate
name and country.

SQL> SELECT CONCAT (name, country) CUSTOMER


2 FROM s_customer
3 WHERE credit_rating = ’GOOD’;

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.

SQL> SELECT name, LENGTH(name)


2 FROM s_product
3 WHERE SUBSTR(name,1,3) = ’Ace’;

NAME LENGTH(NAME)
-------------------- ------------
Ace Ski Boot 12
Ace Ski Pole 12

Single Row Functions 3Ć15


3Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Number Functions
Number functions accept numeric input and return numeric values. This section
describes some of the number functions.

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.

Note: This list is a subset of the available number functions.


For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Number Functions.”

Single Row Functions 3Ć17


3Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Number Functions continued

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.

SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),


2 ROUND(45.923,-1)
3 FROM SYS.DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)


--------------- --------------- ----------------
45.92 46 50

Example
Display the value 45.923 truncated to the hundredth, no, and ten decimal places.

SQL> SELECT TRUNC(45.923,2), TRUNC(45.923),


2 TRUNC(45.923,-1)
3 FROM SYS.DUAL;

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)


--------------- --------------- ----------------
45.92 45 40

SYS.DUAL is a dummy table. It will be covered in detail later in this lesson.

Single Row Functions 3Ć19


3Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Number Functions continued

Example
Calculate the remainder of the ratio of salary to commission for all employees whose
salary is more than 1400.

SQL> SELECT last_name, MOD(salary,commission_pct)


2 FROM s_emp
3 WHERE salary > 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.

Single Row Functions 3Ć21


3Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Oracle Date Format

Oracle Date Storage


Oracle stores dates in an internal numeric format, representing the following:
D Century
D Year
D Month
D Day
D Hours
D Minutes
D Seconds
The default display and input format for any date is DD-MON-YY. Valid Oracle dates
are between January 1, 4712 B.C. and December 31, 4712 A.D.

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.

SQL> SELECT SYSDATE


2 FROM SYS.DUAL;

Single Row Functions 3Ć23


3Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Using Arithmetic Operators with Dates
Since the database stores dates as numbers, you can perform calculations using
arithmetic operators such as addition and subtraction. You can add and subtract
number constants as well as dates.

Arithmetic Operations on Dates


You can perform the following operations:

Operation Result Description


date + number date Adds a number of days to a date.
date - number date Subtracts a number of days from a date.
date - date number of days Subtracts one date from another.
date + number/24 date Adds a number of hours to a date.

Example
For employees in department 43, display the last name and number of weeks
employed.

SQL> SELECT last_name, (SYSDATE-start_date)/7 WEEKS


2 FROM s_emp
3 WHERE dept_id = 43;

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.

Single Row Functions 3Ć25


3Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Date Functions

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.

For more information, see


Oracle7 Server SQL Reference, Release 7.3, “Date Functions.”

Single Row Functions 3Ć27


3Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Date Functions continued

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.

SQL> SELECT id, start_date,


2 MONTHS_BETWEEN (SYSDATE,start_date) TENURE,
3 ADD_MONTHS(start_date,6) REVIEW
4 FROM s_emp
5 WHERE MONTHS_BETWEEN (SYSDATE,start_date)<48;

ID START_DAT TENURE REVIEW


------ --------- ---------- ---------
9 09-FEB-92 44.1163486 09-AUG-92
12 18-JAN-92 44.826026 18-JUL-92
14 22-JAN-92 44.6969937 22-JUL-92
16 07-FEB-92 44.1808647 07-AUG-92

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.

SQL> SELECT product_id,


2 NEXT_DAY (restock_date,’FRIDAY’),
3 LAST_DAY (restock_date)
4 FROM s_inventory
5 WHERE restock_date IS NOT NULL
6 ORDER BY restock_date;

PRODUCT_ID NEXT_DAY( LAST_DAY(


---------- --------- ---------
30433 11-SEP-92 30-SEP-92
40422 12-FEB-93 28-FEB-93
50532 16-APR-93 30-APR-93

Single Row Functions 3Ć29


3Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Date Functions continued

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.

SQL> SELECT id, start_date,


2 ROUND(start_date, ’MONTH’),
3 TRUNC(start_date, ’MONTH’)
4 FROM s_emp
5 WHERE start_date LIKE ’%91’;

ID START_DAT ROUND(STA TRUNC(STA


------ --------- --------- ---------
3 17-JUN-91 01-JUL-91 01-JUN-91
6 18-JAN-91 01-FEB-91 01-JAN-91
10 27-FEB-91 01-MAR-91 01-FEB-91
13 18-FEB-91 01-MAR-91 01-FEB-91
15 09-OCT-91 01-OCT-91 01-OCT-91
18 09-FEB-91 01-FEB-91 01-FEB-91
19 06-AUG-91 01-AUG-91 01-AUG-91
20 21-JUL-91 01-AUG-91 01-JUL-91
21 26-MAY-91 01-JUN-91 01-MAY-91
24 17-MAR-91 01-APR-91 01-MAR-91
25 09-MAY-91 01-MAY-91 01-MAY-91

11 rows selected.

Single Row Functions 3Ć31


3Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Conversion Functions
SQL provides three functions to convert a value from one datatype to another.

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.”

Single Row Functions 3Ć33


3Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Date Formats

Displaying a Date in a Specific Format


Previously, all Oracle date values were displayed in the DD-MON-YY format. The
TO_CHAR function allows you to convert a date from this default format to one
specified by you.

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.

SQL> SELECT ID,TO_CHAR(date_ordered,’MM/YY’) ORDERED


2 FROM s_ord
3 WHERE sales_rep_id = 11;

ID ORDERED
------- -------------------
100 08/92
105 09/92
109 09/92
110 09/92
111 09/92

Single Row Functions 3Ć35


3Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Date Formats continued

Sample Valid Date Format Elements

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.

Single Row Functions 3Ć37


3Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Date Formats continued

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.

Using the FM Prefix


The FM prefix suppresses blank padding in month and day names, leaving a
variable-length result. It also suppresses leading zeros in numbers. A second
occurrence of FM turns blank padding on again.

Specifying Suffixes to Influence Number Display

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).

Single Row Functions 3Ć39


3Ć40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Date Formats continued

The RR Date Format Element


The RR date format is similar to the YY element, but it allows you to specify
different centuries. You can use the RR date format element instead of YY, so that the
century of the return value varies according to the specified two-digit year and the
last two digits of the current year. The table on the opposite page summarizes the
behavior of the RR element.

Current Year Given Date Interpreted (RR) Interpreted (YY)


1994 27-OCT-95 1995 1995
1994 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017

Single Row Functions 3Ć41


3Ć42 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Date Formats continued

Example
Display the names and hire dates for all employees hired in 1991. The hire date
should look like 7 of February 1991.

SQL> SELECT last_name, TO_CHAR(start_date,


2 ’fmDD ”of” Month YYYY’) HIREDATE
3 FROM s_emp
4 WHERE start_date LIKE ’%91’;

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.

SQL> SELECT last_name, TO_CHAR(start_date,


2 ’fmDdspth ”of” Month YYYY fmHH:MI:SS AM’)
3 HIREDATE
4 FROM s_emp
5 WHERE start_date LIKE ’%91’;

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
...

Single Row Functions 3Ć43


3Ć44 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Number Formats
When working with number values such as character strings, you should convert
those numbers to the character datatype using the TO_CHAR function, which
translates a value of NUMBER datatype to VARCHAR2 datatype. This technique is
especially useful with concatenation.

Number Format Elements


If you are converting a character datatype that converts digits into a number, you can
use the elements listed below.

Element Description Example Result


9 Numeric position (number of 9s 999999 1234
determine display width).
0 Display leading zeros. 099999 001234
$ Floating dollar sign. $999999 $1234
L Floating local currency symbol. L999999 FF1234
. Decimal point in position specified. 999999.99 1234.00
, Comma in position specified. 999,999 1,234
MI Minus signs to right (negative values). 999999MI 1234-
PR Parenthesize negative numbers. 999999PR <1234>
EEEE Scientific notation (format must 99.999EEEE 1.234E+03
specify four Es).
V Multiply by 10 n times (n=no of 9s 9999V99 123400
after V).
B Display zero values as blank, not 0. B9999.99 1234.00

Single Row Functions 3Ć45


3Ć46 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_CHAR Function with Number Formats continued

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.

SQL> SELECT ’Order ’||TO_CHAR(id)||


2 ’ was filled for a total of ’
3 ||TO_CHAR(total,’fm$9,999,999’)
4 FROM s_ord
5 WHERE date_shipped = ’21-SEP-92’;

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.

Single Row Functions 3Ć47


3Ć48 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
TO_NUMBER and TO_DATE Functions
You may want to convert a character string to either a number or a date format. To
accomplish this task, you use the TO_NUMBER or TO_DATE functions,
respectively. The format model you choose will be based on the previously
demonstrated format elements.

Example
Show all orders placed on September 7, 1992. Convert the date string you see here to
the date format.

SQL> SELECT id, total, date_ordered


2 FROM s_ord
3 WHERE date_ordered =
4 TO_DATE(’September 7, 1992’,’Month dd, YYYY’);

ID TOTAL DATE_ORDE
------ ---------- ---------
106 15634 07-SEP-92
107 142171 07-SEP-92
108 149570 07-SEP-92

Single Row Functions 3Ć49


Step 1 = Result 1

Step 2 = Result 2

Step 3 = Result 3

3Ć50 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Nesting Single Row Functions

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.

SQL> SELECT CONCAT(UPPER(last_name),


2 SUBSTR(title,3)) ”Vice Presidents”
3 FROM s_emp
4 WHERE title LIKE ’VP%’;

Vice Presidents
----------------------------------------------------
NGAO, Operations
NAGAYAMA, Sales
QUICK-TO-SEE, Finance
ROPEBURN, Administration

Single Row Functions 3Ć51


3Ć52 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Nesting Functions

Example
Display the head of the company, who has no manager. Display that there is no
manager number for that name.

SQL> SELECT last_name,


2 NVL(TO_CHAR(manager_id),’No Manager’)
3 FROM s_emp
4 WHERE manager_id IS NULL;

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.

SQL> SELECT TO_CHAR(NEXT_DAY(ADD_MONTHS


2 (date_ordered,6),’FRIDAY’),
3 ’fmDay, Month ddth, YYYY’)
4 ”New 6 Month Review”
5 FROM s_ord
6 ORDER BY date_ordered;

New 6 Month Review


----------------------------------
...
Friday, March 5th, 1993
Friday, March 5th, 1993
Friday, March 12th, 1993
...

Single Row Functions 3Ć53


3Ć54 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary

Single Row Functions


Single row functions can be nested to any level. Single row functions can manipulate
D Character data.
D LOWER, UPPER, INITCAP, CONCAT, SUBSTR, LENGTH
D Number data.
D ROUND, TRUNC, MOD
D Date data.
D MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY,
ROUND, TRUNC
D Date values can also use arithmetic operators
Conversion functions can convert character, date, and numeric values.
D TO_CHAR, TO_DATE, TO_NUMBER

SYSDATE and DUAL


SYSDATE is a date function that returns the current date and time. It is customary to
select SYSDATE from a dummy table called DUAL.

Single Row Functions 3Ć55


3Ć56 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice is designed to give you a variety of exercises using different functions
available for character, number, and date datatypes.

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.

Single Row Functions 3Ć57


3Ć58 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 3
1. Single row functions work on many rows to produce a single result.
True / False
2. You can use all of the arithmetic operators on date values.
True / False
3. What is the name of the function that holds the current date?

4. Display the employee number, last name, and salary increased by 15% and
expressed as a whole number.

ID LAST_NAME NEW SALARY


------ ------------ ------------------
1 Velasquez 2875
2 Ngao 1668
3 Nagayama 1610
4 Quick-To-See 1668
5 Ropeburn 1783
6 Urguhart 1380
7 Menchu 1438
8 Biri 1265
9 Catchpole 1495
10 Havel 1503
11 Magee 1610
12 Giljum 1714
13 Sedeghi 1742
14 Nguyen 1754
15 Dumas 1668
16 Maduro 1610
17 Smith 1081
18 Nozaki 1380
19 Patel 914
20 Newman 863
21 Markarian 978
22 Chang 920
23 Patel 914
24 Dancs 989
25 Schwartz 1265

25 rows selected.

Single Row Functions 3Ć59


Practice 3 continued

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.

3Ć60 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 continued

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.

LAST_NAME START_DAT REVIEW


------------ --------- ------------------------------
Velasquez 03-MAR-90 Tenth of September 1990
Ngao 08-MAR-90 Tenth of September 1990
Nagayama 17-JUN-91 Twenty-Third of December 1991
Quick-To-See 07-APR-90 Eighth of October 1990
Ropeburn 04-MAR-90 Tenth of September 1990
Urguhart 18-JAN-91 Twenty-Second of July 1991
Menchu 14-MAY-90 Nineteenth of November 1990
Biri 07-APR-90 Eighth of October 1990
Catchpole 09-FEB-92 Tenth of August 1992
Havel 27-FEB-91 Second of September 1991
Magee 14-MAY-90 Nineteenth of November 1990
Giljum 18-JAN-92 Twentieth of July 1992
Sedeghi 18-FEB-91 Nineteenth of August 1991
Nguyen 22-JAN-92 Twenty-Seventh of July 1992
Dumas 09-OCT-91 Thirteenth of April 1992
Maduro 07-FEB-92 Tenth of August 1992
Smith 08-MAR-90 Tenth of September 1990
Nozaki 09-FEB-91 Twelfth of August 1991
Patel 06-AUG-91 Tenth of February 1992
Newman 21-JUL-91 Twenty-Seventh of January 1992
Markarian 26-MAY-91 Second of December 1991
Chang 30-NOV-90 Third of June 1991
Patel 17-OCT-90 Twenty-Second of April 1991
Dancs 17-MAR-91 Twenty-Third of September 1991
Schwartz 09-MAY-91 Eleventh of November 1991

25 rows selected.

Single Row Functions 3Ć61


Practice 3 continued

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

3Ć62 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 continued

If you have time, complete the following exercises.


8. For each employee, calculate the number of months between today and the date
the employee was hired. Order your result by the number of months employed.
Round the number of months up to the closest whole number.

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.

Single Row Functions 3Ć63


Practice 3 continued

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.

LAST_NAME START_DAT DAY


------------ --------- ----------
Nagayama 17-JUN-91 MONDAY
Menchu 14-MAY-90 MONDAY
Sedeghi 18-FEB-91 MONDAY
Magee 14-MAY-90 MONDAY
Patel 06-AUG-91 TUESDAY
Havel 27-FEB-91 WEDNESDAY
Patel 17-OCT-90 WEDNESDAY
Nguyen 22-JAN-92 WEDNESDAY
Dumas 09-OCT-91 WEDNESDAY
Ngao 08-MAR-90 THURSDAY
Smith 08-MAR-90 THURSDAY
Schwartz 09-MAY-91 THURSDAY
Urguhart 18-JAN-91 FRIDAY
Chang 30-NOV-90 FRIDAY
Maduro 07-FEB-92 FRIDAY
Velasquez 03-MAR-90 SATURDAY
Quick-To-See 07-APR-90 SATURDAY
Biri 07-APR-90 SATURDAY
Nozaki 09-FEB-91 SATURDAY
Giljum 18-JAN-92 SATURDAY
Ropeburn 04-MAR-90 SUNDAY
Newman 21-JUL-91 SUNDAY
Dancs 17-MAR-91 SUNDAY
Markarian 26-MAY-91 SUNDAY
Catchpole 09-FEB-92 SUNDAY

25 rows selected.

3Ć64 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 continued

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.

Single Row Functions 3Ć65


3Ć66 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
4

Displaying Data from Multiple


Tables
4Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

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.

Displaying Data from Multiple Tables 4Ć3


4Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
When data from more than one table in the database is required, a join condition is
used. Rows in one table may be joined to rows in another table according to common
values existing in corresponding columns, that is to say primary and foreign key
columns.
There are two main types of join conditions:
D Equijoins
D Non-equijoins
Additional join methods include the following:
D Outer joins
D Self joins
D Set operators
For more information about set operators, attend
Advanced SQL and SQL*Plus course.

Displaying Data from Multiple Tables 4Ć5


4Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
What Is a Cartesian Product?
When a join condition is invalid or omitted completely, the result is a Cartesian
Product, in which all combinations of rows will be displayed. All rows in the first
table are joined to all rows in the second table.

And Why Should You Care?


A Cartesian product tends to generate a large number of rows, and its result is rarely
useful. You should always include a valid join condition in a WHERE clause, unless
you have a specific need to combine all rows from all tables.

SQL> SELECT name, last_name


2 FROM s_dept, s_emp;
...
300 rows selected.

Displaying Data from Multiple Tables 4Ć7


4Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Simple Join Query
To display data from two or more related tables, write a simple join condition in the
WHERE clause.

Syntax

SELECT table.column, table.column...


FROM table1, table2
WHERE table1.column1 = table2.column2;

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.”

Displaying Data from Multiple Tables 4Ć9


Server

ÉÉÉÉ

4Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Simple Join Query continued

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.

SQL> SELECT s_emp.last_name, s_emp.dept_id,


2 s_dept.name
3 FROM s_emp, s_dept
4 WHERE s_emp.dept_id = s_dept.id;

LAST_NAME DEPT_ID NAME


------------ ------- --------------------
Velasquez 50 Administration
Ngao 41 Operations
Nagayama 31 Sales
Quick-To-See 10 Finance
Ropeburn 50 Administration
Urguhart 41 Operations
Menchu 42 Operations
Biri 43 Operations
Catchpole 44 Operations
Havel 45 Operations
Magee 31 Sales
Giljum 32 Sales
Sedeghi 33 Sales
...

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.

Displaying Data from Multiple Tables 4Ć11


4Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Simple Join Query continued

Qualifying Ambiguous Column Names


You need to qualify the names of the columns in the WHERE clause with the table
name to avoid ambiguity. Without the table prefixes, the ID column could be from
either the S_DEPT or the S_EMP table. It is necessary to add the table prefix to
execute your query.
If there are no names that are the same between the two tables, then there is no need
to qualify the columns. However, you will gain improved performance by using the
table prefix.

Example
Display the department number, region number, and region name for all departments.

SQL> SELECT s_dept.id ”Department ID”,


2 s_region.id ”Region ID”,
3 s_region.name ”Region Name”
4 FROM s_dept, s_region
5 WHERE s_dept.region_id = s_region.id;

Department ID Region ID Region Name


------------- ---------- ---------------------------
10 3 Africa / Middle East
31 1 North America
32 2 South America
33 3 Africa / Middle East
34 4 Asia
35 5 Europe
41 1 North America
42 2 South America
43 3 Africa / Middle East
44 4 Asia
45 5 Europe
50 1 North America

12 rows selected.

The requirement to qualify ambiguous column names is also applicable to columns


that may be ambiguous in a SELECT or ORDER BY clause.

Displaying Data from Multiple Tables 4Ć13


Server

ÉÉ ÉÉ

4Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Simple Join Query continued

Additional Search Conditions


In addition to the join, you may have additional criteria for your WHERE clause.
Since the join is required to obtain the matches, you need to add your additional
conditions by using the AND operator. Table aliases help to keep SQL code smaller,
therefore using less memory.

Example
Display employee Menchu’s last name, department number, and department name.

SQL> SELECT s_emp.last_name, s_emp.dept_id,


2 s_dept.name
3 FROM s_emp, s_dept
4 WHERE s_emp.dept_id = s_dept.id
5 AND INITCAP(s_emp.last_name) = ’Menchu’;

LAST_NAME DEPT_ID NAME


------------ ------- --------------------
Menchu 42 Operations

Display the last name, region name, and commission percent of all employees who
earn a commission.

SQL> SELECT s_emp.last_name, s_region.name,


2 s_emp.commission_pct
3 FROM s_emp, s_dept, s_region
4 WHERE s_emp.dept_id = s_dept.id
5 AND s_dept.region_id = s_region.id
6 AND s_emp.commission_pct > 0;

LAST_NAME NAME COMMISSION_PCT


------------ -------------------- --------------
Magee North America 10
Giljum South America 12.5
Sedeghi Africa / Middle East 10
Nguyen Asia 15
Dumas Europe 17.5

Displaying Data from Multiple Tables 4Ć15


4Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Using Table Aliases
Qualifying column names with table names can be very time consuming, particularly
if table names are lengthy. Use table aliases instead. Like column aliases, table
aliases are a method of giving the table another name for the purpose of the SELECT
statement. Once you use the table alias, you must continue to qualify every column
reference with the table alias.

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.

SQL> SELECT c.name ”Customer Name”,


2 c.region_id ”Region ID”,
3 r.name ”Region Name”
4 FROM s_customer c, s_region r
5 WHERE c.region_id = r.id;

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.

Displaying Data from Multiple Tables 4Ć17


4Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
NonĆEquijoin
The relationship between the EMP and SALGRADE tables is a non-equijoin, in that
no column in EMP corresponds directly to a column in SALGRADE. The
relationship is obtained using an operator other than equal (=).

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.

SQL> SELECT e.ename, e.job, e.sal, s.grade


2 FROM emp e, salgrade s
3 WHERE e.sal BETWEEN s.losal AND s.hisal;

ENAME JOB SAL GRADE


---------- --------- ---------- ----------
SMITH CLERK 800.00 1
ADAMS CLERK 1,100.00 1
JAMES CLERK 950.00 1
WARD SALESMAN 1,250.00 2
MARTIN SALESMAN 1,250.00 2
MILLER CLERK 1,300.00 2
ALLEN SALESMAN 1,600.00 3
TURNER SALESMAN 1,500.00 3
JONES MANAGER 2,975.00 4
BLAKE MANAGER 2,850.00 4
CLARK MANAGER 2,450.00 4
SCOTT ANALYST 3,000.00 4
FORD ANALYST 3,000.00 4
KING PRESIDENT 5,000.00 5

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.

Displaying Data from Multiple Tables 4Ć19


4Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Returning Records with No Direct Match
If a row does not satisfy a join condition, then the row will not appear in the query
result. For example, in the equijoin condition of S_EMP and S_CUSTOMER, Sweet
Rock Sports does not appear because there is no sales representative for that
customer.

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

SELECT table.column, table.column


FROM table1, table2
WHERE table1.column = table2.column(+);

or

SELECT table.column, table.column


FROM table1, table2
WHERE table1.column(+) = table2.column;

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.

Displaying Data from Multiple Tables 4Ć21


Server

ÉÉ É

4Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Returning Records with No Direct Match continued

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.

SQL> SELECT e.last_name, e.id, c.name


2 FROM s_emp e, s_customer c
3 WHERE e.id (+) = c.sales_rep_id
4 ORDER BY e.id;

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.

Outer Join Restrictions


D The outer join operator can only appear on one side of the expression—the side
that has information missing. It returns those rows from one table which have no
direct match in the other table.
D A condition involving an outer join may not use the IN operator or be linked to
another condition by the OR operator.

Displaying Data from Multiple Tables 4Ć23


Server

ÉÉ É

4Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Joining a Table to Itself
You can join a table to itself by using table aliases to simulate as if the table were two
separate tables. This allows rows in a table to be joined to rows in the same table.

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.

SQL> SELECT worker.last_name||’ works for ’||


2 manager.last_name
3 FROM s_emp worker, s_emp manager
4 WHERE worker.manager_id = manager.id;

Ngao works for Velasquez


Nagayama works for Velasquez
Quick-To-See works for Velasquez
Ropeburn works for Velasquez
Urguhart works for Ngao
Menchu works for Ngao
Biri works for Ngao
Catchpole works for Ngao
Havel works for Ngao
Magee works for Nagayama
Giljum works for Nagayama
Sedeghi works for Nagayama
Nguyen works for Nagayama
Dumas works for Nagayama
...
24 rows selected.

Displaying Data from Multiple Tables 4Ć25


4Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
There are multiple ways to join tables. The common thread, though, is that you want
to link them through a condition in the WHERE clause. The method you choose will
be based on the required result and the data structures you are using.

Syntax

SELECT table.column, table.column...


FROM table1, table2
WHERE table1.column1 = table2.column2;

where: table.column denotes a table and column from which data is


retrieved.
table1.column1 = is the condition that joins (or relates)
table2.column2 the tables together.

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.

Displaying Data from Multiple Tables 4Ć27


4Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice is intended to give you practical experience extracting data from more
than one table. You will be required to join and restrict rows in the WHERE clause.

Practice Contents
D Joining tables using an equijoin
D Performing outer and self joins
D Adding additional conditions

Displaying Data from Multiple Tables 4Ć29


4Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice 4
Use the S_EMP, S_DEPT, S_CUSTOMER, S_REGION, S_ORD, S_ITEM, and
S_PRODUCT tables to complete the following exercises.
1. Write a report containing each employee’s last name, department number, and
name of their department.

LAST_NAME DEPT_ID NAME


------------ ------- --------------------
Velasquez 50 Administration
Ngao 41 Operations
Nagayama 31 Sales
Quick-To-See 10 Finance
Ropeburn 50 Administration
Urguhart 41 Operations
Menchu 42 Operations
Biri 43 Operations
Catchpole 44 Operations
Havel 45 Operations
Magee 31 Sales
Giljum 32 Sales
Sedeghi 33 Sales
Nguyen 34 Sales
Dumas 35 Sales
Maduro 41 Operations
Smith 41 Operations
Nozaki 42 Operations
Patel 42 Operations
Newman 43 Operations
Markarian 43 Operations
Chang 44 Operations
Patel 34 Sales
Dancs 45 Operations
Schwartz 45 Operations

25 rows selected.

Displaying Data from Multiple Tables 4Ć31


Practice 4 continued

2. Write a query to display the last name, department name, and region name of all
employees who earn a commission.

LAST_NAME NAME NAME


------------ -------------- --------------------
Magee Sales North America
Giljum Sales South America
Sedeghi Sales Africa / Middle East
Nguyen Sales Asia
Dumas Sales Europe

3. Display the employee name and department name for Smith.

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.

4Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 continued

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.

Displaying Data from Multiple Tables 4Ć33


Practice 4 continued

If you have time, complete the following exercises.


6. Display the customer number, customer name, and order number of all customers
and their orders. Display the customer number and name, even if they have not
placed an order.

Customer ID Customer Name Order ID


----------- ------------------------------ ----------
201 Unisports 97
202 Simms Atheletics 98
203 Delhi Sports 99
204 Womansport 100
204 Womansport 111
205 Kam’s Sporting Goods 101
206 Sportique 102
207 Sweet Rock Sports
208 Muench Sports 103
208 Muench Sports 104
209 Beisbol Si! 105
210 Futbol Sonora 106
210 Futbol Sonora 112
211 Kuhn’s Sports 107
212 Hamada Sport 108
213 Big John’s Sports Emporium 109
214 Ojibway Retail 110
215 Sporta Russia

18 rows selected.

4Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 continued

7. Display all employees by last name name and employee number along with their
manager’s last name and manager number.

EMP_NAME EMP_ID MGR_NAME MGR_ID


---------–––––– ––––––– ––––––––––––– –––––––
Ngao 2 Velasquez 1
Nagayama 3 Velasquez 1
Quick-To-See 4 Velasquez 1
Ropeburn 5 Velasquez 1
Urguhart 6 Ngao 2
Menchu 7 Ngao 2
Biri 8 Ngao 2
Catchpole 9 Ngao 2
Havel 1O Ngao 2
Magee 11 Nagayama 3
Giljum 12 Nagayama 3
Sedeghi 13 Nagayama 3
Nguyen 14 Nagayama 3
Dumas 15 Nagayama 3
Maduro 16 Urguhart 6
Smith 17 Urguhart 6
Nozaki 18 Menchu 7
Patel 19 Menchu 7
Newman 20 Biri 8
Markarian 21 Biri 8
Chang 22 Catchpole 9
Patel 23 Catchpole 9
Dancs 24 Havel 10
Schwartz 25 Havel 10

24 rows selected.

Displaying Data from Multiple Tables 4Ć35


Practice 4 continued

8. Modify the solution to exercise 7 to also display Velasquez, who has no manager.

Employee Name Employee ID Manager Name Manager_ID


---------–––––––––––––––––– ––––––––––––– ––––––––––
Velasquez 1
Ngao 2 Velasquez 1
Nagayama 3 Velasquez 1
Quick-To-See 4 Velasquez 1
Ropeburn 5 Velasquez 1
Urguhart 6 Ngao 2
Menchu 7 Ngao 2
Biri 8 Ngao 2
Catchpole 9 Ngao 2
Havel 10 Ngao 2
Magee 11 Nagayama 3
Giljum 12 Nagayama 3
Sedeghi 13 Nagayama 3
Nguyen 14 Nagayama 3
Dumas 15 Nagayama 3
Maduro 16 Urguhart 6
Nozaki 18 Menchu 7
Markarian 21 Biri 8
Patel 23 Catchpole 9
Smith 17 Urguhart 6
Patel 19 Menchu 7
Newman 20 Biri 8
Chang 22 Catchpole 9
Dancs 24 Havel 10
Schwartz 25 Havel 10

25 rows selected.

4Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 continued

9. Display all customers and the products and quantities they ordered for those
customers whose order totaled more than 100,000.

Customer PRODUCT_ID QUANTITY


---------------------- –––––––––– ––––––––
Womansport 10011 500
Womansport 10013 400
Womansport 10021 500
Womansport 30326 600
Womansport 41010 250
Womansport 30433 450
Womansport 10023 400
Kuhn’s Sports 20106 50
Kuhn’s Sports 20201 130
Kuhn’s Sports 30421 55
Kuhn’s Sports 30321 75
Kuhn’s Sports 20108 22
Hamada Sport 20510 9
Hamada Sport 41080 50
Hamada Sport 41100 42
Hamada Sport 32861 57
Hamada Sport 20512 18
Hamada Sport 32779 60
Hamada Sport 30321 85
Big John’s Sports Emporium 10011 150
Big John’s Sports Emporium 30426 500
Big John’s Sports Emporium 50418 43
Big John’s Sports Emporium 32861 50
Big John’s Sports Emporium 30326 1500
Big John’s Sports Emporium 10012 600
Big John’s Sports Emporium 10022 300

26 rows selected.

Displaying Data from Multiple Tables 4Ć37


4Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
5

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 5Ć3


5Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Overview
Unlike single row functions, group functions operate on sets of rows to give one
result per group. These sets may be the whole table or the table split into groups.
Group functions appear in both SELECT lists and HAVING clauses.

Group Functions
D AVG
D COUNT
D MAX
D MIN
D STDDEV
D SUM
D VARIANCE

GROUP BY and HAVING Clauses in the SELECT Statement


By default, all the rows in a table are treated as one group. Use the GROUP BY
clause in the SELECT statement to divide rows into smaller groups. Additionally, to
restrict the result groups returned, use the HAVING clause.

Syntax

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

where: group_by_expression specifies columns whose values determine the


basis for grouping rows.
group_condition restricts the groups of rows returned to those
groups for which the specified condition is
TRUE.

Group Functions 5Ć5


5Ć6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Group Functions
Each of the functions accepts an argument. The following table identifies the options
you can use in the 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.

Group Functions 5Ć7


5Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Group Functions continued

Example
Display the average, highest, lowest, and sum of the monthly salaries for all sales
representatives.

SQL> SELECT AVG(salary), MAX(salary), MIN(salary),


2 SUM(salary)
3 FROM s_emp
4 WHERE UPPER(title) LIKE ’SALES%’;

AVG(SALARY) MAX(SALARY) MIN(SALARY) SUM(SALARY)


----------- ----------- ----------- -----------
1476 1525 1400 7380

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.

SQL> SELECT MIN(last_name), MAX(last_name)


2 FROM s_emp;

MIN(LAST_NAME) MAX(LAST_NAME)
------------------------- -------------------------
Biri Velasquez

Note: You can use MAX and MIN functions for any datatype.

Group Functions 5Ć9


5Ć10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Group Functions continued

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.

SQL> SELECT COUNT(*)


2 FROM s_emp
3 WHERE dept_id = 31;

COUNT(*)
----------
2

In contrast, COUNT(expr) returns the number of non-null rows in the column


identified by expr.

Example
Display the number of employees in department 31 who can earn a commission.

SQL> SELECT COUNT(commission_pct)


2 FROM s_emp
3 WHERE dept_id = 31;

COUNT(COMMISSION_PCT)
---------------------
1

Group Functions 5Ć11


5Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The GROUP BY Clause
You use the GROUP BY clause to divide the rows in a table into smaller groups. You
can then use the group functions to return summary information for each group.

Syntax

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

where: group_by_expression specifies columns whose values determine the


basis for grouping rows.

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.

Group Functions 5Ć13


5Ć14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The GROUP BY Clause continued

Example
Display each possible customer credit rating and the number of customers in each
credit rating category. Label the column # Cust.

SQL> SELECT credit_rating, COUNT(*) ”# Cust”


2 FROM s_customer
3 GROUP BY credit_rating;

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.

SQL> SELECT title, SUM(salary) PAYROLL


2 FROM s_emp
3 WHERE title NOT LIKE ’VP%’
4 GROUP BY title
5 ORDER BY SUM(salary);

TITLE PAYROLL
--------------------- ----------
President 2500
Warehouse Manager 6157
Sales Representative 7380
Stock Clerk 9490

Group Functions 5Ć15


5Ć16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The GROUP BY Clause continued

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.

SQL> SELECT MAX(salary)


2 FROM s_emp
3 GROUP BY title;

MAX(SALARY)
-----------
2500
1525
1400
...

8 rows selected.

Example
Display the maximum salary for each title group and display the title.

SQL> SELECT title, MAX(salary)


2 FROM s_emp
3 GROUP BY title;

TITLE MAX(SALARY)
--------------------- -----------
President 2500
Sales Representative 1525
Stock Clerk 1400
...

8 rows selected.

Group Functions 5Ć17


5Ć18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Illegal Queries Using Group Functions
Whenever you use a mixture of individual items (REGION_ID) and group functions
(COUNT) in the same SELECT statement, you must include a GROUP BY clause
that specifies the individual items (in this case, REGION_ID). If the GROUP BY
clause is missing, then the error message “not a single-group group function” would
appear and an asterisk (*) would point to the offending column.

Example
Display each region and the number of departments in that region.

SQL> SELECT region_id, COUNT(name)


2 FROM s_dept;
SELECT region_id, COUNT(name)
*
ERROR at line 1:
ORA-00937: not a single-group group function

Correct the above error by adding the GROUP BY clause. Now, REGION_ID is the
name of a group.

SQL> SELECT region_id, COUNT(name)


2 FROM s_dept
3 GROUP BY region_id;

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.

Group Functions 5Ć19


5Ć20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Illegal Queries Using Group Functions continued

The WHERE clause cannot be used to restrict groups.

Example
Display the department number and average salary for those departments that have an
average salary more than 2000.

SQL> SELECT dept_id, AVG(salary)


2 FROM s_emp
3 WHERE AVG(salary) > 2000
4 GROUP BY dept_id;
WHERE AVG(salary) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed here

Instead, use the HAVING clause to limit those rows.

SQL> SELECT dept_id, AVG(salary)


2 FROM s_emp
3 GROUP BY dept_id
4 HAVING AVG(salary) > 2000;

DEPT_ID AVG(SALARY)
------- -----------
50 2025

Group Functions 5Ć21


5Ć22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Groups Within Groups
You can return summary results for groups and subgroups by listing more than one
GROUP BY column. In the example, you count the number of people not only within
the department, but also by the job category. The order in which the columns are
listed in the GROUP BY clause determines the default sort order.
Example
Display the number of employees for each job category within each department.

SQL> SELECT dept_id, title, COUNT(*)


2 FROM s_emp
3 GROUP BY dept_id, title;

DEPT_ID TITLE COUNT(*)


------- --------------------- ----------
...
34 Sales Representative 1
34 Stock Clerk 1
35 Sales Representative 1
41 Stock Clerk 2
41 VP, Operations 1
...

Example
Display the number of employees for each department within each job category.

SQL> SELECT title, dept_id, COUNT(*)


2 FROM s_emp
3 GROUP BY title, dept_id;

TITLE DEPT_ID COUNT(*)


--------------------- ------- ----------
...
Sales Representative 34 1
Sales Representative 35 1
Stock Clerk 34 1
...

Group Functions 5Ć23


5Ć24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The HAVING Clause
You use the HAVING clause to specify which groups are to be displayed. Therefore,
you further restrict the groups on the basis of aggregate information.

Syntax

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

where: group_condition restricts the groups of rows returned to those


groups for which the specified condition is
TRUE.
The Oracle7 Server performs the following steps when you use the HAVING clause:
D Rows are grouped.
D The group function is applied.
D The groups that match the criteria in the HAVING clause are displayed.
The HAVING clause may precede the GROUP BY clause, but it is recommended that
you place the GROUP BY clause first because it is more logical. Groups are formed
and group functions are calculated before the HAVING clause is applied to the groups
in the SELECT list.

Group Functions 5Ć25


5Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The HAVING Clause continued

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.

SQL> SELECT title, SUM(salary) PAYROLL


2 FROM s_emp
3 WHERE title NOT LIKE ’VP%’
4 GROUP BY title
5 HAVING SUM(salary) > 5000
6 ORDER BY SUM(salary);

TITLE PAYROLL
--------------------- ----------
Warehouse Manager 6157
Sales Representative 7380
Stock Clerk 9490

Group Functions 5Ć27


5Ć28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
The HAVING Clause continued

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.

SQL> SELECT dept_id


2 FROM s_emp
3 GROUP BY dept_id
4 HAVING SUM(salary) > 4000;

DEPT_ID
-------
41
50

Group Functions 5Ć29


5Ć30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
There are seven group functions available in SQL:
D AVG
D COUNT
D MAX
D MIN
D STDDEV
D SUM
D VARIANCE

Syntax

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

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.

Group Functions 5Ć31


5Ć32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
At the end of this practice, you should be familiar with using group functions and
selecting groups of data.

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.

Group Functions 5Ć33


Practice 5
1. Determine the validity of the following statements. Circle either True or False.
a. Group functions work across many rows to produce one result.
True / False
b. Group functions include nulls in calculations.
True / False
c.Use the HAVING clause to exclude rows from a group calculation.
True / False
d. Use the HAVING clause to exclude groups of rows from the display.
True / False
2. Display the highest and lowest order totals in the S_ORD table. Label the
columns Highest and Lowest, respectively.

Highest Lowest
---------- ----------
1020935 377

3. Write a query to display the minimum and maximum salary for each job type
ordered alphabetically.

JOB MAXIMUM MINIMUM


------------------------- ---------- ----------
President 2500 2500
Sales Representative 1525 1400
Stock Clerk 1400 750
VP, Administration 1550 1550
VP, Finance 1450 1450
VP, Operations 1450 1450
VP, Sales 1400 1400
Warehouse Manager 1307 1100

8 rows selected.

4. Determine the number of managers without listing them.

Number of Managers
------------------
8

5Ć34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 5 continued

5. Display the number of line items in each order under each order number, labeled
Number of Items.

ORD_ID NUMBER OF ITEMS


---------- ---------------
97 2
98 1
99 4
100 7
101 7
102 2
103 2
104 4
105 3
106 6
107 5
108 7
109 7
110 2
111 2
112 1

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.

MANAGER_ID LOWEST PAID EMPLOYEE


–––––––––– –––––––––––––––––––––
2 1100
1 1400
3 1400
2500

Group Functions 5Ć35


Practice 5 continued

7. What is the difference between the highest and lowest salaries?

DIFFERENCE
----------
1750

If you have time, complete the following exercises.


8. Display the product number and number of times it was ordered, labeled Times
Ordered. Only show those products that have been ordered at least three times.
Order the data by the number of products ordered.

PRODUCT_ID TIMES ORDERED


---------- --------------
20106 3
20108 3
20201 3
20510 3
50273 3
30421 3
20512 3
30321 4

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

5Ć36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 5 continued

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.

ORD_ID TOTAL ITEM COUNT


---------- -----------------
97 1050
99 165
100 3100
101 217
102 145
106 392
107 332
108 321
109 3143

9 rows selected.

11. Display the customer name and the number of orders for each customer.

NAME NUMBER OF ORDERS


-------------------------------- -----------------
Beisbol Si! 1
Big John’s Sports Emporium 1
Delhi Sports 1
Futbol Sonora 2
Hamada Sport 1
Kam’s Sporting Goods 1
Kuhn’s Sports 1
Muench Sports 2
Simms Athletics 1
Ojibway Retail 1
Sportique 1
Unisports 2
Womansport 2

13 rows selected.

Group Functions 5Ć37


5Ć38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
6

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

ÉÉ
ÉÉÉÉ
ÉÉ

6Ć4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Overview
A subquery is a SELECT statement that is embedded in a clause of another SQL
statement.You can build powerful commands out of simple ones by using subqueries.
They can be very useful when you need to select rows from a table with a condition
that depends on the data in the table itself.
You can place the subquery in a number of SQL command clauses:
D WHERE clause
D HAVING clause
D FROM clause of a SELECT or DELETE statement

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);

where: operator includes a comparison operator such as >, =, or


IN.
Note: Comparison operators fall into two classes: single row (>, =, >=, <, <>, <=)
and multiple row (IN, NOT IN) operators.
The subquery is often referred to as a nested SELECT, sub-SELECT, or inner
SELECT statement. The subquery generally executes first, and its output is used to
complete the query condition for the main or outer query.

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

6Ć8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


How Are Nested Subqueries Processed?
A SELECT statement can be considered as a query block. This example consists of
two query blocks: the main query and the inner query.

Example
Retrieve the last name and title of the employees in the same department as Biri.

SQL> SELECT last_name, title


2 FROM s_emp
3 WHERE dept_id =
4 (SELECT dept_id
5 FROM s_emp
6 WHERE UPPER(last_name)=’BIRI’);

1. The nested SELECT statement or query block is executed first, producing a query
result: 43.

SQL> SELECT dept_id


2 FROM s_emp
3 WHERE UPPER(last_name)=’BIRI’;

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:

SQL> SELECT last_name, title


2 FROM s_emp
3 WHERE dept_id = 43;

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.

SQL> SELECT last_name, title


2 FROM s_emp
3 WHERE title =
4 (SELECT title
5 FROM s_emp
6 WHERE last_name = ’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:

=, >, <, >=, or <=.

Subqueries 6Ć11
Server

ÉÉÉÉ

6Ć12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Single Row Subqueries continued

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.

SQL> SELECT last_name, title, salary


2 FROM s_emp
3 WHERE salary <
4 (SELECT AVG(salary)
5 FROM s_emp);

LAST_NAME TITLE SALARY


------------------- --------------------- -----------
Urguhart Warehouse Manager 1200
Menchu Warehouse Manager 1250
Biri Warehouse Manager 1100
Smith Stock Clerk 940
Nozaki Stock Clerk 1200
Patel Stock Clerk 795
Newman Stock Clerk 750
Markarian Stock Clerk 850
Chang Stock Clerk 800
Patel Stock Clerk 795
Dancs Stock Clerk 860
Schwartz Stock Clerk 1100

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.

SQL> SELECT last_name, first_name, title


2 FROM s_emp
3 WHERE dept_in =
4 (SELECT ID
5 FROM s_dept
6 WHERE name = ’Finance’
7 OR region_id = 2);

ORA-1427: single-row subquery returns more than


one row

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.

SQL> SELECT last_name, first_name, title


2 FROM s_emp
3 WHERE dept_in IN
4 (SELECT ID
5 FROM s_dept
6 WHERE name = ’Finance’
7 OR region_id = 2);

LAST_NAME FIRST_NAME TITLE


––––––––––––– ––––––––––– –––––––––––––––––––
Quick–To–See Mark VP, Finance
Menchu Roberta Warehouse Manager
Giljum Henry Sales Representative
Nozaki Akira Stock Clerk
Patel Vikram Stock Clerk

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.

SQL> SELECT dept_id, AVG(salary)


2 FROM s_emp
3 GROUP BY dept_id
4 HAVING AVG(salary) >
5 (SELECT AVG(salary)
6 FROM s_emp
7 WHERE dept_id = 32);

DEPT_ID AVG(SALARY)
------- -----------
33 1515
50 2025

Example
Find the job with the lowest average salary.

SQL> SELECT title, AVG(salary)


2 FROM s_emp
3 GROUP BY title
4 HAVING AVG(salary) =
5 (SELECT MIN(AVG(salary))
6 FROM s_emp
7 GROUP BY title);

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?

b. How many times does the first query run?

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?

ii. If the answer is False, why?

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

If you have time, complete the following exercises.


8. Display the name and short description for any product that did not appear on an
order in the month of September, 1992.
9. Display the customer name and credit rating for all customers of sales
representative Andre Dumas.
10. Display each sales representative’s last name in region 1 and region 2, their
customers’ names and each customer’s total sales orders.

6Ć26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

You might also like