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 Neena Kochhar Debby Kramer

Copyright E Oracle Corporation, 1992, 1996. All rights reserved. This documentation contains proprietary information of Oracle Corporation; it is provided under a license agreement containing restrictions on use and disclo 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: Restricted Rights Legend Use, duplication or disclosure by the Government is subject to restrictions for 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 252.227 7013, Rights in Technical Data and Computer Software (October 1988). 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 group of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties. If this documentation is delivered to a U.S. Government Agency not within the De partment of Defense, then it is delivered with Restricted Rights," as defined in FAR 52.227 14, Rights in Data General, including Alternate III (June 1987). The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Worldwide Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, Red wood Shores, CA 94065. Oracle Corporation does not warrant that this document is error free. SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle Server, Discoverer/2000, and Designer/2000 are trademarks or registered trade marks of Oracle Corporation. All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Technical Contributors and Reviewers Christian Bauwens Debra Bowman Lenny Brunson Jackie Collins Ralf Durben Brian Fry Anthony Holbrook Karlene Jensen Sarah Jones Glenn Maslen Sundar Nagarathnam Sandra Schrick Ulrike Schwinn Rosemarie Truman Jenny Tsai Laura Van Deusen

Publishers Stephanie Jones Kimberly Lee Jennifer Robertson Mark Turangan

Contents
Volume 1
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Related Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typographic Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Course Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Course Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Relational Database Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System Development Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is Oracle? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Oracle Product Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL, SQL*Plus, and PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summit Sporting Goods Demonstration Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1. Selecting Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Basic Query Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arithmetic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Column Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Concatenation Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Literal Character String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Managing Null Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preventing the Selection of Duplicate Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL*Plus Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Logging in to SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Displaying Table Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL*Plus Editing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL*Plus File Commands and Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. Limiting Selected Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ordering Rows with the ORDER BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limiting Selected Rows with the WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi xii xviii xix I1 I3 I5 I9 I 17 I 19 I 21 I 23 I 29 I 33 11 13 15 1 13 1 21 1 23 1 25 1 27 1 31 1 35 1 37 1 39 1 41 1 43 1 45 1 51 1 53 1 55 21 23 25 2 11 2 13

iii

Negating Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Querying Data with Multiple Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rules of Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3. Single Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Single Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Character Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Number Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Oracle Date Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Arithmetic Operators with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Date Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TO_CHAR Function with Date Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TO_CHAR Function with Number Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TO_NUMBER and TO_DATE Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Nesting Single Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Nesting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. Displaying Data from Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is a Cartesian Product? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Simple Join Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Table Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Non Equijoin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Returning Records with No Direct Match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Joining a Table to Itself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. Group Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Group Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2 2 2 2 2 2 2

17 19 27 29 33 35 37

31 33 35 37 39 3 17 3 23 3 25 3 27 3 33 3 35 3 45 3 49 3 51 3 53 3 55 3 57 3 59 41 43 45 47 49 4 17 4 19 4 21 4 25 4 27 4 29 4 31 51 53 55 57

iv

The GROUP BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Illegal Queries Using Group Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Groups Within Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How Are Nested Subqueries Processed? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Single Row Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Errors with Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Multiple Row Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HAVING Clause with Nested Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5 5 5 5 5 5 5

13 19 23 25 31 33 34

61 63 65 67 69 6 11 6 15 6 17 6 19 6 21 6 23 6 25

Volume 2
7. Specifying Variables at Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Substitution Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Single Ampersand Substitution Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining User Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Passing Values into a Script File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. Overview of Data Modeling and Database Design . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System Development Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Database Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entity Relationship Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entity Relationship Model Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Integrity Constraints and Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Designing the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 73 75 77 79 7 15 7 21 7 23 7 25 7 26 81 83 85 87 89 8 11 8 13 8 15 8 23 8 29 8 39

v

9. Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Oracle7 Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Table from a Table Instance Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Table from Rows in Another Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Confirming Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. Oracle Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Querying the Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Checking Constraints on a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11. Manipulating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding a New Row to a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying Rows from Another Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Updating Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deleting Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transaction Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Committing Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rolling Back Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rolling Back Changes to a Savepoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Statement Level Rollback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. Altering Tables and Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding a Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modifying a Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding and Dropping a Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

91 93 95 97 9 13 9 15 9 25 9 31 9 33 9 35 9 37 9 39 10 1 10 3 10 5 10 7 10 13 10 17 10 19 10 21 11 1 11 3 11 5 11 7 11 19 11 21 11 29 11 35 11 39 11 43 11 45 11 47 11 49 11 51 11 53 12 1 12 3 12 5 12 7 12 9 12 11

vi

Disabling and Enabling a Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dropping a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Renaming and Truncating a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding a Comment to a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13. Creating Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Altering a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Removing a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Performing DML Operations on a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Confirming View Names and Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Removing a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15. Creating Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . When Is the Index Used? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Index Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating an Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Confirming Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Removing an Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. Controlling User Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12 12 12 12 12 12 12

15 17 19 21 23 25 27

13 1 13 3 13 5 13 7 13 13 13 17 13 19 13 21 13 23 13 25 14 1 14 3 14 5 14 7 14 15 14 21 14 23 14 25 14 27 14 29 15 1 15 3 15 5 15 7 15 9 15 13 15 17 15 19 15 21 15 23 15 25 16 1 16 3 16 5

vii

System Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is a Role? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing Your Password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Granting Object Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Confirming Privileges Granted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Revoking Object Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Synonym for an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. Summary of SQL and SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary of SQL and SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16 7 16 11 16 13 16 15 16 21 16 23 16 25 16 29 16 31 16 33 17 1 17 3 17 9 17 11

Volume 3
18. Overview of PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PL/SQL Block Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The PL/SQL Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About Procedure Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19. Basics of Procedure Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Oracle Procedure Builder Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Procedure Builder Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Object Navigator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Program Unit Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Stored Program Unit Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging a Stored Program Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Performing Debug Actions in the Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting a Breakpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Examining Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20. Modularizing Programming with Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1 18 3 18 5 18 9 18 15 18 17 19 1 19 3 19 5 19 7 19 9 19 15 19 23 19 27 19 31 19 33 19 35 19 37 19 43 19 45 19 47 19 49 20 1 20 3 20 5

viii

Creating a Subprogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparing Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Invoking Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21. Developing a Simple PL/SQL Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring PL/SQL Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring Scalar Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring Composite Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PL/SQL Block Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Assigning Values to Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Programming Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 21 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22. Interacting with Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Retrieving Data Using PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SELECT Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Manipulating Data Using PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23. Controlling Flow in PL/SQL Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The IF Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Building Logical Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loop Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

20 7 20 9 20 15 20 17 20 21 20 29 20 31 20 33 21 1 21 3 21 5 21 7 21 9 21 15 21 25 21 29 21 43 21 49 21 51 21 53 22 1 22 3 22 5 22 7 22 15 22 19 22 23 22 27 22 31 22 33 22 35 23 1 23 3 23 5 23 7 23 13 23 17 23 29 23 31 23 33

ix

24. Processing Queries by Using Explicit Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling Explicit Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Explicit Cursor Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cursors and Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cursors with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cursor FOR Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Applying the WHERE CURRENT OF Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25. Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Trapping Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Trapping Predefined Oracle7 Server Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . Trapping Non Predefined Oracle7 Server Exceptions . . . . . . . . . . . . . . . . . . . . . . . . Trapping User Defined Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Error Trapping Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Propagating Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 25 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26. Summary of PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 26 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

24 1 24 3 24 5 24 7 24 17 24 21 24 23 24 25 24 27 24 29 24 31 24 33 25 1 25 3 25 5 25 7 25 9 25 11 25 15 25 17 25 19 25 21 25 23 25 25 25 27 26 1 26 3 26 9 26 11

Volume 4
A Practice Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 1 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 2 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 3 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 4 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 5 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 6 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 7 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 9 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 10 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A1 A3 A4 A8 A 20 A 29 A 39 A 46 A 55 A 59 A 63

x

Practice 11 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 12 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 13 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 14 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 15 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 16 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 17 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 19 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 20 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 21 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 22 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 23 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 24 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 25 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice 26 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B Table Descriptions and Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summit Sporting Goods Database Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_CUSTOMER Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_DEPT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_EMP Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_IMAGE Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_INVENTORY Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_ITEM Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_ORD Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_PRODUCT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_REGION Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S_WAREHOUSE Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C Using SQL*Plus to Create Reports and Manage PL/SQL Code . . . . . . . . . . . . Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entering Commands in SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparison of SQL and SQL*Plus Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL*Plus SET Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Declaring and Creating PL/SQL Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entering Commands in SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Passing Input and Output Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging in SQL*Plus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Displaying Contents of a Subprogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Executing Stored Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A 68 A 82 A 88 A 97 A 105 A 109 A 116 A 154 A 155 A 158 A 163 A 170 A 177 A 186 A 192 B1 B3 B4 B7 B8 B 10 B 11 B 16 B 20 B 22 B 25 B 26 C1 C3 C5 C7 C9 C 11 C 15 C 23 C 25 C 27 C 31 C 35 C 37 C 41 C 43

xi

Practice C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice C Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . D Related Products and Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Related Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Related Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary Index

C 45 C 47 D1 D3 D5

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 Lesson 1: Selecting Rows Aim 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
Lesson Lesson 3: Single Row Functions Aim

continued

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. 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. You can create a command file 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.

Lesson 6: Subqueries

Lesson 7: Specifying Variables at Runtime

Preface

xv

Profile
Lesson Lesson 8: Overview of Data Modeling and Database Design Aim

continued

Before you build your tables, you 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. You will create tables. You will also build integrity constraints, which are rules governing what can and cannot be done with the data. 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. 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. After you create your tables, you may need to change the table structures because you omitted a column, your column definition needs to be changed, or you want to enable or disable constraints. This lesson will demonstrate how you can amend table structures as well as add and remove constraints.

Lesson 9: Creating Tables

Lesson 10: Oracle Data Dictionary

Lesson 11: Manipulating Data

Lesson 12: Altering Tables and Constraints

xvi

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

Profile
Lesson Lesson 13: Creating Sequences Aim

continued

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

Lesson 14: Creating Views

Lesson 15: Creating Indexes

Lesson 16: Controlling User Access

Preface

xvii

Profile
Lesson Lesson 17: Summary of SQL and SQL*Plus (optional) Lesson 18: Overview of PL/SQL Aim

continued

This lesson reviews the basic commands covered in the course so far. Overview lesson of how to create and use PL/SQL program units and subprograms using Oracle 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. Modularity allows you to break your 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. Create a simple PL/SQL block after learning the various elements that compose a block. Access the database and control transactions through SQL statements in 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

xviii

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

Profile
Lesson Lesson 23: Using Control Structures Aim

continued

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. Review the topics covered in the course. Create a PL/SQL-based application for manipulating and maintaining information in your database.

Lesson 26: Summary of PL/SQL (optional)

Preface

xix

Related Publications
Oracle Publications Title Oracle7 Server SQL Reference, Release 7.3 SQL*Plus User’s Guide and Reference, Release 3.3 PL/SQL User’s Guide and Reference, Release 2.3 Oracle7 Server SQL Language Quick Reference SQL*Plus Quick Reference, Release 3.3 Oracle Procedure Builder 1.5 Developer’s Guide Oracle7 Server Concepts Manual, Release 7.3 Oracle Press: Oracle Beginner’s Guide Oracle Press: Oracle Complete Reference Additional References
D D D D D

Part Number A32538 A42562–1 A32542 5421–70–1292 A42561 A32485 A32534 A31178–1 A10197–1

System Release Bulletins Installation and User’s Guides read.me Files International Oracle User’s Group (IOUG) Articles Oracle Magazine

xx

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

Typographic Conventions
Typographic Conventions Within Text Convention Uppercase Object or Term Example 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 File names, where: role syntax variables, usernames, passwords Triggers and button names Books, names of courses and manuals, and emphasized words or phrases is the name of the role to be created.

Lowercase, italic

Initial cap

Assign a When–Validate–Item trigger to the S_ORD block. Press the Cancel button. For further information on the subject see: Oracle7 Server SQL Language Reference Manual Do not save changes to the database. This subject is covered in Lesson 3, “Working with Objects.”

Italic

Quotation marks Lesson module titles referenced 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
Typographic Conventions Within Code Convention Uppercase Lowercase, italic Lowercase Object or Term Example Commands, functions SQL> SELECT userid 2 FROM s_emp;

continued

Syntax variables SQL> CREATE ROLE role; 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 be entered by a user. Separates alternative syntax elements Optional items list in syntax Mandatory items list in syntax Default value in syntax

SQL> SELECT userid 2 FROM s_emp; OFF | ON

Vertical bar

Brackets Braces

[OFF | ON] {OFF | ON}

Underlining

{OFF | ON}

xxii

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

Typographic Conventions
Symbols Used in This Document Guidance relating to the subject matter, such as hints or advice.

continued

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

I2

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

Course Objectives
At the end of this course, you should be able to
D D

Describe the relational database approach, concepts, terminology, and operators. Create database structures such as tables and views using Structured Query Language (SQL). Store, retrieve, and update data in the database. Develop PL/SQL blocks of application code using Procedure Builder to manipulate data.

D D

Introduction

I3

I4

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 Lesson 2 Lesson 3 Lesson 4 Selecting Rows Limiting Selected Rows Single Row Functions Displaying Data from Multiple Tables Group Functions Subqueries Specifying Variables at Runtime Overview of Data Modeling and Database Design Creating Tables Oracle Data Dictionary

DAY 2
Lesson 5 Lesson 6 Lesson 7 Lesson 8 Lesson 9 Lesson 10

DAY 3
Lesson 11 Lesson 12 Lesson 13 Lesson 14 Lesson 15 Lesson 16 Lesson 17 Manipulating Data Altering Tables and Constraints Creating Sequences Creating Views Creating Indexes Controlling User Access Summary of SQL and SQL*Plus (optional)

Introduction

I5

I6

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

Course Outline DAY 4
Lesson 18 Lesson 19 Lesson 20 Lesson 21 Lesson 22 Overview of PL/SQL Basics of Procedure Builder Modularizing Programming with Subprograms Developing a Simple PL/SQL Block Interacting with Oracle

continued

DAY 5
Lesson 23 Lesson 24 Lesson 25 Lesson 26 Controlling Flow in PL/SQL Blocks Processing Queries by Using Explicit Cursors Error Handling Summary of PL/SQL (optional)

Introduction

I7

I8

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

Collections of objects or relations store the data. A set of operators can act on the relations to produce other relations. 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 D D

Manage the storage of data Control access to the data 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

I9

I 10

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

The Relational Database Concept
Database Terminology Concept Table Row Description

continued

A table is the basic storage structure of an RDBMS, consisting of one or more columns and zero or more rows. 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”. 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. 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. 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. 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.

Column

Field

Primary Key

Foreign Key

Guidelines
D D D

No duplicate values are allowed in a primary key. Primary keys generally cannot be changed. Foreign keys are based on data values and are purely logical, not physical pointers. A foreign key value must match an existing primary key value or else be NULL.

D

Introduction

I 11

I 12

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

The Relational Database Concept
Relational Database Properties

continued

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 Table View Sequence Index Synonym Program unit Description Basic unit of storage composed of rows and columns. Logically represents subsets of data from one or more tables. Generates primary key values. Improves the performance of queries. Alternate name for an object. 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
Protect Data Integrity

continued

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 Entity Referential Column User-defined Description No part of a primary key can be NULL and the value must be unique. Foreign key values must match a primary key or be NULL. Values in the column must match the defined datatype. 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 Strategy and Analysis Design Build and Document Transition Production Action Study and analyze the business requirements. Build models of the system. Build a database design based on the model. Produce the working, tested software. Write user documentation, help screens, and operations manual. Engage in a user acceptance testing phase. 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 SQL Description A command language for communication with the Oracle7 Server from any tool or application. Oracle SQL contains many extensions. An Oracle tool that recognizes and submits SQL and PL/SQL statements to the Server for execution and contains its own command language. An Oracle procedural language for writing application logic and manipulating data outside the database.

SQL*Plus

PL/SQL

Features of SQL
D

Can be used by a range of users, including those with little or no programming experience Is a non-procedural language Reduces the amount of time required for creating and maintaining systems Is an English-like language

D D D

Features of SQL*Plus
D D D D D D D

Accepts ad hoc entry of statements Accepts SQL and PL/SQL input from files Edits SQL statements with a line editor Controls environmental settings Formats query results into basic reports Interacts with end users 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 SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Description Retrieves data from the database. Most commonly used command. Enters new rows, changes existing rows, and removes unwanted rows from tables in the database, respectively. Collectively known as Data Manipulation Language (DML) commands. Sets up, changes, and removes data structures from tables. Collectively known as Data Definition Language (DDL) commands.

Manage the changes made by DML statements. Changes to the data can be grouped together into logical transactions. Gives or removes access rights to both the Oracle database and 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
SQL*Plus Command Categories Category Environment Format File manipulation Execution Edit Interaction Purpose

continued

Affects the general behavior of SQL statements for the session. Formats query results. Saves, loads, and runs script files. Sends SQL or PL/SQL commands from SQL buffer to Oracle7 Server. Modifies SQL commands in the buffer. Allows users to create and pass variables to SQL statements, print variable values, and print messages to the screen. Various commands to connect to the database, manipulate the SQL*Plus environment, and display column definitions.

Miscellaneous

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 Header Declarative Executable Exception Description Contains the subprogram name, type, and arguments. Only used for subprograms. Contains the local identifiers for the block. Contains the SQL statements and PL/SQL control statements. 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
Business Narrative continued

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

12

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

Write a SELECT statement to query the database. Perform arithmetic calculations using SQL arithmetic operators. Handle null values. Specify alternative column headings using aliases. Concatenate columns. Edit SQL statements in the SQL*Plus buffer and create command files.

Selecting Rows

13

14

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 FROM [DISTINCT] {*,column [alias],....} table; is a list of at least one column. suppresses duplicates. selects all columns. selects the named column. gives selected columns a different heading. specifies the table containing the columns.

where: SELECT DISTINCT * column alias FROM table

Selecting Rows

15

16

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

The Basic Query Block Writing SQL Commands

continued

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

Tabs and indents can be used to make code more readable. Command words cannot be split across lines or abbreviated. Keywords and commands typically are entered in uppercase; all other words, such as table names and columns, are entered in lowercase. SQL commands are not case sensitive, unless indicated. An SQL command is entered at the SQL prompt, and subsequent lines are numbered. This is called the SQL buffer. 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 D D

D D

D

Place a semicolon or slash on the last line in the buffer. Place a slash at the SQL prompt. Issue a SQL*Plus RUN command at the SQL prompt.

For more information, see Oracle Applications: Coding Standards, Release 10G.

Selecting Rows

17

Simplest SELECT statement contains the following two clauses:

18

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

The Basic Query Block
In its simplest form, a SELECT statement must include the following: D A SELECT clause, which specifies the columns to be displayed.
D

continued

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 ------10 31 32 33 34 35 41 42 43 44 45 50

NAME REGION_ID --------------- --------Finance 1 Sales 1 Sales 2 Sales 3 Sales 4 Sales 5 Operations 1 Operations 2 Operations 3 Operations 4 Operations 5 Administration 1

12 rows selected.

Selecting Rows

19

1 10

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

The Basic Query Block
Selecting Specific Columns

continued

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 2 FROM dept_id, last_name, manager_id s_emp;

DEPT_ID ------50 41 31 10 50 41 42 43 44 ...

LAST_NAME MANAGER_ID ------------ ---------Velasquez Ngao 1 Nagayama 1 Quick-To-See 1 Ropeburn 1 Urguhart 2 Menchu 2 Biri 2 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 2 FROM last_name, salary * 12, commission_pct 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
Operator Precedence

continued

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 2 FROM last_name, salary, 12 * salary + 100 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 2 FROM last_name, salary, 12 * (salary + 100) 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 2 3 FROM last_name, salary, 12 * (salary + 100) AS ANNUAL_SALARY 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 2 3 FROM last_name, salary, 12 * (salary + 100) ”Annual Salary” 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 2 FROM first_name||last_name AS ”Employees” 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 2 3 FROM first_name || ’ ’ || last_name || ’, ’|| title ”Employees” 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 2 3 FROM last_name, title, salary*commission_pct/100 COMM s_emp;

LAST_NAME -----------... Havel Magee Giljum Sedeghi Nguyen Dumas Maduro ...

TITLE COMM --------------------- ---------Warehouse Manager Sales Representative Sales Representative Sales Representative Sales Representative Sales Representative Stock Clerk

140 186.25 151.5 228.75 253.75

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
NVL Function In order to convert a null value to an actual value, use the NVL function. Syntax NVL (expr1, expr2) where: expr1 expr2

continued

is the source value or expression that may contain null. 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 2 3 FROM LAST_NAME -----------... Havel Magee Giljum ... last_name, title, salary * NVL(commission_pct,0)/100 COMM s_emp; TITLE COMM --------------------- ---------Warehouse Manager Sales Representative Sales Representative 0 186.25 186.25

NVL Conversions for Various Datatypes Datatype NUMBER DATE CHAR or VARCHAR2 Conversion Example NVL(number_column,9) NVL(date_column,‘01-JAN-95’) NVL(character_column,‘Unavailable’)

Selecting Rows

1 29

SQL> SELECT 2 FROM

DISTINCT name 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 2 FROM name 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 2 FROM DISTINCT name 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
DISTINCT with Multiple Columns

continued

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 2 FROM DISTINCT dept_id, title s_emp;

DEPT_ID ------10 31 31 32 33 34 34 35 41 41 41 42 42 43 43 44 44 45 45 50 50

TITLE --------------------VP, Finance Sales Representative VP, Sales Sales Representative Sales Representative Sales Representative Stock Clerk Sales Representative Stock Clerk VP, Operations Warehouse Manager Stock Clerk Warehouse Manager Stock Clerk Warehouse Manager Stock Clerk Warehouse Manager Stock Clerk Warehouse Manager President 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 D D D D D

Describe the table structure. Edit SQL in the buffer. Save files containing SQL for editing purposes. Execute saved files. Load SQL commands from a file into the SQL buffer. 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 password is your database username. 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 --------------ID NAME REGION_ID where: Null? Type Datatype NUMBER (p,s) VARCHAR2(s) DATE CHAR(s)

Null? Type -------- -------------------NOT NULL NUMBER(7) NOT NULL VARCHAR2(25) NUMBER(7) indicates that a column must contain data. displays the datatype for a column.

Description Number value having a maximum number of digits p, and the number of digits to the right of the decimal point s. Variable length character value of maximum size s. Date and time value between January 1, 4712 B.C. and December 31, 4712 A.D. 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. 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.

D

SQL*Plus Editing Commands Command A[PPEND] text C[HANGE] / old / new / C[HANGE] / text / CL[EAR] BUFF[ER] DEL DEL n DEL m n I[NPUT] I[NPUT] text L[IST] L[IST] n L[IST] m n R[UN] n n text 0 text Description Adds text to the end of the current line. Changes old text to new in the current line. Deletes text from the current line. Deletes all lines from the SQL buffer. Deletes current line. Deletes one line (specified by n) Deletes a range of lines (m to n) Inserts an indefinite number of lines. Inserts a line consisting of text. Lists all lines in the SQL buffer. Lists one line (specified by n). Lists a range of lines (m to n). Displays and runs the current SQL command in the buffer. Specifies the line to make the current line. Replaces line n with 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 SAV[E] filename [.ext] [REP[LACE]|APP[END]] Description Saves current contents of SQL buffer to a file. Use APPEND to add to an existing file; use REPLACE to overwrite an existing file. The default file extension is .sql. Writes the contents of a previously saved file to the SQL buffer. The default extension for the filename is .sql. Runs a previously saved command file. Runs a previously saved command file (same as START). Invokes the editor and saves the buffer contents to a file named afiedt.buf. Invokes editor to edit contents of a saved file. Stores query results in a file, OFF closes the spool file. OUT closes the spool file and sends the file results to the system printer. Leaves SQL*Plus.

GET filename [.ext]

STA[RT] filename [.ext] @ filename EDIT ED[IT] [filename[.ext]] SPO[OL] [filename[.ext]| OFF|OUT] EXIT

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 CLE[AR] FOR[MAT] format HEA[DING] text JUS[TIFY] {align} NOPRI[NT] NUL[L] text PRI[NT] TRU[NCATED] WRA[PPED] WOR[D_WRAPPED] Description Clears any column formats. Changes the display of the column data. Sets the column heading. A vertical line (|) will force a line feed in the heading if you do not use justification. Justifies the column heading (not the data) to be left, center, or right. Hides the column. Specifies text to be displayed for null values. Shows the column. Truncates the string at the end of the first line of display. Wraps the end of the string to the next line. 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
Display or Clear Settings

continued

To show or clear the current COLUMN command settings, use the following commands: Command COL[UMN] column COL[UMN] CLE[AR] COL[UMN] Description Displays the current settings for the specified column. Displays the current settings for all columns. Clears the settings for all columns.

COL[UMN] column CLE[AR] Clears the settings for the specified column.

Selecting Rows

1 47

1 48

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

Creating a Report
Sample Column Format Model Elements Element Description An 9 0 $ L . , Sets a display width of n for character and date columns. Represents a single zero-suppression digit. Enforces leading zero. Represents a floating dollar sign. Represents local currency. Represents the position of the decimal point. Represents the thousand separator. Example N/A 999999 099999 $9999 L9999 9999.99 9,999 Result N/A 1234 01234 $1234 L1234

continued

1234.00 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 DISTINCT * column alias FROM table 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. is a list of at least one column. suppreses duplicates. selects all columns. selects the named column. gives selected column a different heading. specifies the table containing the columns.

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

Selecting all data from different tables. Describing the structure of tables. Performing arithmetic calculations and specifying different column names. 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. 2. 3.

SQL commands are always held in a buffer. True / False SQL*Plus commands assist with querying data. True / False Show the structure of the S_DEPT table. Select all information from the S_DEPT table. ID --------10 31 32 33 34 35 41 42 43 44 45 50 NAME REGION_ID ------------------------- --------Finance 3 Sales 1 Sales 2 Sales 3 Sales 4 Sales 5 Operations 1 Operations 2 Operations 3 Operations 4 Operations 5 Administration 1

12 rows selected.
4.

Show the structure of the S_CUSTOMER table. Using this table, perform the following actions.
a. b.

Retrieve all information from the S_CUSTOMER table. Display the name and phone number for each customer.

Selecting Rows

1 55

Practice 1
4.—Continued c.

continued

Display the phone number and name for each customer, with phone number appearing first. PHONE -------------------55-2066101 81-20101 91-10351 1-206-104-0103 852-3692888 33-2257201 234-6036201 49-527454 809-352689 52-404562 42-111292 20-1209211 1-415-555-6281 1-716-555-7171 7-3892456 15 rows selected. NAME ------------------------Unisports Simms Atheletics Delhi Sports Womansport Kam’s Sporting Goods Sportique Sweet Rock Sports Muench Sports Beisbol Si! Futbol Sonora Kuhn’s Sports Hamada Sport Big John’s Sports Emporium Ojibway Retail Sporta Russia

1 56

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

2
Limiting Selected Rows

22

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 D

Sort row output using the ORDER BY clause. Enter search criteria using the WHERE clause.

Limiting Selected Rows

23

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.

24

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 ASC DESC Example Query the employee table for employee last name, department number, and the hire date for all employees. Sort the results by employee last name. SQL> SELECT last_name, dept_id, start_date 2 FROM s_emp 3 ORDER BY last_name; specifies the order in which the retrieved rows are displayed. orders the rows in ascending order. This is the default order. orders the rows in descending order.

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

25

26

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

Ordering Rows with the ORDER BY Clause
Default Ordering of Data

continued

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 2 FROM 3 ORDER BY last_name, dept_id, start_date s_emp start_date DESC;

LAST_NAME DEPT_ID ------------ ------... Urguhart 41 Chang 44 Patel 34 Menchu 42 ... 25 rows selected.

START_DAT --------18-JAN-91 30-NOV-90 17-OCT-90 14-MAY-90

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

27

28

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

Ordering Rows with the ORDER BY Clause
Ordering by Position

continued

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

29

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 FROM [WHERE [ORDER BY expr table condition(s)] expr]; restricts the query to rows that meet a condition. is composed of column names, expressions, constants, and comparison operators.

where: WHERE condition 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 2 FROM 3 WHERE first_name, last_name, title s_emp 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 2 FROM 3 WHERE first_name, last_name, title s_emp 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
Comparison Operators Logical operators test the following conditions: Operator = > >= < <= SQL Operators There are four SQL operators that operate with all datatypes: Operator BETWEEN...AND... IN(list) LIKE IS NULL Logical Operators Operator AND OR NOT Meaning Meaning Between two values (inclusive) Match any of a list of values Match a character pattern Is a null value Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to

continued

If both component conditions return TRUE, then the result is TRUE. If either component condition returns TRUE, then the result is TRUE. 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 != ^= := <> NOT colname = NOT colname > Negating SQL Operators Operator NOT BETWEEN...AND... NOT IN (list) NOT LIKE IS NOT NULL Description Not between two specified values Not in specified list of values Not like comparison string Is not a null value Description Not equal to (VAX, UNIX, PC) Not equal to (IBM) Not equal to (all operating systems) Not equal to Not greater than

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 2 FROM 3 WHERE 4

first_name, last_name, start_date s_emp start_date BETWEEN ’09-may-91’ 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 2 FROM 3 WHERE 4 first_name, last_name, start_date s_emp start_date BETWEEN ’09-may-91’ 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 2 FROM 3 WHERE id, name, region_id s_dept 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 2 FROM 3 WHERE

last_name s_emp 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 FROM WHERE last_name s_emp 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 2 FROM 3 WHERE last_name s_emp 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 2 FROM 3 WHERE last_name, start_date s_emp 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 2 FROM 3 WHERE last_name s_emp 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 2 FROM 3 WHERE name s_customer 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 2 FROM 3 WHERE id, name, credit_rating s_customer sales_rep_id = NULL;

no rows selected

SQL> SELECT 2 FROM 3 WHERE

id, name, credit_rating s_customer sales_rep_id = ’’;

no rows selected

SQL> SELECT 2 FROM 3 WHERE

id, name, credit_rating s_customer 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 2 FROM 3 WHERE last_name, title, commission_pct s_emp commission_pct IS NOT NULL;

Limiting Selected Rows

2 25

SQL> 2 3 4

SELECT FROM WHERE AND

last_name, salary, dept_id, title s_emp dept_id = 41 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> 2 3 4 SELECT FROM WHERE AND last_name, salary, dept_id, title s_emp dept_id = 41 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> 2 3 4 SELECT FROM WHERE OR last_name, salary, dept_id, title s_emp dept_id = 41 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 1 2 3

Operator All comparison operators. AND 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 1 2 3 Operator All comparison operators (=, <>, >, >=, <, <=, IN, LIKE, IS NULL, BETWEEN) AND 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
Example 1

continued

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> 2 3 4 5 SELECT FROM WHERE AND OR last_name, salary, dept_id s_emp salary >= 1000 dept_id = 44 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> 2 3 4 5 SELECT FROM WHERE AND OR last_name, salary, dept_id s_emp salary >= 1000 (dept_id = 44 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 FROM [WHERE [ORDER BY [DISTINCT] {*,column [alias],....} table condition(s)] {column,expr} [ASC|DESC]]; is a list of at least one column. suppresses duplicates. selects all columns. selects the named column. gives selected columns a different heading. specifies the table containing the columns. restricts the query to rows that meet a condition. is composed of column names, expressions, constants, and comparison operators. specifies the order in which the retrieved rows are displayed. orders rows in ascending order. orders the rows in descending order.

where: SELECT DISTINCT * column alias FROM table WHERE condition ORDER BY ASC DESC

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 D

Selecting data and changing the order of rows displayed. Using the WHERE clause to restrict rows, with a combination of logical and SQL operators. Using column aliases.

D

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

You cannot order by a column that you have not selected. True / False This SELECT statement will execute successfully. True / False SQL> Select 2 From 3 Where last_name, title, salary Ann_sal s_emp last_name = ’Dancs’;

3.

This SELECT statement will execute successfully. True / False SQL> select 2 from 3 where * s_emp salary*12 = 9600;

4.

There are four coding errors in this statement. Can you identify them? SQL> 2 3 4 5 SELECT FROM WHERE AND id, last_name, salary x 12 ANNUAL SALARY s_emp sal > 3000 start_date LIKE %84;

Limiting Selected Rows

2 37

Practice 2
5.

continued

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

Run your query in the file p2q5. 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 -------------------------- ––––––––––– Womansport 204 Beisbol Si! 209 Big John’s Sports Emporium 213 Ojibway Retail 214 Rating –––––––– GOOD GOOD GOOD GOOD

d. 6.

Retrieve p2q5 into the SQL buffer. Order the query results in descending order by customer number. Run your query.

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 ----------------------------------Mark Quick-To-See Audry Ropeburn Carmen Velasquez DEPT_ID --------10 50 50

c. d.

Display all employees whose last names contain an “s.” 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
If you have time, complete the following exercises.
7.

continued

Use the S_EMP table to perform the following actions.
a. b.

Write a query to show the last name and salary of all employees who are not making between 1000 and 2500 per month. 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. Display the last name and start date of every employee who was hired in 1991. Display the full name of all employees with no manager. Alphabetically display all products having a name beginning with Pro. Display all product names and short descriptions for all descriptions containing the word “bicycle.” Display all short descriptions. Compare the results from Exercise 8b. Did your response in Exercise 8b return all descriptions containing bicycle?

c. d. 8.

Show the structure of S_PRODUCT table.
a. b. c.

Limiting Selected Rows

2 39

2 40

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

3
Single Row Functions

32

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

Explain the various types of functions available in SQL. Identify the basic concepts of using functions. Use a variety of character, number, and date functions in SELECT statements. Explain the conversion functions and how they might be used.

Single Row Functions

33

34

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

Perform calculations on data. Modify individual data items. Manipulate output for groups of rows. Alter date formats for display. Convert column datatypes.

There are two distinct types of functions:
D D

Single row functions. 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 D D D

Character Number Date 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

35

36

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

A user-supplied constant A variable value A column name An expression

Features of Single Row Functions
D D D D D D

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

Syntax function_name (column|expression, [arg1, arg2,...]) where: function_name column expression arg1, arg2 is the name of the function. is any named database column. is any character string or calculated expression. is any argument to be used by the function.

Single Row Functions

37

38

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 LOWER(column|expression) UPPER(column|expression) INITCAP(column|expression) Purpose Converts alpha character values to lowercase. Converts alpha character values to uppercase. Converts alpha character values to uppercase for the first letter of each word, all other letters in lowercase. Concatenates the first character value to the second character value. Equivalent to concatenation operator (||). 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. Returns the number of characters in value.

CONCAT(column1|expression1, column2|expression2) SUBSTR(column|expression,m[,n])

LENGTH(column|expression)

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

39

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 2 3 4 FROM 5 WHERE LOWER(first_name||’ ’||last_name) VP, INITCAP(userid) USERID, UPPER(title) TITLE s_emp title LIKE ’VP%’;

VP --------------------ladoris ngao midori nagayama mark quick-to-see audry ropeburn

USERID -------Lngao Mnagayam Mquickto Aropebur

TITLE ------------------VP, OPERATIONS VP, SALES VP, FINANCE 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 2 FROM 3 WHERE first_name, last_name s_emp last_name = ’PATEL’;

no rows returned

SQL> SELECT 2 FROM 3 WHERE

first_name, last_name s_emp UPPER(last_name) = ’PATEL’;

FIRST_NAME -------------------Vikram Radha

LAST_NAME -------------------Patel 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 2 FROM 3 WHERE CONCAT (name, country) CUSTOMER s_customer 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 2 FROM 3 WHERE name, LENGTH(name) s_product 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 ROUND(column|expression,n) Purpose 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. 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. Returns the remainder of m divided by n.

TRUNC(column|expression,n)

MOD(m,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 2 3 FROM ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1) 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 2 3 FROM TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-1) 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 2 FROM 3 WHERE last_name, MOD(salary,commission_pct) s_emp 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 D D D D D

Century Year Month Day Hours

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 2 FROM SYSDATE 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 date + number date - number date - date date + number/24 Result date date number of days date Description Adds a number of days to a date. Subtracts a number of days from a date. Subtracts one date from another. 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 2 FROM 3 WHERE last_name, (SYSDATE-start_date)/7 WEEKS s_emp dept_id = 43;

LAST_NAME -----------Biri Markarian Newman

WEEKS ---------297.226498 238.083641 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 MONTHS_BETWEEN(date1, date2) Purpose 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. Adds n number of calender months to date. n must be an integer and can be negative 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. Finds the date of the last day of the month that contains date. 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. 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.

ADD_MONTHS(date,n)

NEXT_DAY(date,‘char’)

LAST_DAY(date) ROUND(date[,‘fmt’])

TRUNC(date[,‘fmt’])

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 -----9 12 14 16

START_DAT --------09-FEB-92 18-JAN-92 22-JAN-92 07-FEB-92

TENURE ---------44.1163486 44.826026 44.6969937 44.1808647

REVIEW --------09-AUG-92 18-JUL-92 22-JUL-92 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> 2 3 4 5 6 SELECT product_id, NEXT_DAY (restock_date,’FRIDAY’), LAST_DAY (restock_date) FROM s_inventory WHERE restock_date IS NOT NULL ORDER BY restock_date;

PRODUCT_ID ---------30433 40422 50532

NEXT_DAY( --------11-SEP-92 12-FEB-93 16-APR-93

LAST_DAY( --------30-SEP-92 28-FEB-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 2 3 4 FROM 5 WHERE id, start_date, ROUND(start_date, ’MONTH’), TRUNC(start_date, ’MONTH’) s_emp start_date LIKE ’%91’;

ID -----3 6 10 13 15 18 19 20 21 24 25

START_DAT --------17-JUN-91 18-JAN-91 27-FEB-91 18-FEB-91 09-OCT-91 09-FEB-91 06-AUG-91 21-JUL-91 26-MAY-91 17-MAR-91 09-MAY-91

ROUND(STA --------01-JUL-91 01-FEB-91 01-MAR-91 01-MAR-91 01-OCT-91 01-FEB-91 01-AUG-91 01-AUG-91 01-JUN-91 01-APR-91 01-MAY-91

TRUNC(STA --------01-JUN-91 01-JAN-91 01-FEB-91 01-FEB-91 01-OCT-91 01-FEB-91 01-AUG-91 01-JUL-91 01-MAY-91 01-MAR-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 TO_CHAR(number|date,[‘fmt’]) Purpose Converts a number or date value to a VARCHAR2 character string with format model fmt. Converts a character string containing digits to a number. 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.

TO_NUMBER(char) TO_DATE(char,[‘fmt’])

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. The format model can include any valid date format element. Be sure to separate the date value from the format model by a comma. The names of days and months in the output are automatically padded with blanks. To remove padded blanks or to suppress leading zeros, use the fill mode fm element. You can resize the display width of the resulting character field with the SQL*Plus COLUMN command. The resultant column width is 80 characters by default.

D

D

D

D

D

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> 2 3 SELECT FROM WHERE ID,TO_CHAR(date_ordered,’MM/YY’) ORDERED s_ord sales_rep_id = 11;

ID ------100 105 109 110 111

ORDERED ------------------08/92 09/92 09/92 09/92 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
Sample Valid Date Format Elements Element SCC or CC Years in dates YYYY or SYYYY YYY or YY or Y Y,YYY IYYY, IYY, IY, I SYEAR or YEAR BC or AD B.C. or A.D. Q MM MONTH MON RM WW or W DDD or DD or D DAY DY J Description

continued

Century; S prefixes BC date with -. Year; S prefixes BC date with -. Last 3, 2, or 1 digit(s) of year. Year with comma in this position. 4, 3, 2, or 1 digit year based on the ISO standard. Year spelled out; S prefixes BC date with -. BC/AD indicator. BC/AD indicator with periods. Quarter of year. Month, 2-digit value. Name of month padded with blanks to length of 9 characters. Name of month, 3-letter abbreviation. Roman numeral month. Week of year or month. Day of year, month, or week. Name of day padded with blanks to length of 9 characters. Name of day; 3-letter abbreviation. 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
Time Formats

continued

Use the formats listed in the following tables to display time information and literals, and to change numerals to spelled numbers. Element AM or PM A.M. or P.M. HH or HH12 or HH24 MI SS SSSSS Other Formats Element / . , “ of the ” 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 TH SP SPTH or THSP Description Ordinal number (for example, DDTH for 4TH). Spelled-out number (for example, DDSP for FOUR). Spelled-out ordinal numbers (for example, DDSPTH for FOURTH). Description Punctuation is reproduced in the result. Quoted string is reproduced in the result. Description Meridian indicator. Meridian indicator with periods. Hour of day or hour (1-12) or hour (0-23) Minute (0-59). Second (0-59). Seconds past midnight (0-86399).

Single Row Functions

3 39

3 40

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

TO_CHAR Function with Date Formats
The RR Date Format Element

continued

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 1994 1994 2001 Given Date 27-OCT-95 27-OCT-17 27-OCT-17 Interpreted (RR) 1995 2017 2017 Interpreted (YY) 1995 1917 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 2 3 FROM 4 WHERE last_name, TO_CHAR(start_date, ’fmDD ”of” Month YYYY’) HIREDATE s_emp start_date LIKE ’%91’;

LAST_NAME -----------Nagayama Urguhart Havel ...

HIREDATE -------------------17 of June 1991 18 of January 1991 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 -----------Nagayama Urguhart Havel ...

HIREDATE -----------------------------------Seventeenth of June 1991 12:00:00 AM Eighteenth of January 1991 12:00:00 AM 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 9 0 $ L . , MI PR EEEE V B Description Numeric position (number of 9s determine display width). Display leading zeros. Floating dollar sign. Floating local currency symbol. Decimal point in position specified. Comma in position specified. Parenthesize negative numbers. Scientific notation (format must specify four Es). Multiply by 10 n times (n=no of 9s after V). Display zero values as blank, not 0. Example 999999 099999 $999999 L999999 999999.99 999,999 999999PR 99.999EEEE 9999V99 B9999.99 Result 1234 001234 $1234 FF1234 1234.00 1,234 1234<1234> 1.234E+03 123400 1234.00

Minus signs to right (negative values). 999999MI

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 2 3 4 FROM 5 WHERE ’Order ’||TO_CHAR(id)|| ’ was filled for a total of ’ ||TO_CHAR(total,’fm$9,999,999’) s_ord 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. The Oracle7 Server rounds the stored decimal value to the number of decimal spaces provided in the format model.

D

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 2 3 FROM 4 WHERE CONCAT(UPPER(last_name), SUBSTR(title,3)) ”Vice Presidents” s_emp 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 2 3 FROM 4 WHERE last_name, NVL(TO_CHAR(manager_id),’No Manager’) s_emp 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 2 3 4 5 FROM 6 ORDER BY TO_CHAR(NEXT_DAY(ADD_MONTHS (date_ordered,6),’FRIDAY’), ’fmDay, Month ddth, YYYY’) ”New 6 Month Review” s_ord 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 ROUND, TRUNC, MOD MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND, TRUNC Date values can also use arithmetic operators

D

Number data.
D

D

Date data.
D

D

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

Creating queries that require the use of numeric, character, and date functions Using concatenation with functions Writing case-insensitive queries to test the usefulness of character functions if you are unsure exactly how character date is stored Performing calculations of years and months of service for an employee Determining the review date for an employee

D D

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

Single row functions work on many rows to produce a single result. True / False You can use all of the arithmetic operators on date values. True / False What is the name of the function that holds the current date? Display the employee number, last name, and salary increased by 15% and expressed as a whole number. ID -----1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 LAST_NAME NEW SALARY ------------ -----------------Velasquez 2875 Ngao 1668 Nagayama 1610 Quick-To-See 1668 Ropeburn 1783 Urguhart 1380 Menchu 1438 Biri 1265 Catchpole 1495 Havel 1503 Magee 1610 Giljum 1714 Sedeghi 1742 Nguyen 1754 Dumas 1668 Maduro 1610 Smith 1081 Nozaki 1380 Patel 914 Newman 863 Markarian 978 Chang 920 Patel 914 Dancs 989 Schwartz 1265

4.

25 rows selected.

Single Row Functions

3 59

Practice 3
5.

continued

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

continued

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

25 rows selected.

Single Row Functions

3 61

Practice 3
7.

continued

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
If you have time, complete the following exercises.
8.

continued

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

continued

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

25 rows selected.

3 64

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

Practice 3
10.

continued

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

42

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. View data that would not normally meet a join condition by using outer joins. Join a table to itself.

D D

Displaying Data from Multiple Tables

43

44

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 D

Equijoins Non-equijoins Outer joins Self joins Set operators

Additional join methods include the following:
D D D

For more information about set operators, attend Advanced SQL and SQL*Plus course.

Displaying Data from Multiple Tables

45

46

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 2 FROM ... 300 rows selected. name, last_name s_dept, s_emp;

Displaying Data from Multiple Tables

47

48

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 table1.column1 = table2.column2 Guidelines
D

denotes the table and column from which data is retrieved. is the condition that joins (or relates) the tables together.

When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and to enhance database access. If the same column name appears in more than one table, then the column name must be prefixed with the table name. 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.

D

D

For more information, see Oracle7 Server SQL Language Reference Manual, “SELECT.”

Displaying Data from Multiple Tables

49

Server

4 10

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

ÉÉ ÉÉ

Simple Join Query
Equijoin

continued

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 2 3 FROM 4 WHERE s_emp.last_name, s_emp.dept_id, s_dept.name s_emp, s_dept 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
Qualifying Ambiguous Column Names

continued

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 2 3 4 FROM 5 WHERE s_dept.id ”Department ID”, s_region.id ”Region ID”, s_region.name ”Region Name” s_dept, s_region 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
Additional Search Conditions

continued

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> 2 3 4 5 SELECT FROM WHERE AND s_emp.last_name, s_emp.dept_id, s_dept.name s_emp, s_dept s_emp.dept_id = s_dept.id 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> 2 3 4 5 6 SELECT FROM WHERE AND AND s_emp.last_name, s_region.name, s_emp.commission_pct s_emp, s_dept, s_region s_emp.dept_id = s_dept.id s_dept.region_id = s_region.id s_emp.commission_pct > 0;

LAST_NAME -----------Magee Giljum Sedeghi Nguyen Dumas

NAME COMMISSION_PCT -------------------- -------------North America 10 South America 12.5 Africa / Middle East 10 Asia 15 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 2 3 4 FROM 5 WHERE c.name ”Customer Name”, c.region_id ”Region ID”, r.name ”Region Name” s_customer c, s_region r c.region_id = r.id;

Guidelines
D

Table aliases can be up to 30 characters in length, but the shorter they are the better. 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. Table aliases should be meaningful. The table alias is only valid for the current SELECT statement.

D

D D

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 2 FROM 3 WHERE e.ename, e.job, e.sal, s.grade emp e, salgrade s e.sal BETWEEN s.losal AND s.hisal;

ENAME ---------SMITH ADAMS JAMES WARD MARTIN MILLER ALLEN TURNER JONES BLAKE CLARK SCOTT FORD KING

JOB SAL GRADE --------- ---------- ---------CLERK 800.00 1 CLERK 1,100.00 1 CLERK 950.00 1 SALESMAN 1,250.00 2 SALESMAN 1,250.00 2 CLERK 1,300.00 2 SALESMAN 1,600.00 3 SALESMAN 1,500.00 3 MANAGER 2,975.00 4 MANAGER 2,850.00 4 MANAGER 2,450.00 4 ANALYST 3,000.00 4 ANALYST 3,000.00 4 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 = table2.column (+) is the condition that joins (or relates) the tables 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> 2 3 4 SELECT FROM WHERE ORDER BY e.last_name, e.id, c.name s_emp e, s_customer c e.id (+) = c.sales_rep_id 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. A condition involving an outer join may not use the IN operator or be linked to another condition by the OR operator.

D

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 2 3 FROM 4 WHERE worker.last_name||’ works for ’|| manager.last_name s_emp worker, s_emp manager 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 table1.column1 = table2.column2 Types of Joins
D D D D

denotes a table and column from which data is retrieved. is the condition that joins (or relates) the tables together.

Equijoin Non-equijoin Outer join 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. Table aliases can help to keep SQL code smaller, therefore conserving memory.

D

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

Joining tables using an equijoin Performing outer and self joins 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
2.

continued

Write a query to display the last name, department name, and region name of all employees who earn a commission. LAST_NAME -----------Magee Giljum Sedeghi Nguyen Dumas NAME -------------Sales Sales Sales Sales Sales NAME -------------------North America South America Africa / Middle East Asia 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 --------------------------------Grand Prix Bicycle Tires Pro Curling Bar Prostar 10 Pound Weight Prostar 100 Pound Weight Major League Baseball Griffey Glove Cabrera Bat 7 rows selected. ID ORDERED ----- ------30421 15 40422 30 41010 20 41100 35 50169 40 50417 27 50530 50

4 32

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

Practice 4
5.

continued

Display the customer number and the last name of their sales representative. Order the list by last name. ID ----205 206 208 211 215 201 204 214 209 213 202 203 212 LAST_NAME --------------Dumas Dumas Dumas Dumas Dumas Giljum Magee Magee Magee Magee Nguyen Nguyen Sedeghi

13 rows selected.

Displaying Data from Multiple Tables

4 33

Practice 4
If you have time, complete the following exercises.
6.

continued

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

18 rows selected.

4 34

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

Practice 4
7.

continued

Display all employees by last name name and employee number along with their manager’s last name and manager number. EMP_NAME EMP_ID ---------–––––– ––––––– Ngao 2 Nagayama 3 Quick-To-See 4 Ropeburn 5 Urguhart 6 Menchu 7 Biri 8 Catchpole 9 Havel 1O Magee 11 Giljum 12 Sedeghi 13 Nguyen 14 Dumas 15 Maduro 16 Smith 17 Nozaki 18 Patel 19 Newman 20 Markarian 21 Chang 22 Patel 23 Dancs 24 Schwartz 25 24 rows selected. MGR_NAME ––––––––––––– Velasquez Velasquez Velasquez Velasquez Ngao Ngao Ngao Ngao Ngao Nagayama Nagayama Nagayama Nagayama Nagayama Urguhart Urguhart Menchu Menchu Biri Biri Catchpole Catchpole Havel Havel MGR_ID ––––––– 1 1 1 1 2 2 2 2 2 3 3 3 3 3 6 6 7 7 8 8 9 9 10 10

Displaying Data from Multiple Tables

4 35

Practice 4
8.

continued

Modify the solution to exercise 7 to also display Velasquez, who has no manager. Employee Name Employee ID ---------–––––––––––––––––– Velasquez 1 Ngao 2 Nagayama 3 Quick-To-See 4 Ropeburn 5 Urguhart 6 Menchu 7 Biri 8 Catchpole 9 Havel 10 Magee 11 Giljum 12 Sedeghi 13 Nguyen 14 Dumas 15 Maduro 16 Nozaki 18 Markarian 21 Patel 23 Smith 17 Patel 19 Newman 20 Chang 22 Dancs 24 Schwartz 25 25 rows selected. Manager Name Manager_ID ––––––––––––– –––––––––– Velasquez Velasquez Velasquez Velasquez Ngao Ngao Ngao Ngao Ngao Nagayama Nagayama Nagayama Nagayama Nagayama Urguhart Menchu Biri Catchpole Urguhart Menchu Biri Catchpole Havel Havel 1 1 1 1 2 2 2 2 2 3 3 3 3 3 6 7 8 9 6 7 8 9 10 10

4 36

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

Practice 4
9.

continued

Display all customers and the products and quantities they ordered for those customers whose order totaled more than 100,000. Customer ---------------------Womansport Womansport Womansport Womansport Womansport Womansport Womansport Kuhn’s Sports Kuhn’s Sports Kuhn’s Sports Kuhn’s Sports Kuhn’s Sports Hamada Sport Hamada Sport Hamada Sport Hamada Sport Hamada Sport Hamada Sport Hamada Sport Big John’s Sports Emporium Big John’s Sports Emporium Big John’s Sports Emporium Big John’s Sports Emporium Big John’s Sports Emporium Big John’s Sports Emporium Big John’s Sports Emporium 26 rows selected. PRODUCT_ID –––––––––– 10011 10013 10021 30326 41010 30433 10023 20106 20201 30421 30321 20108 20510 41080 41100 32861 20512 32779 30321 10011 30426 50418 32861 30326 10012 10022 QUANTITY –––––––– 500 400 500 600 250 450 400 50 130 55 75 22 9 50 42 57 18 60 85 150 500 43 50 1500 600 300

Displaying Data from Multiple Tables

4 37

4 38

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

5
Group Functions

52

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

Identify the available group functions. Explain the use of group functions. Use the GROUP BY clause to force statistics to be displayed for different groups. Use the HAVING clause to include or exclude grouped rows.

Group Functions

53

54

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

AVG COUNT MAX MIN STDDEV SUM 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 FROM [WHERE [GROUP BY [HAVING [ORDER BY column, group_function table condition] group_by_expression] group_condition] column]; specifies columns whose values determine the basis for grouping rows. restricts the groups of rows returned to those groups for which the specified condition is TRUE.

where: group_by_expression group_condition

Group Functions

55

56

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 AVG(DISTINCT|ALL|n) COUNT(DISTINCT|ALL|expr|*) Description Average value of n, ignoring null values. Number of rows, where expr evaluates to something other than null. Count all selected rows using *, including duplicates and rows with nulls. Maximum value of expr. Minimum value of expr. Standard deviation of n, ignoring null values. Sum values of n, ignoring null values. Variance of n, ignoring null values.

MAX(DISTINCT|ALL|expr) MIN(DISTINCT|ALL|expr) STDDEV(DISTINCT|ALL|n) SUM(DISTINCT|ALL|n) VARIANCE(DISTINCT|ALL|n) 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. The datatypes for the arguments may be CHAR, VARCHAR2, NUMBER, or DATE where expr is listed. All group functions except COUNT(*) ignore null values. To substitute a value for null values, use the NVL function.

D

D

Group Functions

57

58

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 2 3 FROM 4 WHERE AVG(salary), MAX(salary), MIN(salary), SUM(salary) s_emp 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 2 FROM MIN(last_name), MAX(last_name) s_emp;

MIN(LAST_NAME) MAX(LAST_NAME) ------------------------- ------------------------Biri Velasquez Note: You can use MAX and MIN functions for any datatype.

Group Functions

59

5 10

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

Group Functions
COUNT Function

continued

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 2 FROM 3 WHERE COUNT(*) s_emp 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 2 FROM 3 WHERE COUNT(commission_pct) s_emp 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 FROM [WHERE [GROUP BY [ORDER BY column, group_function table condition] group_by_expression] column]; specifies columns whose values determine the basis for grouping rows.

where: group_by_expression 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. Using a WHERE clause, you can pre-exclude rows before dividing them into groups. You must include the columns in the GROUP BY clause. You cannot use the positional notation or column alias in the GROUP BY clause. By default, rows are sorted by ascending order of the GROUP BY list. You can override this by using the ORDER BY clause.

D

D D D

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 2 FROM 3 GROUP BY credit_rating, COUNT(*) ”# Cust” s_customer 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> 2 3 4 5 SELECT FROM WHERE GROUP BY ORDER BY title, SUM(salary) PAYROLL s_emp title NOT LIKE ’VP%’ title 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 2 FROM 3 GROUP BY MAX(salary) s_emp title;

MAX(SALARY) ----------2500 1525 1400 ... 8 rows selected. Example Display the maximum salary for each title group and display the title. SQL> SELECT 2 FROM 3 GROUP BY title, MAX(salary) s_emp 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
The WHERE clause cannot be used to restrict groups.

continued

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> 2 3 4 SELECT FROM GROUP BY HAVING dept_id, AVG(salary) s_emp dept_id 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 2 FROM 3 GROUP BY dept_id, title, COUNT(*) s_emp dept_id, title;

DEPT_ID ------... 34 34 35 41 41 ...

TITLE COUNT(*) --------------------- ---------Sales Representative Stock Clerk Sales Representative Stock Clerk VP, Operations 1 1 1 2 1

Example Display the number of employees for each department within each job category. SQL> SELECT 2 FROM 3 GROUP BY title, dept_id, COUNT(*) s_emp 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 FROM [WHERE [GROUP BY [HAVING [ORDER BY column, group_function table condition] group_by_expression] group_condition] column]; restricts the groups of rows returned to those groups for which the specified condition is TRUE.

where: group_condition

The Oracle7 Server performs the following steps when you use the HAVING clause:
D D D

Rows are grouped. The group function is applied. 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> 2 3 4 5 6 SELECT FROM WHERE GROUP BY HAVING ORDER BY title, SUM(salary) PAYROLL s_emp title NOT LIKE ’VP%’ title SUM(salary) > 5000 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> 2 3 4 SELECT FROM GROUP BY HAVING dept_id s_emp dept_id 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 D D D D D D

AVG COUNT MAX MIN STDDEV SUM VARIANCE

Syntax SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY column, group_function table condition] group_by_expression] group_condition] 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. 2. 3.

If the statement contains a WHERE clause, the server establishes the candidate rows. The server identifies the groups specified in the GROUP BY clause. 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 Grouping by rows to achieve more than one result Excluding groups by using the HAVING clause

D D

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

continued

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 –––––––––– 2 1 3 LOWEST PAID EMPLOYEE ––––––––––––––––––––– 1100 1400 1400 2500

Group Functions

5 35

Practice 5
7.

continued

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 ----1 2 3 4 5 NAME # OF DEPT --------------------------- ---------------North America 4 South America 2 Africa / Middle East 2 Asia 2 Europe 2

5 36

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

Practice 5
10.

continued

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

62

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

Write nested subqueries to query data based on unknown criteria. Use subqueries in data manipulation statements. Order data with subqueries.

Subqueries

63

Server

64

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

WHERE clause HAVING clause FROM clause of a SELECT or DELETE statement

Subqueries

65

66

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 FROM WHERE select_list table expr operator (SELECT select_list FROM table); includes a comparison operator such as >, =, or IN.

where: operator

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

Enclose a subquery within parentheses. Place the subquery after the comparison operator. 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

67

43

68

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 2 FROM 3 WHERE 4 5 6
1.

last_name, title s_emp dept_id = (SELECT dept_id FROM s_emp WHERE UPPER(last_name)=’BIRI’);

The nested SELECT statement or query block is executed first, producing a query result: 43. SQL> SELECT 2 FROM 3 WHERE dept_id s_emp 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 2 FROM 3 WHERE last_name, title s_emp dept_id = 43;

Subqueries

69

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

LAST_NAME ----------------------Maduro Smith Nozaki Patel Newman Markarian Chang Patel Dancs Schwartz 10 rows selected.

TITLE -------------------Stock Clerk Stock Clerk Stock Clerk Stock Clerk Stock Clerk Stock Clerk Stock Clerk Stock Clerk Stock Clerk Stock Clerk

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 2 FROM 3 WHERE 4 5 last_name, title, salary s_emp salary < (SELECT AVG(salary) FROM s_emp);

LAST_NAME ------------------Urguhart Menchu Biri Smith Nozaki Patel Newman Markarian Chang Patel Dancs Schwartz 12 rows selected.

TITLE SALARY --------------------- ----------Warehouse Manager 1200 Warehouse Manager 1250 Warehouse Manager 1100 Stock Clerk 940 Stock Clerk 1200 Stock Clerk 795 Stock Clerk 750 Stock Clerk 850 Stock Clerk 800 Stock Clerk 795 Stock Clerk 860 Stock Clerk 1100

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> 2 3 4 5 6 7 SELECT FROM WHERE last_name, first_name, title s_emp dept_in = (SELECT ID FROM s_dept WHERE name = ’Finance’ 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 2 FROM 3 WHERE 4 5 6 7 last_name, first_name, title s_emp dept_in IN (SELECT ID FROM s_dept WHERE name = ’Finance’ OR region_id = 2);

LAST_NAME ––––––––––––– Quick–To–See Menchu Giljum Nozaki Patel

FIRST_NAME ––––––––––– Mark Roberta Henry Akira Vikram

TITLE ––––––––––––––––––– VP, Finance Warehouse Manager Sales Representative Stock Clerk 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> 2 3 4 5 6 7 SELECT FROM GROUP BY HAVING dept_id, AVG(salary) s_emp dept_id AVG(salary) > (SELECT AVG(salary) FROM s_emp WHERE dept_id = 32);

DEPT_ID AVG(SALARY) ------- ----------33 1515 50 2025 Example Find the job with the lowest average salary. SQL> 2 3 4 5 6 7 SELECT FROM GROUP BY HAVING title, AVG(salary) s_emp title AVG(salary) = (SELECT MIN(AVG(salary)) FROM s_emp 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 FROM WHERE select_list table 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 <=. Can pass multiple rows of data to a main statement that contains a multiple row operator, such as IN. Are processed first by the Oracle7 Server, and the WHERE or HAVING clause uses the results. Can contain group functions.

D

D

D

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 D

Creating subqueries to query values based on unknown criteria 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? How many times does the first query run? You cannot use the equality (=) operator if the inner query returns more than one value. True / False
i.

b.

c.

If the answer is True, why and what operator should be used? If the answer is False, why?

ii.

These exercises use the S_EMP, S_DEPT, S_ORD, S_ITEM, and S_PRODUCT tables.
2. 3. 4. 5.

Display the first name, last name, and start date for all employees in the same department as Magee. Display the employee number, first name, last name, and user name for all employees with salaries above the average salary. Display last name, department number, and title for all employees assigned to region 1 or region 2. Display the last name and salary for all employees that report to LaDoris Ngao. 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.” 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.

If you have time, complete the following exercises.
6.

7.

Subqueries

6 25

Practice 6
If you have time, complete the following exercises.
8. 9. 10.

continued

Display the name and short description for any product that did not appear on an order in the month of September, 1992. Display the customer name and credit rating for all customers of sales representative Andre Dumas. 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