lEARN ORACLE8i José A. RAmalho
Wordware Publishing, Inc.
Library of Congress Cataloging-in-Publication Data Ramalho, José A. Learn Oracle8i / by José A. Ramalho. p. cm. Includes index. ISBN 1-55622-731-0 (pbk.) 1. Oracle (Computer file) 2. Relational databases. I. Title. QA76.9.D3 R2395 2000 005.75’85—dc21 00-036466 CIP
© 2000, Wordware Publishing, Inc. All Rights Reserved 2320 Los Rios Boulevard Plano, Texas 75074 No part of this book may be reproduced in any form or by any means without permission in writing from Wordware Publishing, Inc. Printed in the United States of America
ISBN 1-55622-731-0 10 9 8 7 6 5 4 3 2 1
0004
Product names mentioned are used for identification purposes only and may be trademarks of their respective companies. All inquiries for volume purchases of this book should be addressed to Wordware Publishing, Inc., at the above address. Telephone inquiries may be made by calling: (972) 423-0090
Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Part I—Basic Concepts Chapter 1 Introduction to the Oracle Server . . . . . . . 3 The Oracle Server . . . . . . . . . . . . . . . . . . . . . . . . . . 3 The Database Structure . . . . . . . . . . . . . . . . . . . . . . . 3 The Physical Database . . . . . . . . . . . . . . . . . . . . . 3 The Logical Database . . . . . . . . . . . . . . . . . . . . . . 4 An Oracle Instance . . . . . . . . . . . . . . . . . . . . . . . . . 4 Database Structure and Space Management . . . . . . . . . . . . . 5 Logical Database Structures . . . . . . . . . . . . . . . . . . . 5 Tablespaces . . . . . . . . . . . . . . . . . . . . . . . . . 6 Databases, Tablespaces, and Datafiles . . . . . . . . . . . . 6 Schemas and Schema Objects . . . . . . . . . . . . . . . . 7 Data Blocks, Extents, and Segments. . . . . . . . . . . . . 7 Physical Database Structures . . . . . . . . . . . . . . . . . . 8 Datafiles . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Redo Record Files. . . . . . . . . . . . . . . . . . . . . . 9 Control Files. . . . . . . . . . . . . . . . . . . . . . . . 10 Memory and Process Structures . . . . . . . . . . . . . . . . . . 11 Memory Structures . . . . . . . . . . . . . . . . . . . . . . 11 System Global Area (SGA). . . . . . . . . . . . . . . . . 12 Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Program Global Area (PGA) . . . . . . . . . . . . . . . . 14 Process Architecture . . . . . . . . . . . . . . . . . . . . . . 14 User Processes (Client) . . . . . . . . . . . . . . . . . . 15 Oracle’s Process Architecture . . . . . . . . . . . . . . . 15 The Program Interface . . . . . . . . . . . . . . . . . . . . . . . 19 How Oracle Works . . . . . . . . . . . . . . . . . . . . . . . 20 Oracle and Net8 . . . . . . . . . . . . . . . . . . . . . . . . 21 The Object Relational Model for Database Management . . . . . . 22 The Relational Model . . . . . . . . . . . . . . . . . . . . . 22 iii
Contents
The Object Relational Model . . . . . . . . . . . . . Schemas and Schema Objects . . . . . . . . . . . . . . Tables . . . . . . . . . . . . . . . . . . . . . . . . Views . . . . . . . . . . . . . . . . . . . . . . . . Sequences . . . . . . . . . . . . . . . . . . . . . . Program Units . . . . . . . . . . . . . . . . . . . . Synonyms . . . . . . . . . . . . . . . . . . . . . . Indexes . . . . . . . . . . . . . . . . . . . . . . . Clusters and Hash Clusters. . . . . . . . . . . . . . Clustered Tables . . . . . . . . . . . . . . . . . Hash Clusters . . . . . . . . . . . . . . . . . . Database Links . . . . . . . . . . . . . . . . . The Data Dictionary . . . . . . . . . . . . . . . . . . . Client/Server Architecture: Distributed Processing . . . . The Client . . . . . . . . . . . . . . . . . . . . . . The Server . . . . . . . . . . . . . . . . . . . . . . Multitiered Architecture: Application Servers . . Distributed Databases . . . . . . . . . . . . . . . . . . Manipulation of Distributed Data . . . . . . . . . . Two-Phase Commit . . . . . . . . . . . . . . . . . Table Replication . . . . . . . . . . . . . . . . . . Database Security . . . . . . . . . . . . . . . . . . . . Security Mechanisms . . . . . . . . . . . . . . . . Database Users and Schemas . . . . . . . . . . Privileges . . . . . . . . . . . . . . . . . . . . Roles . . . . . . . . . . . . . . . . . . . . . . Audits . . . . . . . . . . . . . . . . . . . . . . Database Backup and Recovery . . . . . . . . . . . . . Types of Failures . . . . . . . . . . . . . . . . . . . Structures Used in the Recovery . . . . . . . . . . . The Redo Log . . . . . . . . . . . . . . . . . . Control Files. . . . . . . . . . . . . . . . . . . Rollback Segments . . . . . . . . . . . . . . . Database Backups . . . . . . . . . . . . . . . . Accessing Data . . . . . . . . . . . . . . . . . . . . . . SQL Declarations . . . . . . . . . . . . . . . . . . Data Definition Language (DDL) Declarations . . Data Manipulation Language (DML) Declarations iv
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
23 23 24 24 24 25 25 26 26 26 27 28 28 29 29 29 30 30 31 31 32 32 33 34 35 36 37 38 39 40 40 42 42 42 43 44 45 45
Contents
Transaction Control Declarations . . . . . Session Control Declarations. . . . . . . . System Control Declarations . . . . . . . . Built-in SQL Declarations . . . . . . . . . Transactions . . . . . . . . . . . . . . . . . . Committing and Rolling Back Transactions Savepoints. . . . . . . . . . . . . . . . . PL/SQL . . . . . . . . . . . . . . . . . . . . . . Procedures and Functions . . . . . . . . . . . Packages . . . . . . . . . . . . . . . . . . . . Database Triggers . . . . . . . . . . . . . . . Methods . . . . . . . . . . . . . . . . . . . . Data Integrity . . . . . . . . . . . . . . . . . . . Integrity Restrictions. . . . . . . . . . . . . . Keys . . . . . . . . . . . . . . . . . . . . . . Database Triggers . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
Chapter 2 Data Dictionary . Structures . . . . . . . . . . . . Views of Type USER . . . . . USER_TRIGGER_COLS . Views of Type ALL . . . . . . ALL_USERS . . . . . . . Views of Type DBA. . . . . . DBA_CATALOG . . . . . Dual Table . . . . . . . . . . Dynamic Performance Tables. Views . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
45 46 46 46 46 47 48 49 50 50 50 51 52 52 53 54
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
55 55 56 57 57 58 58 58 59 59 66
Chapter 3 Tablespaces and Datafiles. . Tablespaces . . . . . . . . . . . . . . . . . . System Tablespace . . . . . . . . . . . . . Creating Tablespaces. . . . . . . . . . . . Allocation of Space . . . . . . . . . . . . Dictionary-Managed Tablespaces . . . Locally Managed Tablespaces . . . . . Online and Offline Tablespaces . . . . Read-Only Tablespaces . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
67 68 68 68 69 69 69 70 70 v
Contents
Temporary Tablespaces . . . . . . . . . . . . . . . . . . . . 70 Transporting Tablespaces Among Databases . . . . . . . . . . 71 Datafiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Chapter 4 Data Blocks, Extents, and Segments. . . . . Data Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . Understanding PCTFREE, PCTUSED, and Row Chaining . . . Extents. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Segments . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Segments. . . . . . . . . . . . . . . . . . . . . . . . Index Segments . . . . . . . . . . . . . . . . . . . . . . . Temporary Segments . . . . . . . . . . . . . . . . . . . . Rollback Segments. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
73 74 75 77 77 77 77 78 78
Chapter 5 Schema Objects . Tables . . . . . . . . . . . . . . Nested Tables . . . . . . . . Temporary Tables . . . . . . Views . . . . . . . . . . . . . . How a View Works. . . . . . Join Views . . . . . . . . . . Sequences . . . . . . . . . . . . Synonyms . . . . . . . . . . . . Indexes . . . . . . . . . . . . . Clusters . . . . . . . . . . . . . Hash Clusters . . . . . . . . Stored Procedures and Functions. Packages . . . . . . . . . . . Triggers . . . . . . . . . . . . . Roles. . . . . . . . . . . . . . . Database Links . . . . . . . . . . Snapshots . . . . . . . . . . . . Users. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
79 80 82 82 82 84 84 84 85 85 87 88 88 89 90 90 90 90 91
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Part II—SQL Chapter 6 SQL*Plus . . . . . . . . . . . . . . . . . . . . 95 Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 File Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 vi
Contents
Edit Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Find Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Options Menu . . . . . . . . . . . . . . . . . . . . . . . . 100 Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Editing the Command Line . . . . . . . . . . . . . . . . . . . . 104 Correcting Errors . . . . . . . . . . . . . . . . . . . . . 105 Changing a Line . . . . . . . . . . . . . . . . . . . . . 106 Adding a New Line . . . . . . . . . . . . . . . . . . . . 106 Adding Text to the End of a Line . . . . . . . . . . . . . 107 Deleting Lines . . . . . . . . . . . . . . . . . . . . . . 108 The DESCRIBE Command. . . . . . . . . . . . . . . . . . . . . 109 The COLUMN Command . . . . . . . . . . . . . . . . . . . . . 110 Changing Headers . . . . . . . . . . . . . . . . . . . . 110 Formatting Numeric Columns . . . . . . . . . . . . . . 112 Copying Attributes from Columns . . . . . . . . . . . . 114 Displaying the Attributes of a Column . . . . . . . . . . 114 Temporarily Disabling the Attributes of a Column . . . . 115 The SAVE Command . . . . . . . . . . . . . . . . . . . . . . . 116 The GET Command . . . . . . . . . . . . . . . . . . . . . . . . 117 The START Command. . . . . . . . . . . . . . . . . . . . . . . 118 The EDIT Command . . . . . . . . . . . . . . . . . . . . . . . 119 Chapter 7 Basic SQL . . . . . . . . . . . Oracle and SQL . . . . . . . . . . . . . . . . . SQL Language Basics . . . . . . . . . . . . . . Types of SQL Declarations . . . . . . . . . DDL (Data Definition Language) . . . . DML (Data Manipulation Language) . . The SELECT Command . . . . . . . . . . . . . Data Types . . . . . . . . . . . . . . . . . . . Oracle 8 Data Types . . . . . . . . . . . . Synonyms . . . . . . . . . . . . . . . Numeric Data Type . . . . . . . . . . . Character Data Type . . . . . . . . . . Date Data Type. . . . . . . . . . . . . Binary Data Type . . . . . . . . . . . . Rowid . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
121 122 122 122 123 123 124 130 131 132 133 133 134 135 135
vii
Contents
Expressions and Operators . Precedence of Operators Types of Operators . . . Functions . . . . . . . . . . The INSERT Command . . . Data Integrity . . . . . The UPDATE Command . . . The DELETE Command . . . Transactions . . . . . . . . PL/SQL Commands . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
136 137 137 142 145 148 149 149 151 154
Chapter 8 Data Integrity . . . . . . . . Types of Integrity . . . . . . . . . . . . . . . . Nulls . . . . . . . . . . . . . . . . . . . . Unique Values . . . . . . . . . . . . . . . Primary Key Values . . . . . . . . . . . . . Referential Integrity . . . . . . . . . . . . Triggers. . . . . . . . . . . . . . . . . . . . . Integrity Constraints . . . . . . . . . . . . . . Understanding Constraints . . . . . . . . . NOT NULL Constraints . . . . . . . . . UNIQUE KEY Constraints. . . . . . . . PRIMARY KEY Constraints . . . . . . . FOREIGN KEY Constraints . . . . . . . SELF-REFERENTIAL Constraints . . . . CHECK Constraints. . . . . . . . . . . Deferred Constraints . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
159 160 160 160 161 161 161 162 162 163 163 164 164 165 167 167
Chapter 9 Creating and Maintaining Tables . . The CREATE TABLE Command . . . . . . . . . . . . . Creating a Table with the Contents of Another Table Using the PARALLEL Option . . . . . . . . . . Constraint Disabling . . . . . . . . . . . . . . . . Modifying Tables . . . . . . . . . . . . . . . . . . . . Considerations and Limitations . . . . . . . . . . . The ALTER TABLE Command . . . . . . . . . . . .
. . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
169 169 179 180 180 181 181 182
Part III—Schema Objects
viii
Contents
Using the PARALLEL Option Enabling a Constraint . . . Changing a Column . . . . Adding Columns . . . . . . Eliminating a Column . . . Deleting a Table . . . . . . . . Index-Organized Tables. . . . . CREATE TABLE Command Syntax. .
. . . . . . . .
182 182 183 184 185 186 186 188
Chapter 10 Indexes . . . . . . . . . . . . . . . . When to Create Indexes . . . . . . . . . . . . . . . . . Creating Indexes . . . . . . . . . . . . . . . . . . . . . Creating Indexes with Constraints . . . . . . . . . . Creating Indexes with the CREATE INDEX Command . Creating a Function-Based Index . . . . . . . . . . . Creating an Index Using Key Compression . . . . . . Changing an Index . . . . . . . . . . . . . . . . . . . . Re-creating an Index . . . . . . . . . . . . . . . . . . . Obtaining Information about Indexes . . . . . . . . . . . Eliminating an Index . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
203 205 205 205 206 209 210 211 212 212 214
Chapter 11 Sequences . . . . . The CREATE SEQUENCE Command. Pseudo-Columns . . . . . . . . . . currval and nextval . . . . . . . rowid. . . . . . . . . . . . . . rownum . . . . . . . . . . . . Creating a Sequence . . . . . . . . Checking a User’s List of Sequences . Deleting a Sequence . . . . . . . . Changing a Sequence . . . . . . . . Using a Sequence . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
217 217 219 219 220 221 222 222 223 224 225
Chapter 12 Views . . . . . . How a View Works . . . . . . . . Advantages of Using a View . Restrictions on Using a View . Properties and Privileges of a View Creating a View. . . . . . . . . .
. . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . .
. . . . . . . . . . . . . . . . . .
231 232 232 233 233 234
. . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
ix
Contents
x
A View Based on a Table . . . . . . . . . . . . A View Based on Two Tables (Join View) . . . . Using the SELECT Command in a View . . . . . . . Deleting a View . . . . . . . . . . . . . . . . . . . Using Views to Change Tables. . . . . . . . . . . . The UPDATE Command . . . . . . . . . . . . . . . The INSERT Command . . . . . . . . . . . . . . . Replacing a View . . . . . . . . . . . . . . . . . . Viewing the Definitions of the View . . . . . . . . . Materialized Views . . . . . . . . . . . . . . . . . Designing Multiple Tables and Views Simultaneously
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
235 236 239 240 240 242 243 243 244 245 245
Chapter 13 Users, Privileges, and Roles Users . . . . . . . . . . . . . . . . . . . . . . The CREATE USER Command . . . . . . . Creating a New User . . . . . . . . . . . . The GRANT Command . . . . . . . . . . . Deleting a User . . . . . . . . . . . . . . . Privileges . . . . . . . . . . . . . . . . . . . . System Privileges . . . . . . . . . . . . . . Object Privileges . . . . . . . . . . . . . . Assigning Object Privileges to a User/Role . Viewing Users and Privileges . . . . . . . . Revoking a System Privilege . . . . . . . . Revoking an Object Privilege . . . . . . . . Roles . . . . . . . . . . . . . . . . . . . . . . Creating a Role . . . . . . . . . . . . . . . Granting Privileges and Roles to a Role . . . Granting a Role to a User. . . . . . . . . . Viewing the Roles of a User. . . . . . . . . Deleting a Role . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
249 249 249 252 253 255 256 257 259 260 264 265 266 267 268 270 271 271 272
Chapter 14 Synonyms . . . . . . . . . . The CREATE SYNONYM Command . . . . . . . Creating Synonyms for Tables of Other Users . . Renaming Synonyms . . . . . . . . . . . . . . Removing Synonyms . . . . . . . . . . . . . . Obtaining Information on the Schema Objects .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . .
. . . . . . . . . . . . . . . . . .
275 276 277 278 279 281
Contents
Part IV—PL/SQL Chapter 15 PL/SQL . . . . . . . PL/SQL Blocks . . . . . . . . . . . . Declaration Section. . . . . . . . Variables and Constants . . . Execution Section . . . . . . . . Exception Section . . . . . . . . How PL/SQL Works. . . . . . . . . . Control Structures . . . . . . . . The IF..THEN Command . . . The LOOP Command . . . . . The FOR..LOOP Command . . The WHILE Command . . . . Integrating SQL in a PL/SQL Program Practical Examples . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
287 288 289 289 291 291 292 292 293 295 296 297 298 300
Chapter 16 Triggers . . . . . . . . . . . Restrictions . . . . . . . . . . . . . . . . . . . Components of a Trigger . . . . . . . . . . . . Types of Triggers . . . . . . . . . . . . . . . . Table Triggers . . . . . . . . . . . . . . . Statement-Level Trigger . . . . . . . . Row-Level Trigger . . . . . . . . . . . INSTEAD OF Triggers. . . . . . . . . . . . System Event and User Event Triggers . . . Creating a Trigger . . . . . . . . . . . . . . . Modifying a Trigger . . . . . . . . . . . . . . . Enabling/Disabling a Trigger . . . . . . . . . . Deleting a Trigger. . . . . . . . . . . . . . . . References to Columns Inside a Trigger . . . . . Validating the Data Entry . . . . . . . . . . . . Compilation Errors . . . . . . . . . . . . . . . Replicating with Triggers . . . . . . . . . . . . Obtaining Information about a Trigger . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
307 308 309 310 310 311 311 312 312 314 317 317 318 318 319 320 322 326
Chapter 17 Stored Procedures and Functions . . . . . 329 Creating a Stored Procedure . . . . . . . . . . . . . . . . . . . 331
xi
Contents
Executing a Stored Procedure. Deleting a Stored Procedure . Functions . . . . . . . . . . . Creating a Function . . . Executing a Function . . .
xii
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
Chapter 18 Packages . . . . . Package Structure. . . . . . . . . . Specification Section . . . . . . Package Body. . . . . . . . . . Using Navigator . . . . . . . . . . Creating a Package in Navigator Creating the Body in Navigator . Referencing a Package Subprogram . Recompiling a Package . . . . . . . Deleting a Package . . . . . . . . . Oracle Packages. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
Chapter 19 Cursors . . . . . . . . . . . Creating a Cursor . . . . . . . . . . . . . . . . Declaring the Cursor . . . . . . . . . . . . Opening a Cursor. . . . . . . . . . . . . . Attributes of an Explicit Cursor . . . . . Attributes of an Implicit Cursor. . . . . Accessing the Cursor Rows . . . . . . . . . Closing a Cursor . . . . . . . . . . . . . . A Practical Example. . . . . . . . . . . . . . . Using the FOR..LOOP . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
Chapter 20 Transactions . . . . . . . . Transaction Management . . . . . . . . . . . . Discretionary Transaction Management. . . Transaction Declaration and Control . . . . . . Committing Transactions . . . . . . . . . . . . Two-Phase Commit . . . . . . . . . . . . . Rolling Back Transactions . . . . . . . . . . . . Rollback at Declaration Level . . . . . . . . Savepoints . . . . . . . . . . . . . . . . . Autonomous Transactions. . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . .
. . . . .
. . . . .
335 337 338 338 342
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
345 345 345 346 347 347 348 349 349 350 351
. . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
353 354 354 356 357 358 359 361 361 362
. . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
365 366 366 367 368 368 370 371 371 372
Contents
Autonomous PL/SQL Blocks . . . . . . . . . . . . . . . . . 373 Transaction Control Declarations in Autonomous PL/SQL Blocks . . . . . . . . . . . . . . . . . . . . . . . . 374
Part V—Distributed Processing Chapter 21 Distributed Processing . . . Oracle’s Client/Server Architecture . . . . . . . Distributed Processing . . . . . . . . . . . Net8 . . . . . . . . . . . . . . . . . . . . . . How Net8 Works . . . . . . . . . . . . . . Network Listener . . . . . . . . . . . . . . Multitiered Architecture . . . . . . . . . . . . Clients . . . . . . . . . . . . . . . . . . . Application Servers . . . . . . . . . . . . . Database Servers . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
377 377 378 380 381 382 383 384 384 384
Chapter 22 Replication . . . . . . . . . Replication Objects . . . . . . . . . . . . . . . Replication Groups . . . . . . . . . . . . . . . Replication Sites . . . . . . . . . . . . . . . . Multimaster Replication. . . . . . . . . . . . . Snapshot Replication . . . . . . . . . . . . . . Updatable Snapshots . . . . . . . . . . . . Using Snapshot Replication . . . . . . . . . Disconnected Environments. . . . . . . . . . . Hybrid Snapshots . . . . . . . . . . . . . . . . Administering a Replicated Environment . . . . Replication Conflicts . . . . . . . . . . . . . . Procedure Replication . . . . . . . . . . . Conflict Detection . . . . . . . . . . . . . Synchronous Data Propagation . . . . . . . Synchronous Data Replication . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
385 385 386 387 389 390 391 392 393 393 395 395 396 397 397 397
Part VI—Utilities Chapter 23 Export . . . . . . . . . . . . . . . . . . . . 401 Export Methods. . . . . . . . . . . . . . . . . . . . . . . . . . 402 xiii
Contents
Table Mode. . . . . . . . . . . . . . . . . . . User Mode . . . . . . . . . . . . . . . . . . . Full Mode . . . . . . . . . . . . . . . . . . . Execution Modes . . . . . . . . . . . . . . . . . . The EXP Command . . . . . . . . . . . . . . . . . Obtaining Help . . . . . . . . . . . . . . . . . . . Executing the Export Program . . . . . . . . . . . Command Line Mode. . . . . . . . . . . . . . Interactive Mode . . . . . . . . . . . . . . . . The Parameter File . . . . . . . . . . . . . . . Exporting in User Mode. . . . . . . . . . . . . . . Warning Messages . . . . . . . . . . . . . . . Exporting in Full Mode . . . . . . . . . . . . . . . Incremental, Cumulative, and Complete Exports
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
Chapter 24 Import. . . . . . . . Import Methods. . . . . . . . . . . . Table Mode. . . . . . . . . . . . User Mode . . . . . . . . . . . . Full Mode . . . . . . . . . . . . Execution Modes . . . . . . . . . . . The IMP Command . . . . . . . . . . Obtaining Help . . . . . . . . . . . . Importing Data from the Schema Itself Importing Data to Existing Tables . . . Importing Objects from Other Users .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
402 402 402 403 403 406 408 408 409 410 410 411 412 413
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
415 416 416 416 416 417 418 420 422 424 424
Chapter 25 DBVERIFY . . . . . . . . . . . . . . . . . . 427 DBVERIFY Syntax. . . . . . . . . . . . . . . . . . . . . . . . . 427 Obtaining Help . . . . . . . . . . . . . . . . . . . . . . . . . . 428 Chapter 26 SQL*Loader . Working Schema . . . . . . . Discarded or Rejected Records Bad File . . . . . . . . . Discard File. . . . . . . . Log File . . . . . . . . . The SQL*Loader Control File . Input Datafiles . . . . . . Stream Record Format xiv
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
431 431 432 432 432 432 433 434 434
Contents
Fixed Record Format . . Variable Record Format. The SQLLDR.EXE Program . . . Control File Commands . . . . . Comments . . . . . . . . . Load Data . . . . . . . . . Infile . . . . . . . . . . . . Append/Replace/Truncate . Delimiters . . . . . . . . . . . Terminated Fields . . . . . Enclosed Fields . . . . . . . WHEN . . . . . . . . . INTO TABLE . . . . . . Columns and Fields . . . . TRAILING NULLCOLS . . . Practical Example . . . . . . . . The Control File . . . . . . The LOG File . . . . . . . . The Bad File . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
Chapter 27 Oracle Web Publishing Assistant . Creating a Page . . . . . . . . . . . . . . . . . . . . The Specify Additional Query Criteria Button. . . Creating and Maintaining an Updatable Web Page . . Using Publishing Assistant . . . . . . . . . . . . . . Generating a Query of a Stored Web Page . . . . Deleting a Query of a Stored Web Page . . . . . . Checking and Changing the Properties of a Query Login Information Tab . . . . . . . . . . . . Query Tab . . . . . . . . . . . . . . . . . . Scheduling Tab. . . . . . . . . . . . . . . . File Options Tab . . . . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
435 436 437 438 438 439 439 439 440 440 440 441 441 441 441 442 443 445 447
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
451 451 455 458 460 461 461 461 462 462 463 464
Part VII—Internet Resources
Index . . . . . . . . . . . . . . . . . . . . . . . . . . 467
xv
Introduction This book provides the system developer with an introduction to the Oracle8i database. Oracle8i has so many features and resources that it is virtually impossible to cover them in one book. Therefore, this book focuses on those areas related to application development. Because this book concentrates on the programming features rather than product administration resources, it is most suitable for new Oracle developers. This book’s 27 chapters teach you the basic concepts needed to understand the functionality and features of Oracle8i. The book is organized into seven parts, which are described below.
Part I: Basic Concepts The book begins with an overview of Oracle8i, showing its basic concepts and details about its main components, such as the data dictionary, tablespaces, and other structures. Chapter 1: Introduction to the Oracle Server Chapter 2: Data Dictionary Chapter 3: Tablespaces and Datafiles Chapter 4: Data Blocks, Extents, and Segments Chapter 5: Schema Objects
Part II: SQL In the second part of the book you will learn how the SQL*Plus utility works and receive an introduction to the SQL language. Chapter 6: SQL*Plus
xvii
Introduction
Chapter 7: Basic SQL
Part III: Schema Objects The third part is dedicated to the creation and maintenance of Oracle’s schema objects, such as tables, indexes, views, users, and sequences. The reader will learn how to use the SQL commands that work with these objects. Chapter 8: Data Integrity Chapter 9: Creating and Maintaining Tables Chapter 10: Indexes Chapter 11: Sequences Chapter 12: Views Chapter 13: Users, Privileges, and Roles Chapter 14: Synonyms
Part IV: PL/SQL After you learn how to create and maintain the schema objects, we will go a little further into the use of PL/SQL, Oracle’s procedural language. In this part we show how to create triggers, stored procedures, and packages, and introduce the concept of cursors. Chapter 15: PL/SQL Chapter 16: Triggers Chapter 17: Stored Procedures and Functions Chapter 18: Packages Chapter 19: Cursors Chapter 20: Transactions xviii
Introduction
Part V: Distributed Processing This part is somewhat more conceptual and shows how Oracle8i works in a distributed environment, as well as the replication of tables and databases. Chapter 21: Distributed Processing Chapter 22: Replication
Part VI: Utilities Here we show how some of Oracle’s utilities work. These utilities, which include Export, Import, DBVERIFY, and SQL*Loader, are extremely useful for the developer. Chapter 23: Export Chapter 24: Import Chapter 25: DBVERIFY Chapter 26: SQL*Loader
Part VII: Internet Resources This last part explains how to use Oracle’s publishing wizard to create HTML pages containing queries made to the database. Chapter 27: Oracle Web Publishing Assistant This book is designed to provide a good foundation for developers who want to learn about Oracle8i. After you master the concepts covered here, you may want to read books that focus on other resources of the product in order to expand your knowledge. If you have any comments about this book, contact the author via e-mail:
[email protected].
xix
Part I
BASIC CONCEPTS The book begins with an overview of Oracle8i, showing its basic concepts and details about its main components, such as the data dictionary, tablespaces, and other structures. Chapter 1: Introduction to the Oracle Server Chapter 2: Data Dictionary Chapter 3: Tablespaces and Datafiles Chapter 4: Data Blocks, Extents, and Segments Chapter 5: Schema Objects
1
Chapter 1
Introduction to the Oracle Server This chapter provides an overview of the Oracle database and its physical and logical structure, so that you understand the relationship and purpose of each component of a database.
The Oracle Server The Oracle server is a relational database management system of an object that is formed by the database and an instance of the Oracle server.
The Database Structure An Oracle database has a physical structure as well as a logical structure. Since these structures are separate in the server, the physical storage of data can be managed without affecting the access to the logical storage structures.
The Physical Database The files that constitute the operating system determine the physical structure of the database. Each database is formed by three
3
Chapter 1—Introduction to the Oracle Server
types of files: one or more datafiles, two or more redo record files, and one or more control files. These files provide real physical storage for Oracle’s information.
The Logical Database The logical structure of Oracle is determined by one or more tablespaces—logical storage spaces—and by the schema objects of the database. A schema is a collection of objects that, in turn, are the logical structures that refer directly to the data in the database. The schema objects include structures such as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links. The logical storage structures, including tablespaces, segments, and extents, tell how the physical space in a database is used. The schema objects and relationships among them form the relational project of a database.
An Oracle Instance Whenever a database is initialized, a system global area (SGA) is allocated and the background processes of Oracle are initiated. The system global area is an area pertaining to the memory used for information that is shared by the database’s users. The combination of the background processes and memory buffers is called an Oracle instance. An instance has two types of processes: user processes and Oracle processes.
: :
4
A user process executes the code of an application program, such as Oracle Forms, Oracle Tools, or the Oracle Enterprise Manager. Oracle processes include server processes, which do the work for the user, and background processes, which do the maintenance work of the Oracle server.
Introduction to the Oracle Server—Chapter 1
User
User
User
User processes
User
System Global Area (SGA)
Recoverer (RECO)
Figure 1.1:
Process Monitor (PMON)
System Monitor (SMON)
Database Writer (DBWO)
Log Writer (LGWR)
Archiver (ARCO)
Oracle processes (background processes)
An Oracle instance.
Database Structure and Space Management This section describes the structures that form an Oracle database. Here you’ll learn about Oracle’s solutions for the controlled availability of data, logical and physical separation of data structures, and more rigid control of disk space management. Oracle is a collection of data that is treated as a unit. The objective of a database is to store and recover related information.
Logical Database Structures The logical structures of an Oracle database include tablespaces, schema objects, data blocks, extents, and segments.
5
Chapter 1—Introduction to the Oracle Server
Tablespaces A database is organized into logical storage units called tablespaces that also group together related logical structures. For example, generally the tablespaces group all the software objects to simplify some administrative operations.
Databases, Tablespaces, and Datafiles The relationship among databases, tablespaces, and datafiles (datafiles are described later in the chapter) is shown below. Database System Tablespace
DATA1.ORA 1 Mb
Figure 1.2:
DATA2.ORA 1 Mb
Users Tablespace
DATA3.ORA 4 Mb
Databases, tablespaces, and datafiles.
This figure illustrates the following:
: : : :
6
Each database is logically divided into one or more tablespaces. One or more datafiles are explicitly created for each tablespace in order to physically store data of every logical structure. The combined size of datafiles in a tablespace represents its total storage capacity. In the figure the System tablespace has a storage capacity of 2 MB, while the Users tablespace has 4 MB. The combined storage capacity of a database’s tablespaces represents the total storage capacity of a database (6 MB in Figure 1.2).
Introduction to the Oracle Server—Chapter 1
Online and Offline Tablespaces A tablespace can be online (available) or offline (not available). Generally, it is online so that users can access needed information. However, a tablespace can be offline to make part of the database unavailable, allowing simultaneous access to the other part of the database. This allows for the easy execution of many administrative tasks.
Schemas and Schema Objects A schema is a collection of the objects in a database. The schema objects are logical structures that refer directly to data. These objects include structures such as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links. (There is no relationship between a tablespace and a schema; the objects of a schema can be located in different tablespaces, and a tablespace may contain objects of different schemas.)
Data Blocks, Extents, and Segments Oracle allows you to strictly control disk space through logical storage structures, including data blocks, extents, and segments.
Data Blocks Data blocks are the smallest form in which Oracle data is stored. A data block corresponds to a specific number of bytes in a disk. When it is created, the size of the data block is specified for each database. A database uses and allocates free space in Oracle’s data blocks.
Extents The next level of the logical space in a database is called an extent. An extent is a specific number of contiguous data blocks, obtained in a simple allocation and used to store certain types of information. 7
Chapter 1—Introduction to the Oracle Server
Segments The level of logical storage space that is above an extent is called a segment. It is a set of extents allocated to certain logical structures. The different types of segments include: Each non-clustered table has a data segment. All of its data is stored in the extents of its data segment. In a partitioned table, each partition has a data segment. Each cluster has a data segment. The data in its tables is stored in the cluster’s data segment. Each index has an index segment that stores all of Index segment its data. In a partitioned index, each partition has an index segment. The database administrator can create one or Rollback segment more rollback segments of the database to temporarily store “undo” information. Temporary segment Oracle creates a temporary segment when an SQL declaration needs a temporary work area in order to complete the execution. When the declaration finishes the execution, the temporary segment extents are returned to the system for future use. Data segment
Oracle dynamically allocates space when the existing extents of a segment are full. When the existing extents are full, Oracle allocates another extent to that segment, as needed. Since the extents are allocated as needed, the extents of a segment may or may not be contiguous on the disk.
Physical Database Structures The following sections describe the physical structures of an Oracle database, including datafiles, redo record files, and control files.
8
Introduction to the Oracle Server—Chapter 1
Datafiles Every Oracle database has one or more physical datafiles. These datafiles contain all the data in the database. The data of the logical structures, such as tables and indexes, are physically stored in the allocated datafiles. Datafiles have the following characteristics:
: : :
A datafile can be associated to only one database. The database files have certain characteristics that are defined in order to allow them to automatically extend themselves when they run out of space. One or more datafiles form a logical storage unit called a tablespace.
Using the Datafiles The data in a datafile is read as needed during the normal operation of a database, and is stored in the memory cache. For example, suppose that a user wants to access some data from a database table. If the needed information is on the memory cache, it is read in the appropriate datafiles and stored in the memory. The modified or new data doesn’t necessarily need to be written immediately to a datafile. In order to reduce the amount of access to the disk and to improve performance, all data is saved in the memory and written to the appropriate datafiles at the same time, as determined by the background process DBWn.
Redo Record Files Every Oracle database has one or two sets of redo record files. They are collectively known as the redo record of the database. A redo record comprises the redo entries (also called the redo record files), and each is a group of changing vectors that describe only one atomic change made to the database.
9
Chapter 1—Introduction to the Oracle Server
The main function of a redo record is to register all the changes made to data. If a failure prevents the permanent writing of modified data to the datafiles, the changes can be obtained through the redo record. The redo record files are critical to protect a database against failures. To protect itself, Oracle allows a multiplexed redo record, so that two or more copies of it can be maintained in different disks.
Using the Redo Record Files The information in a redo record file is only used to recover a database when some system or media failure prevents the writing of data in the datafiles. For example, when a power failure suddenly stops the operation of a database, data in memory cannot be written to datafiles and is lost. However, the lost data can be recovered when the database is opened after the power is restored. By applying information contained in the most recent redo record files to datafiles, Oracle can restore them to how they were at the time the power outage occurred. The use of the redo record during the recovery operation is called “rolling forward.”
Control Files Every Oracle database has a control file, which contains entries that specify the physical structure of the database. A control file may contain the following information:
: : :
Name of the database. Names and locations of the database datafiles and the redo record files. Time stamp for database creation.
Like the redo record, Oracle allows the control file to be multiplexed for its own protection. 10
Introduction to the Oracle Server—Chapter 1
Using the Control Files Whenever an instance of an Oracle database is initialized, its control file is used to identify those files of the database and the redo log that must be opened so that the operation may continue. When the physical arrangement of the database changes (for example, when a new datafile or a redo log file is created), Oracle automatically modifies the control file in order to reflect such a change.
Memory and Process Structures This section covers the memory and process structures that are used by an Oracle server to manage a database. The resources mentioned here allow the user to understand the capabilities supported by Oracle, including the following:
: :
The ability for several users to access a database at the same time. The high performance required by current database systems from different users and applications.
An Oracle server uses memory structures and processes to manage and access the database. All these structures exist in the main memory of computers, and constitute the database system. Processes are jobs or tasks that work in the memory of those computers.
Memory Structures Oracle creates and uses the memory structures to perform several tasks. For instance, the memory stores the code of a program that is executed and the data that is shared among users. Several basic memory structures are associated with Oracle, including the system global area (database buffers, redo log buffers, and shared
11
Chapter 1—Introduction to the Oracle Server
pool) and the program global area. The following subsections explain the details of each of them.
LCKO
PMON
RECO
SMON
System Global Area Redo Log Buffer
Database Buffer Cache
User Process
Shared Server Process
Dedicated Server Process
User Processes
ARCO
CKPT D000
DBWO
Legend: LCKO RECO PMON SMON CKPT ARCO DBWO LGWR
Lock process Recoverer process Process monitor System monitor Checkpoint Archiver Database writer Log writer
Offline Storage Device
LGWR
User Process
Control Files
Redo Log Files
Datafiles
Figure 1.3:
Memory structures and processes of Oracle.
System Global Area (SGA) The system global area (SGA) is a shared region in the memory that contains data and control information for an Oracle instance. An SGA and the background processes form an Oracle instance. The database allocates the system global area when an instance is initiated and deallocates it when it is closed. Each instance has its own system global area.
12
Introduction to the Oracle Server—Chapter 1
The users who are connected at that moment to an Oracle server can share the data contained in the system global area. To achieve the ideal performance, this area must have the maximum size possible (within the memory limitations) in order to store the maximum amount of data possible and to minimize the I/O to and from the disk. Information stored inside the system global area is divided into several types of memory structures, including database buffers, redo log, and shared pool. These areas have fixed sizes and are created during the instance initialization.
Database Buffer Cache The database buffers in the system global area store the data blocks used most recently. The set of database buffers of an instance forms the database buffer cache. It contains modified and non-modified blocks. Since data used more recently (and often more frequently) is maintained in the memory, less I/O to and from the disk is necessary, and the performance is improved.
Redo Log Buffer The redo log buffer of the system global area stores the redo entries, which is a log containing the changes made to the database. The redo entries stored in the redo log buffers are written to an online redo log file that is used when database recovery is needed. Its size is static.
Shared Pool The shared pool contains shared memory structures, such as the SQL shared areas. This is required for the processing of each unique SQL declaration that is submitted to a database, and contains information such as the analysis tree and the execution plan for the corresponding declaration. A unique area of shared SQL is used by several applications that issue the same declaration, thus leaving more shared memory for other uses. 13
Chapter 1—Introduction to the Oracle Server
Large Pool The large pool is an optional area of the SGA that provides large allocations of memory for the backup and restoration operations in Oracle, the server processes of I/O, and the session memory for the multithreaded server and Oracle XA.
Cursors A cursor is a handle (a name or pointer) to the memory associated to a specific declaration. (The Oracle Call Interface (OCI) calls them declaration handles.) While most Oracle users depend on the automatic cursor management of the utilities of this software, the programmatic interfaces offer greater control over the cursors to the application developers. For example, in the precompiler application development, a cursor is a resource named as available to a program, which can be used specifically in the analysis of SQL declarations built inside the application. The application developer can code it so that it controls the execution phases of the SQL declaration, thus improving its performance.
Program Global Area (PGA) The program global area (PGA) is a memory buffer containing data and control information for a server process. A PGA is created by Oracle when a server process is initiated. The information in a PGA depends on the configuration of Oracle.
Process Architecture A process is a “control thread,” or a mechanism of an operating system that can execute a series of steps. Some of these systems use the term “job” or “task.” Normally a process has its own private memory area in which it is executed.
14
Introduction to the Oracle Server—Chapter 1
An Oracle server has two general types of processes: user processes and Oracle processes.
User Processes (Client) A user process is created and maintained to execute the software code of an application (such as the program Pro*C/C++) or an Oracle tool (such as the Oracle Enterprise Manager). The user process also manages the communication with the server processes. The user processes communicate with the server processes through the program interface, which is described later in this book.
Oracle’s Process Architecture Other processes to execute functions on behalf of the process that is invoking the function call the Oracle processes. The different types of Oracle processes and their specific functions are discussed below. They include the server processes and the background processes.
Server Processes Oracle creates the server processes to deal with the requests of processes made by a user who is connected. A server process deals with the communication with the user and the interaction with Oracle, so as to execute the user’s process requests. For example, when a user queries a piece of data that is not yet on the database buffers in the system global area, the associated server process reads the appropriate data blocks of datafiles to the system global area. Oracle can be configured to vary the number of user processes by server process. In a dedicated server configuration, a server process deals with the requests of only one user process. A multi-
15
Chapter 1—Introduction to the Oracle Server
threaded server configuration allows many user processes to be shared by a small number of server processes, thus minimizing the number of server processes and maximizing the use of available system resources. In some systems, the user and server processes are separate, while in others they are combined into one process. When a system uses a multithreaded server or when the user and server processes are executed in different machines, they must be separated. The client/server systems separate and execute them in different machines.
Background Processes Oracle creates a set of background processes for each instance. These consolidate the functions that otherwise would be treated by several Oracle programs that would be executed for each user process. The background processes asynchronously execute the I/O and monitor other Oracle processes, so as to provide more symmetry with better performance and reliability.
Database Writer (DBWn) The database writer writes the changed blocks of the database buffer cache to datafiles. While this is enough in most systems, you can configure additional processes (DBW1 up to DBW9) to improve the performance of a system with many changes to data. The initialization parameter DB_WRITER_PROCESSES specifies the number of processes of DBWn. Since Oracle uses the write-ahead log, it does not have to write the blocks when a transaction is made. Instead, DBWn was created to execute effective batch writing. In the most common case, the DBWn writes only when more data must be read in the system global area and few database buffers are available. Less recent data is written first to the datafiles. DBWn also writes other functions, such as checkpointing.
16
Introduction to the Oracle Server—Chapter 1
Log Writer (LGWR) The log writer writes the entries to the redo log to disk. These entries are generated in the redo log buffer of the system global area (SGA). The LGWR writes the entries to the redo log sequentially in an online redo log file. When a database has a multiplexed redo log, the LGWR also writes the entries to the redo log in a group of online redo log files.
Checkpoint (CKPT) In some specific cases, the DBWn writes all the buffers of the changed database in the system global area to the datafiles; this event is called checkpoint. The process is responsible for signaling the checkpoints to the DBWn; updating all the files, including those that control the database; and indicating the most recent one.
System Monitor (SMON) The system monitor executes the recovery when an instance that failed is reinitialized. In a system with several instances (a system that uses the Oracle Parallel Server), the SMON process of an instance can execute the recovery of another instance that has failed. The SMON also cleans the temporary segments that are not being used anymore, and recovers the “dead” transactions that were skipped during the failure and recovery of the instance, due to the file read or offline errors. Eventually, these transactions are recovered by SMON when the tablespace or the file is brought back online. It also unites the free extents inside the tablespaces managed by the database dictionary, in order to free contiguous free space and to ease the allocation.
Process Monitor (PMON) The process monitor executes the recovery when a user process fails. The PMON is responsible for cleaning the cache and freeing resources that have been used by the process. It also checks the 17
Chapter 1—Introduction to the Oracle Server
dispatcher and the server processes and reinitializes when there are failures.
Archiver (ARCn) The archiver copies the online redo files to store the file when they are full, or when the log is switched. While one ARCn (ARC0) process is enough for most systems, you can specify up to ten using the dynamic initialization parameter LOG_ARCHIVE_MAX_PROCESSES. When the workload is too big for the current number of ARCn processes, the LGWR automatically initiates another ARCn process up to the maximum of ten processes. It is active only when a database is in ARCHIVELOG mode and automatic filling is activated.
Recoverer (RECO) The recoverer is used to transform distributed transactions that are pending due to a network failure or a failure that occurred in the system of a distributed database. At certain intervals, local RECO tries to connect itself to the remote databases and automatically complete the commit or rollback of the local part of transactions.
Dispatcher (Dnnn) The dispatchers are optional background processes, which are present only when a multithreaded server configuration is used. At least one dispatcher process is created for each communication protocol that is being used (D000. . . Dnnn). Each of its processes is responsible for the routing requests of the user processes connected to the available processes of the shared server, and by the return of answers to the appropriate user processes.
Lock (LCK0) The lock (LCK0) process is used to block instances in the Oracle Parallel Server. 18
Introduction to the Oracle Server—Chapter 1
Job Queue (SNPn) In a distributed database configuration, up to 36 processes in the task queue (SNP0. . . SNP9, SNPA. . . SNPZ) can automatically refresh table snapshots. These processes “awake” with certain frequency and refresh all the snapshots that are programmed for automatic refreshing. When more than one process of the task queue is used, the processes share the task of refreshing the snapshots. These processes also execute the requests of tasks created by the DBMS_JOB package and propagate the messages of the queue to those of other databases.
Queue Monitor (QMNn) Queue monitors are optional background processes that monitor the message queues in Oracle Advanced Queuing (Oracle AQ). You can configure up to ten processes in it.
The Program Interface The program interface is the mechanism by which a user process communicates with a server process. It works as a standard communication method between any type of client or application tool, such as Oracle Forms, and the Oracle software. The interface functions are as follows:
: :
To act as a communication mechanism, formatting and passing data requests and detecting and returning errors. To execute data conversions and translations, particularly to and from different types of computers or with data types of an external user program.
19
Chapter 1—Introduction to the Oracle Server
How Oracle Works The following steps describe an Oracle configuration in which the user and the associated server process are located in separate machines and are connected through a network: 1. An instance is executed in a computer where Oracle is configured (most often called host or database server). 2. A computer executing an application (a local machine or a client workstation) executes the application in a user process. The client application tries to establish a connection with the server, using the appropriate Net8 driver. 3. The server executes the appropriate Net8 driver and detects the request for connection from the application, thus creating a (dedicated) server process on behalf of the user process. 4. The user executes a SQL declaration and submits the transaction. For example, the user changes a name in a table’s row. 5. The server process receives the declaration and checks the shared pool of the shared SQL area containing an identical SQL declaration. If a shared SQL area is found, the server process checks the user’s access privileges to data requested, and this pre-existing area is used to process the declaration; otherwise, a new shared SQL area is allocated to the declaration, allowing it to be analyzed and processed. 6. The server process recovers all the data values needed from the real datafile (table) or those that are stored in the system global area. 7. The server process changes data in the system global area. The DBWn process permanently writes the changed blocks to disk, if this is an efficient operation. Due to the submitted transaction, the LGWR process immediately records the transaction to the online redo log file.
20
Introduction to the Oracle Server—Chapter 1 8. When the transaction is successful, the server process sends a message through the network to the application. Otherwise, an appropriate error message is transmitted. 9. In this procedure, other background processes are executed, observing the conditions that require intervention. In addition, the database server also manages other user transactions and prevents conflicts among the transactions that request the same data.
These steps describe the most basic level of the operations performed by Oracle.
Oracle and Net8 Net8 is Oracle’s interface mechanism among the communications protocols used by the networks in order to ease the distributed processing of the distributed databases. The communications protocols define the way in which data is transmitted and received in a network. In a network environment, an Oracle database server communicates with the client workstations and other servers that use Net8. Net8 supports communications in each of the main network protocols, from those supported by PC LANs to those used by major mainframe systems. When using Net8, the software developer does not need to worry about support for network communications in a database application. When a new protocol is used, the database administrator makes some minor changes, while the application does not require any change at all and continues to work. Net8 is explored in more detail in Chapter 21.
21
Chapter 1—Introduction to the Oracle Server
The Object Relational Model for Database Management Database management systems have developed from hierarchical models to network and relational models. The most popular database model is the relational model. Oracle extends it to an object relational model, which allows for the storage of complex business models in a relational database.
The Relational Model The relational model has three important aspects: Structures
Operations
Integrity rules
The structures are well-defined objects (such as tables, views, indexes, and so on) that store or access data in a database. The structures and data contained inside them can be manipulated by the operations. The operations are clearly defined actions that allow the users to manipulate data and database structures. They must follow a predefined set of integrity rules. The integrity rules govern the operations that are allowed in data and in the structures of a database. They protect data and the structures of a database.
Relational database management systems offer benefits such as:
: : : :
22
Independence from the physical storage of data and the logical structure of the database. Diversified and easy access to all data. Complete flexibility when designing the database. Reduced data storage and redundancy.
Introduction to the Oracle Server—Chapter 1
The Object Relational Model The object relational model allows users to define the types of objects, specifying both the structure and the data operation methods and the use of these data types inside the relational model. The object types are abstractions from the real-world entities—for example, purchase requests—with which the software deal. They have three types of components:
: : :
A name that identifies the type of object. Attributes, which are built-in data types or other user-defined types. These model the entity structure in the real world. Methods, which are functions or procedures written in PL/SQL, externally stored in the database, or written in a language such as C. Methods implement the specific operations that an application can execute in data. Every object type has a construction method that creates a new object according to the specification of the data type.
Schemas and Schema Objects A schema is a collection of database objects that are available to the user. Schema objects are the logical structures that directly refer to the database data. They include structures such as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links. (There is no relationship between a tablespace and a schema. Objects in the same schema can be located in different tablespaces, and a tablespace may contain objects of different schemas.)
23
Chapter 1—Introduction to the Oracle Server
Tables A table is the basic storage unit in Oracle. Tables contain all the stored data in rows and columns that can be accessed by the user. Each table is defined with a name and a set of columns. Each column receives a name, a data type (such as char, date, or number), and a size (which can be predetermined by the data type, such as in date) or scale and precision (only for the data type number). After a table is created, rows of data can be inserted, queried, deleted, or updated.
Views A view is a personalized presentation of data from one or more tables. It can also be seen as a “stored query.” Views do not really contain or store data, but they take data from the tables on which they are based, called base tables. The base tables can, in turn, be tables or views. As with tables, the views can be queried, updated, inserted, and deleted, with some restrictions. All the operations performed in a view actually affect the base tables of that view.
Sequences A sequence generates a sequential list of unique numbers for a table’s columns. They simplify application programming by automatically generating numeric values that are unique to the rows of one or several tables. For example, let’s assume that two users are simultaneously inserting rows of new employees in the EMP table. By using a sequence to generate unique numbers for the employees in the Empno column, neither user needs to wait until the other inserts the next available employee number. The sequence automatically generates the correct values for each user.
24
Introduction to the Oracle Server—Chapter 1
Program Units The term program unit is used to refer to stored procedures, functions, packages, triggers, and anonymous blocks. A procedure or function is a set of declarations in SQL and PL/SQL (the SQL extension of Oracle’s procedure language), grouped as an executable unit to work with a specific task. Procedures and functions combine the ease and flexibility of SQL with the functionality of a structured programming language. Using PL/SQL, such procedures and functions can be defined and stored in the database for constant use. Procedures and functions are identical, except that functions always return a unique value and procedures don’t. Packages provide a method for storing related procedures, functions, and other package constructs as a unit of the database. While they provide the database administrator or application developer with the benefits of organization, they also offer more functionality and high performance to the database.
Synonyms A synonym is an alias of a table, view, sequence, or program unit. Actually, a synonym is not a schema object in itself, but a direct reference to it. They are used:
: : : :
To mask the real name and owner of a schema object. To provide public access to a schema object. To provide location transparency for tables, views, or program units of a remote database. To simplify SQL declarations for database users.
A synonym can be public or private. A user can create a private synonym that is available only to him or her. Database administrators often create public synonyms, which make the basic schema object available to any database user. 25
Chapter 1—Introduction to the Oracle Server
Indexes An index is an optional structure associated to tables that increases the data recovery performance. Similar to a book’s index, which allows you to quickly locate information, an Oracle index provides a quick path for accessing data in a table. When processing a request, Oracle can efficiently use some or all of the available indexes to locate the requested rows. Indexes are useful when the applications frequently query a range of rows in a table (for example, all the employees with a salary under $15,000) or a specific row. An index is created for one or more columns of a table. After being created, an index is automatically updated and used by Oracle. The changes made in the table data (such as the addition, updating, or deletion of rows) are automatically incorporated in every relevant index. Indexes are logically and physically independent from data and can be deleted and created at any time, without affecting the tables or other indexes. When they are deleted, all the applications continue working; however, it may take longer to access data that was previously indexed.
Clusters and Hash Clusters Clusters and hash clusters are optional structures for storing data in the tables. They can be created to improve the data recovery performance.
Clustered Tables Clusters are groups of one or more tables that are physically stored together, since they share common columns and often are used together. Because related rows are physically stored together, the disk access time is considerably improved. 26
Introduction to the Oracle Server—Chapter 1
The related columns of the tables in a cluster are called cluster keys. They are indexed so the clustered rows can be recovered with minimum I/O. In the same way that data in the cluster key in an index (a non-hash cluster) is stored only once for several tables, the clusters can store a set of tables more efficiently than when they are stored individually (non-clustered). The clusters also can improve the data recovery performance, depending on the distribution and the SQL operations that are most frequently performed on the data. Particularly, the clustered tables are queried in the associations that benefit from the use of clusters, because the rows common to the tables are recovered in the same I/O operation. As is the case with indexes, clusters do not affect the application design. The fact that a table is part of a cluster is seamless for users and applications alike. Data stored in a clustered table is accessed through SQL similar to data in a non-clustered table.
Hash Clusters Hash clusters also group data in a table in the same way as normal data in an index (the clusters are indexed with an Index function instead of a Hash function). However, a row is stored in a hash cluster based on the result of the application of a Hash function to the key value of the row cluster. All the rows having the same key value are stored together in the disk. Hash clusters are a better alternative to an indexed table or an index cluster when a table is frequently queried with parity queries (for example, return all rows for department 10). In those queries, the key value of the specified cluster is presented again. The resulting value of the Hash key points directly to the area in the disk where the rows are stored.
27
Chapter 1—Introduction to the Oracle Server
Database Links A database link is a named schema object that describes a “path” from one database to another database. Links are implicitly used when a reference is made to the name of a global object in a distributed database.
The Data Dictionary Each Oracle database has a data dictionary, which is a set of tables and views used as a read-only reference about the database. For example, a data dictionary stores information about the logical and physical structures of the database. In addition to these valuable pieces of information, it also stores information such as:
: : :
Valid users of an Oracle database. Information about the integrity restrictions defined for the database tables. When the space is allocated for a schema object and how much of it is being used.
A data dictionary is created when the database is created. To always reflect accurately the status of such a database, Oracle automatically updates the data dictionary when there are specific actions (such as a change in the database structure). It is vital for the operation of the database, which depends on this dictionary in order to log, check, and perform the ongoing work. For example, during database operation Oracle reads the data dictionary and checks whether there are schema objects and if the users have proper access to them.
28
Introduction to the Oracle Server—Chapter 1
Client/Server Architecture: Distributed Processing Distributed processing uses more than one processor to divide the processing into a set of related tasks. It reduces the processing load in one processor, allowing the others to concentrate on a subset of related tasks, thus improving the performance, as well as the system capacities as a whole. An Oracle database system can easily benefit from distributed processing using its client/server architecture. In this architecture, the database system is divided in two parts: a front end or client, and a back end or server.
The Client The client is the front-end application of a database; it interacts with a user through the keyboard, monitor, and mouse. The client has no responsibilities for accessing data; it concentrates on the request, the processing, and the presentation of data managed by the server. The client workstation can be specifically set up for its tasks. For example, it may not need a great amount of disk space or graphic capabilities.
The Server The server executes Oracle software and deals with the functions required for simultaneous and shared data access. The server receives and processes the SQL and PL/SQL declarations that originate in the client applications. The computer that manages the server can be configured to perform its tasks. For example, it may have a greater disk capacity and faster processors.
29
Chapter 1—Introduction to the Oracle Server
Multitiered Architecture: Application Servers A multitiered architecture has the following components:
: :
:
A client or initialization process that initiates the operation. One or more application servers that execute part of the operation. An application server is a process that provides access to data for the client and executes part of the query processing, thus removing part of the load of the database server. It can serve as an interface among clients and several database servers, including an extra supply of security. A database server that serves as a repository for most data used in the operation.
Such architecture allows the use of an application server to:
: : :
Validate the credentials of a client, such as a Web browser. Connect to an Oracle database server. Execute the operation requested by the client.
The identity of the client is maintained in all the layers of the connection. The Oracle database server makes an audit of the operations that the application server performs for the client, separately from those that the application server itself performs (such as a request for a connection with the database server). The application server privileges are limited to preventing it from performing unnecessary and undesired operations during client operations.
Distributed Databases A distributed database has its own network which is managed by several servers that appear to the user as a unique logical database. Data from all the databases of this distributed database can be simultaneously accessed and changed. The main advantage of a distributed database is that physically separated data can be
30
Introduction to the Oracle Server—Chapter 1
logically combined, and can potentially be accessed by all the users of a network. Each computer that manages a database of its own is called a node. The database to which the user is directly connected is called local. All the databases accessed by that user are called remote databases. When a local database accesses information in a remote database, it is the client of the remote server (the client/server architecture that we discussed earlier). While a distributed database allows more access to a great quantity of data through a network, it also has the ability to hide the localization of data and the complexity of their access through the network. The distributed DBMS must also preserve the advantages of each local database administration, as if it were not distributed.
Manipulation of Distributed Data The distributed architecture of the Oracle database supports all the DML operations, including queries, insertions, updates, and deletions of data in a remote table. To access remote data, a reference is made that includes the global name of the remote object—no code or complete syntax is required to access remote data. Let’s suppose that you want to query a table called EMP in the remote Sales database; to do that you have to reference the name of the global object of the table: SELECT * FROM emp@sales;
Two-Phase Commit Oracle provides the same guarantee of data consistency in both a distributed environment and a non-distributed environment. It does this by using a transaction model and a two-phase commit. 31
Chapter 1—Introduction to the Oracle Server
As in non-distributed systems, transactions must be carefully planned in order to include a logical set of SQL declarations, which must either succeed or fail as a unit. Oracle’s two-phase commit guarantees that, independent of the type of system or network failure that occurs, a distributed transaction or a rollback will be submitted in every node involved, maintaining the consistency of data throughout the global distributed database. The two-phase commit is completely seamless for users who issue distributed transactions. A simple COMMIT declaration indicating the end of a transaction automatically triggers its two-phase commit and submits the transaction; no code or complex syntax is needed to include the distributed transactions inside the body of a database application.
Table Replication Distributed database systems often locally replicate remote tables that are frequently queried by local users. By having copies of data accessed in different nodes, the distributed database does not need to always send information through the network, thus helping to maximize the performance of the database application. Data can be replicated using snapshots or replicated master tables.
Database Security Multiuser database systems such as Oracle include security resources that control how a database is accessed and used. These security mechanisms prevent unauthorized access to the database and schema objects; control the use of the disk and system resources (such as the CPU time); and audit the user’s actions. Each database user has an associated schema with the same name. A schema is a logical collection of database objects (tables, views, sequences, synonyms, indexes, clusters, procedures,
32
Introduction to the Oracle Server—Chapter 1
functions, packages, and database links). As the default, each user creates and has the access to all the corresponding schema objects. There are two types of database security: system security and data security. System security encompasses the mechanisms that control the access to and use of the database at a certain level. System security includes:
: : :
Valid combinations of user name and password. The amount of available disk space for the schema objects of a user. A user’s resource limits.
These mechanisms check whether a user is authorized to connect to a database, if the database audit is activated, and which system operations a user can perform. Data security encompasses the mechanisms that control the access and use of the database at the schema object level. Data security includes:
:
:
Which users have access to a specific schema object and what specific types of actions each one can perform on the schema object (for example, user Scott can issue the SELECT and INSERT declarations, but not the DELETE declarations on the EMP table). Auditing the actions, if they exist, for each schema object.
Security Mechanisms Oracle provides arbitrary access control, which is a way to restrict access to privileged information. For a user to access a schema object, he or she must have the appropriate privilege. Users with appropriate privileges can grant them to others, using whatever
33
Chapter 1—Introduction to the Oracle Server
criteria they wish; for this reason, this type of security is called “arbitrary.” Oracle manages database security using several different resources. They include:
: : : : : :
Database users and schemas Privileges Roles Definitions and storage quotas Resource limits Audits
Users
PAY_CLERK Role
MANAGER Role
ACCTS_PAY Role
Privileges to execute the ACCTS_PAY application
Figure 1.4:
REC_CLERK Role
ACCTS_REC Role
Privileges to execute the ACCTS_REC application
User Roles
Application Roles
Application Privileges
Oracle’s security resources.
Database Users and Schemas Each database in Oracle has a list of user names. In order to access a database, an application of this type must be initialized and the user must be connected under a valid user name. Each name has an associated password to avoid unauthorized use.
34
Introduction to the Oracle Server—Chapter 1
Security Domain Each user has a security domain—a set of properties that determines things such as:
: : :
Actions (privileges and roles) available for the user. Tablespace quotas (available disk space) of the user. System resource limits (for example, the processing time of the CPU) of the user.
Each property that contributes to the security domain of a user is discussed in the following sections.
Privileges A privilege is a right to execute a certain type of SQL declaration. Some examples of privileges include:
: : : :
The right to connect to the database (create a session). The right to create a table in a schema. The right to select rows in another person’s table. The right to execute another person’s stored procedure.
Oracle’s database privileges can be divided into two distinct categories: system privileges and schema object privileges.
System Privileges System privileges allow users to execute certain actions at the system level or in a certain type of schema object. For example, the privileges to create a tablespace or to delete rows in any database table are system privileges. Many of them are available only to the administrators and software developers.
Schema Object Privileges Schema object privileges allow users to perform certain actions in a schema object that is itself specific. A privilege that can include, for example, the rows of a specific table is an object privilege. 35
Chapter 1—Introduction to the Oracle Server
These privileges are granted to the final users so they can use the database application to perform specific tasks.
Granting Privileges Privileges are granted to users so they can access and change data in a database. A user can receive a privilege in two different ways:
: :
They can be explicitly granted to the users. For example, the privilege to insert records in the EMP table can be explicitly granted to user Scott. They can be granted to roles (a named group of privileges), and then the roles can be granted to one or more users. For example, the privilege of inserting records in the EMP table can be granted to a role called Clerk, which can then be granted to users Scott and Brian.
Since roles help make the management of privileges easier and more efficient, privileges are normally granted to roles rather than specific users. The following section provides details about roles and their use.
Roles Oracle provides for the easy and controlled management of privileges by means of roles. Roles are named groups of related privileges that are granted to users and to other roles. The following properties of roles allow for easier management of privileges: Property Granting of limited privileges
36
Description Instead of explicitly granting the same set of privileges to many users, the database administrator can grant those privileges using a role. Then the database administrator can grant the role to each user.
Introduction to the Oracle Server—Chapter 1
Property Dynamic management of privileges
Selective availability of privileges
Application awareness
Description When the privileges of a group need to be changed, only the privileges of the role must be changed. The security domains of all the users that have the group role are automatically reflected, and the changes are made to the role. The roles granted to a user can be selectively enabled (available to use) or disabled (not available). This allows the specific control of a user’s privileges in certain situations. A database application can be created to automatically enable or disable selected roles when a user tries to use the application.
Database administrators often create the roles for an application of this type. The DBA grants to this role all the privileges that are needed for the execution, and then grants that role to other roles or users. An application can have many different roles, with each one having a different set of privileges. The DBA can create a role with a password to prevent it from being used without the appropriate authorization. Generally, an application is created to activate the proper role when it is initialized. As a result, a software user does not need to know the password for an application role.
Audits Oracle allows the selective audit (logged monitoring) of the user’s actions in order to help investigate a suspect use of the database. The audit can be performed at three different levels: declaration, privilege, and schema object.
37
Chapter 1—Introduction to the Oracle Server
Type Declaration audit
Privilege audit
Schema object audit
Description The declaration audit makes the audit of the specific SQL declarations without consideration for the specifically named schema objects. (The database triggers allow a DBA to extend and customize the built-in audit resources of Oracle.) The declaration audit can be broad (executed for all the system users) or can be focused (executed for specific users). For example, the declaration audit by user can audit the connections and disconnections with the database of users Scott and Lori. The privilege audit is concerned with the use of the system’s advanced privileges, without consideration for the specifically named schemas. It can be broad and audit all the users, or it can be focused and audit only selected users. The schema object audit refers to the accesses of specific schema objects, without consideration for the user. It monitors the declarations allowed by the object privileges, such as the SELECT or DELETE declarations of certain tables.
In all of these audit types, Oracle allows the selective audit of the declarations that succeeded, the declarations that failed, or both. This allows the monitoring of suspect declarations, independent of the fact that the user that issued it had the appropriate privileges to produce it. The results of the audited operations are recorded in a table called an audit trail. Its predefined views allow an easy recovery of the audit records.
Database Backup and Recovery In every database system there is always the possibility of a system or hardware failure. If a failure affects the database, it must be recovered. After a failure, it is expected that the recovery 38
Introduction to the Oracle Server—Chapter 1
process will reflect all the submitted transactions in the database and that normal operation will resume as soon as possible in order to isolate users from the problems.
Types of Failures Several circumstances can suspend the operation of an Oracle database. The most common types of failures are described below: Errors user error
declaration and process failure
Description A user error can require the recovery of the database up to a point before the error has occurred. Let’s say a user accidentally drops a table. To allow the recovery of errors and anticipate other unique requirements of the recovery, Oracle provides the ability to recover the database at the very instant the table was dropped. The declaration failure occurs when there is a logical failure in the treatment of a declaration in the Oracle program (for example, the declaration is not a valid SQL construct). When the failure occurs, the effects (if any) are automatically undone by Oracle and the control returns to the user. A process failure is an error in a user process that accesses Oracle, such as an abnormal disconnection or termination of the process. The user process that failed cannot continue working, but Oracle and other types of processes can continue working. Oracle’s background process, the PMON, automatically detects the user process that has failed, or is informed by SQL*Net. The PMON solves the problem, making the rollback of the unsubmitted transaction of the user process and freeing the resources that the process was using. The most common problems, such as wrong constructs of the SQL declarations and aborted processes, must never suspend the database
39
Chapter 1—Introduction to the Oracle Server
Errors declaration and process failure (cont.)
instance failure
media failure (disk)
Description system as a whole. In addition, Oracle automatically executes the necessary recovery of the changes in the unsubmitted transactions and the blocked resources, with minimum impact on the system or on other users. The instance failure occurs when there is some problem that prevents an instance (system global area and background processes) from continuing to work. It can result from a hardware problem, such as a power outage, or a software problem, such as a system crash. When there is an instance failure, data in buffers of the system global area is not written to the datafiles. An error can occur when you try to read or write a file that is required for an operation in the database. This is called disk failure, because there is a physical problem in the reading or writing of physical files to disk. A common example of this is a failure in the disk head that causes the loss of files on a hard drive. Several files can be affected by this type of failure, including the redo log files and the control files. Similar to the instance failure, data in the database buffers of the system global area cannot be permanently written to the datafiles.
Structures Used in the Recovery Oracle uses several structures to provide for the complete recovery of an instance or a disk failure. These include the redo log, rollback segments, control files, and database backups.
The Redo Log The redo log is a set of files that protects changed data in a database. It contains changes that are located in the memory and have not yet been written to the datafiles. Redo logs have two parts: the online redo log and the written redo log. 40
Introduction to the Oracle Server—Chapter 1
The Online Redo Log The online redo log is a set of two or more files in this log that marks all the changes made to the database, including both uncommitted and committed changes. The redo entries are temporarily stored in the redo log buffers of the system global area, and the background process LGWR writes them sequentially in an online redo log file. The LGWR continuously writes the redo entries; it also writes a commit log whenever a user process is submitted to a transaction. The online redo log files are used cyclically; for example, when the online redo log contains two files, the first file is filled, and then the second one. Then the first file is reused, as is the second file, and so on. When a file is filled, it receives a number of log sequences to identify the set of redo entries. To avoid losing the database because of a single failure point, Oracle can maintain several sets of redo log files called multiplexed redo logs. Copies of the online redo logs that are physically located in separate disks form the multiplexed redo logs; changes made to a member of the group are made to all the remaining members.
The Written Redo Log Optionally, the online redo logs that are filled can be written before they are reused, creating a written redo log. The offline written redo log files constitute the written redo log. The presence or absence of a written redo log is determined by how the redo log is being used. In ARCHIVELOG mode, the online redo log files are written before they are used in the cycle. In NOARCHIVELOG mode, the online redo log files are not written. In the ARCHIVELOG mode, the database can be completely recovered from the instance or disk failure. It is also possible to make a backup while it is open and available to the user. However, to
41
Chapter 1—Introduction to the Oracle Server
update the written redo log, some additional administrative operations are necessary.
Control Files The control files of a database maintain, among other things, information about the file structure and the current number of log sequences that are being written to the LGWR. During the normal recovery procedures, information in a control file is used to guide the automated progression of the recovery.
Multiplexed Control Files Multiplexed control files are a resource similar to the multiplexed redo log: Oracle can simultaneously update several identical control files.
Rollback Segments The rollback segments log rollback information required by the different functions of Oracle. During the database recovery that occurs after the application of all the changes written to the redo log, Oracle uses the information in the rollback segment to undo all the unsubmitted transactions. Since the rollbacks are stored in the database buffers, the redo log automatically protects this important recovery information.
Database Backups Since one or more files can be physically damaged due to a disk failure, media recovery requires the restoration of these files from the most recent backup of the operating system to a database. There are several ways to do this.
42
Introduction to the Oracle Server—Chapter 1
System Backups A backup of the whole database is a backup of the operating system for all the datafiles, online redo log files, and control files that make up the Oracle database. Complete backups are performed when the database is closed and unavailable to users.
Partial Backups A partial backup is a backup made by the operating system as part of the database. The backup of the datafiles in an individual tablespace, or the backup of a control file are examples of partial backups. Partial backups are useful only when the redo log of the database is being operated in the ARCHIVELOG mode. A variety of partial backups can be made to accommodate the backup strategy. You can perform a backup of datafiles and control files when a database is open or closed, or when a specific tablespace is online or offline. Since the redo log is operated in the ARCHIVELOG mode, the additional backups of the redo log are not necessary; the written redo log is a backup of the completed online redo files.
Accessing Data Oracle uses the Structured Query Language to access a database and data in a table. SQL is the programming language that defines and manipulates the database. The SQL databases are relational. This simply means that data is stored in a set of simple relations. A database can have one or more tables, and columns (also called fields) and rows form each table. A database that has a table of employees, for example, can have a column called Employee ID; each row of this column would contain an employee number.
43
Chapter 1—Introduction to the Oracle Server
You can define and manipulate data in a table with SQL commands. You use the data definition language (DDL) commands to configure data, and create and change databases and tables. You can update, delete, extract, change, or recover data in a table with the data manipulation language (DML) commands. The most common command is the SELECT command, which allows the recovery of data in a database. In addition to the SQL commands, the Oracle server uses a procedural language called PL/SQL. This language allows the programmer to write declarations and control changes in a SQL program, and permits the use of variables and the writing of error handling procedures. SQL is a simple and powerful database access language, and the standard language for relational database management systems. The SQL implemented by Oracle Corporation for the Oracle database supports 100% of the standard ANSI/ISO for the SQL data language.
SQL Declarations All of the operations made to data in an Oracle database are performed using SQL declarations, which are SQL strings of text given to Oracle for execution. A declaration is the equivalent of a complete SQL sentence, such as the following: SELECT ename, deptno FROM emp;
Only a complete SQL declaration can be executed. A sentence fragment, such as the following, generates an error, indicating that more text is necessary for the SQL declaration to be executed: SELECT ename
44
Introduction to the Oracle Server—Chapter 1
A SQL declaration can be seen as a computer program or a very simple instruction, but with much more power. SQL declarations are divided into the following categories:
: : : : : :
Data definition language (DDL) declarations Data manipulation language (DML) declarations Transaction control declarations Session control declarations System control declarations Built-in SQL declarations
Data Definition Language (DDL) Declarations The DDL declarations define, update, and drop schema objects when they are not necessary anymore. They also include declarations that allow a user to grant privileges, or rights, to others for access to databases and to specific objects inside a database.
Data Manipulation Language (DML) Declarations The DML declarations manipulate the databases. For example, querying, inserting, updating, and deleting rows in a table are all DML operations. The blocking of a table or mode, and the review of the execution plan of a SQL declaration are also DML operations.
Transaction Control Declarations The transaction control declarations manage the changes made by the DML declarations. They allow the user or software developer to group the changes in logical transactions. Examples include COMMIT, ROLLBACK, and SAVEPOINT.
45
Chapter 1—Introduction to the Oracle Server
Session Control Declarations The session control declarations allow the user to control the properties of his or her current session, including the enabling or disabling of roles, and changes made to the definitions of the language. Session control declarations include ALTER SESSION and SET ROLE.
System Control Declarations The system control declarations change the instance properties of the Oracle server. Its only command is ALTER SYSTEM, which allows you to change system definitions, such as the minimum number of shared servers, the termination of a session, and the execution of other tasks.
Built-in SQL Declarations The built-in SQL declarations are the DDL and DML declarations, and the transaction control declarations in a procedural language program (such as the ones used in the Oracle precompilers). Examples include OPEN, CLOSE, FETCH, and EXECUTE.
Transactions A transaction is a logical unit of work that comprises one or more SQL declarations executed by a single user. According to the ANSI/ISO SQL standard, supported by Oracle, a transaction is initiated with the first executable SQL declaration of the user, and ends when it is explicitly submitted or rolled back (both terms are discussed in the next section) by the user. Let’s illustrate this process with an example. When a client transfers money from a savings account to a checking account, the transaction can consist of three separate operations: debiting the
46
Introduction to the Oracle Server—Chapter 1
savings account, crediting the checking account, and recording the transaction in the transaction log. Oracle must guarantee that all three SQL declarations are executed to update the balance in the accounts. When something prevents the execution of a transaction declaration (such as a hardware failure), the other declarations must be undone. This is called rolling back. When an error occurs in one of the updates, then no update is performed. Debit Savings Account UPDATE savings_accounts SET balance = balance - 500 WHERE account = 3209;
Credit Checking Account UPDATE checking_accounts SET balance = balance + 500 WHERE account = 3208;
INSERT INTO journal VALUES (journal_seq.1TEXTVAL, ‘1B’ 3209, 3208, 500);
Record in Transaction Journal
End Transaction COMMIT WORK;
Transaction Ends
Figure 1.5:
A banking transaction.
Committing and Rolling Back Transactions The changes made by the SQL declarations that constitute a transaction can be submitted or rolled back. After a transaction is submitted or rolled back, the next one starts with the following SQL declaration.
47
Chapter 1—Introduction to the Oracle Server
The submission of transactions makes the resulting changes permanent in all the SQL declarations of the transaction. The changes made by these declarations are visible to those declarations of another user’s session, which is initiated only after the transaction is submitted. The rolling back of a transaction retracts all the changes resulting from the SQL declarations. After a transaction is rolled back, the affected data is left unchanged, as if the SQL declarations had never been executed.
Savepoints In long transactions containing many SQL declarations, intermediate markers, or savepoints, can be declared. The savepoints can be used to divide a transaction into smaller parts. By using savepoints, you can arbitrarily mark your work at any point inside a long transaction. This gives you the option of making a rollback from the current point in the transaction up to a declared savepoint. You can use savepoints in a complex series of updates, and if you introduce an error, there is no need to resubmit all the declarations. Transactions provide the database user or software developer with the capability of guaranteeing consistent changes in data, since the SQL declarations inside a transaction are logically grouped. A transaction must consist of all the necessary parts for a logical unit of work—nothing more, nothing less. Data in all the referenced tables is in a consistent state before the transaction starts and after it ends. The transactions must consist only of the SQL declarations that make an efficient change in data. Remember the banking example. A fund transfer between two accounts (the transaction) must include the debiting of one account (a SQL declaration), the crediting of another account (a SQL declaration), and the recording of the transaction in the log journal (a SQL declaration). All the actions must succeed or fail at 48
Introduction to the Oracle Server—Chapter 1
the same time; the credit must not be approved without the debit. Other non-related actions, such as a new deposit in one of the accounts, must not be included in the funds transfer transaction; these require other transactions.
PL/SQL PL/SQL is the SQL extension of the Oracle language. It combines the ease of use and flexibility of SQL with the functionality of procedures of a structured programming language, such as IF..THEN, WHILE, and LOOP. When creating a database application, a developer must consider the advantages of using the stored PL/SQL:
: : :
Since the PL/SQL code can be centrally stored in a database, the network traffic among applications and the database is reduced and, therefore, the application and system performance improves. Data access can be controlled by the stored PL/SQL code. In this case, the users of PL/SQL can access data only as the application developer has designed (unless another access route is allowed). The PL/SQL blocks can be sent by an application to the database, executing complex operations without excessive network traffic.
Even when the PL/SQL is not stored in the database, the applications must send PL/SQL blocks for the database, instead of individual SQL declarations, again reducing the network traffic. The following sections describe the different program units that can be defined and stored in a centralized way in the database.
49
Chapter 1—Introduction to the Oracle Server
Procedures and Functions Procedures and functions consist of a set of SQL and PL/SQL declarations grouped as a unit to solve a specific problem or to execute a set of related tasks. A procedure is created, compiled, and stored in the database, and can be executed by a user or database application. Procedures and functions are identical, except that functions always return a value, while procedures do not.
Packages Packages provide a method to encapsulate and store related procedures, functions, variables, and other package constructs as a unit of the database. Packages provide the administrator or software developer with the ability to organize such routines. They also mean more functionality (for example, the variables of the global package can be declared and used by any procedure) and more performance (for example, all the package objects are analyzed, compiled, and loaded in the memory at the same time).
Database Triggers Oracle allows the writing of procedures that are automatically executed as a result of insert, update, or delete operations in a table. These procedures are called database triggers. Database triggers can be used in several ways to manage information in a database. They can be used to automate the generation of data, audit changes, enforce complex integrity restrictions, and customize complex security authorizations.
50
Introduction to the Oracle Server—Chapter 1
Methods A method is a procedure or function that is part of the definition of a user-defined data type (object type, aligned table, or variable array). They are different from stored procedures in two ways:
: :
You invoke a method by referring to an associated object of its type. A method has complete access to the attributes of its associated object and to information about its type.
Each user-defined data type has a constructor method defined by the system, that is, a method that creates a new object according to the data type specifications. The name of this method is the name of the user-defined type. In the case of an object type, the parameters of the constructor method have the names and attributes of the object type. The constructor method is a function that returns the new object as its value. The aligned tables and the arrays also have their constructor methods. The compare methods define an order relationship among the objects of a certain type. A map method uses Oracle’s ability to compare the incorporated types. Oracle can, for example, measure two rectangles and compare their areas when a type of object called RECTANGLE has the attributes HEIGHT and WIDTH, and you define a map method area that returns a number that is the product of the HEIGHT and WIDTH attributes of the rectangle. An order method uses its own internal logical to compare two objects of a certain type. It returns a value that codes the order relationship. It can return, for example, –1 when the first is smaller, 0 when both are equal, and 1 when the first is bigger.
51
Chapter 1—Introduction to the Oracle Server
Data Integrity It is very important to guarantee that data follow certain business rules specified by the database administrator or the software developer. For example, let’s assume that a business rule states that no row of the INVENTORY table can contain a numeric value greater than 9 in the Sale_discount column. When an INSERT or UPDATE declaration tries to violate this rule, Oracle must roll back the invalid declaration and return an error to the application. It also provides integrity restrictions and triggers to the database, as solutions for the management of the integrity rules.
Integrity Restrictions An integrity restriction is a declarative way to define a business rule for a column in a table. An integrity restriction is a declaration about data in a table that is always true. When a restriction is created for a table, and some data in the existing table does not follow the restriction, it cannot be enforced. After a restriction is defined, if some of the results of a DML declaration violate the integrity restriction, the declaration is rolled back and an error is returned. The integrity restrictions are defined as a table and are stored as part of this table in a centralized way in the data dictionary of the database, and all the applications must follow the same set of rules. When a rule changes, it must be changed only once at the database level, and not several times for each application. Oracle supports the following integrity restrictions: NOT NULL UNIQUE
52
Does not allow null values (empty entries) in a column. Does not allow duplicate values in a column or a set of columns.
Introduction to the Oracle Server—Chapter 1
PRIMARY KEY FOREIGN KEY
CHECK
Does not allow duplicate values and nulls in a column or set of columns. Requires that each value in a column or set of columns matches a value in the UNIQUE or PRIMARY KEY of the table. The integrity restrictions of the FOREIGN KEY also define the actions of referential integrity that dictate what Oracle must take with the dependent data when data referenced by it are changed. Does not allow values that do not follow the logical expression of the restriction.
Keys The term “key” is used in the definitions of several types of integrity restrictions. A key is a column or set of columns included in the definition of certain types of integrity restrictions. The keys describe the relations among different tables and columns in a relational database. The different types of keys include: Primary key
Unique key Foreign key Referenced key
The column or set of columns included in the definition of the PRIMARY KEY restriction of a table. The values of the primary key uniquely identify the rows of a table. A primary key can be defined in each table. The column or set of columns included in the definition of a UNIQUE KEY restriction. The column or set of columns included in the definition of a referential integrity restriction. The unique key or primary key of the same table, or in a different table, that is referenced by a foreign key.
The individual values of a key are called key values.
53
Chapter 1—Introduction to the Oracle Server
Database Triggers The centralized actions can be defined using a non-declarative approach (writing of PL/SQL code) to the database triggers. A database trigger is a stored procedure that is triggered (implicitly executed) when an INSERT, UPDATE, or DELETE declaration is issued in the associated table. They can be used to customize a database management system with resources such as an audit based in value, and the implementation of complex security checks and integrity rules. A database trigger could be created to allow a table to be changed only during working hours. This chapter provided an overview of Oracle’s architecture and components. In the remaining chapters of this part, we will explain in detail the main components introduced here.
54
Chapter 2
Data Dictionary The data dictionary is an important part of the database. It is formed by a set of tables that provide information about the database. All these tables are stored in the System tablespace and are read-only tables. Their information includes:
: : : :
Definitions of all the schema objects of the database, such as tables, views, indexes, clusters, synonyms, procedures, triggers, available space, and frequency attributed to those objects. The default values for the columns of the table. The names of users and their privileges and roles. Audit information.
Structures Two types of tables form the data dictionary—base tables and user-accessible views. Base tables are responsible for storing information about the associated database. Only Oracle can access them. User-accessible views display data from the base tables of the data dictionary, so the user sees data in an organized way. The data dictionary is the property of the SYS user and only that person can access it. An accidental or intentional change can cause serious problems when the database is used later.
55
Chapter 2—Data Dictionary
Oracle uses the data dictionary to read information about the users, objects, and the storage structures. Whenever a SQL DDL command is run, Oracle makes the changes in the dictionary. For example, if user Scott creates a table called TEST, new rows will be included in the dictionary, indicating the existence and major characteristics of this table. Oracle creates synonyms for some of the dictionary views, thus helping to ease user access. Most of the information contained in the dictionary is maintained in the SGA memory area, since Oracle accesses it frequently. New tables can be aggregated through the SYS user, and all the changes made to it are executed through the SQL DLL commands. The data dictionary is always visible when the database is opened. The views of this dictionary are identified by prefixes. Check the following table: Prefix USER ALL DBA
View Views of the user Expanded views of the user Views of the database administrator
Views of Type USER These views refer to the user objects, including information about the schema objects, permissions, and columns of tables, etc. These views are identical to those of type ALL except that they do not have the Owner column. In order to return, for example, all the objects of the user schema, the view USER_OBJECTS must be used: SELECT object_name, object_type FROM user_objects;
Following is an example of a USER view.
56
Data Dictionary—Chapter 2
USER_TRIGGER_COLS This view shows the use of the triggers. Column
Data Type
Value
Description
TRIGGER_OWNER
VARCHAR2(30)
NOT NULL
Owner
TRIGGER_NAME
VARCHAR2(30)
NOT NULL
Name
TABLE_OWNER
VARCHAR2(30)
NOT NULL
Owner of the table in which the trigger was created.
TABLE_NAME
VARCHAR2(30)
NOT NULL
Table in which the trigger was created.
COLUMN_NAME
VARCHAR2(4000)
Name of the column used in the trigger.
COLUMN_LIST
VARCHAR2(3)
Column specified in the UPDATE clause.
COLUMN_USAGE
VARCHAR2(17)
How the column is used in the trigger. All the applications for the combinations of NEW, OLD, IN, OUT, and IN OUT.
Views of Type ALL These views refer to the objects to which the user has access through permissions, roles, or privileges. For example, in order to view all the objects to which the user has access permission, you must use the view ALL_OBJECTS: SELECT owner, object_name, object_type FROM all_objects;
Following is an example of an ALL view.
57
Chapter 2—Data Dictionary
ALL_USERS This view contains information about all the database users. Column
Data Type
Value
Description
USERNAME
VARCHAR2(30)
NOT NULL
Name of user
USER_ID
NUMBER
NOT NULL
User’s ID number
CREATED
DATE
NOT NULL
Creation date
Views of Type DBA The DBA views display the whole database. They are accessible only by the database administrator or by users that have been granted permission. To query these views, the DBA must use the prefix SYS: SELECT owner, object_name, object_type FROM sys.dba_objects;
Below is an example of a DBA view.
DBA_CATALOG This view lists all the tables, views, synonyms, and sequences of the database.
58
Column
Data Type
Value
Description
OWNER
VARCHAR2(30)
NOT NULL
Owner of the object
TABLE_NAME
VARCHAR2(30)
NOT NULL
Name of the object
TABLE_TYPE
VARCHAR2(11)
Type of the object
Data Dictionary—Chapter 2
Dual Table There a special table in the data dictionary called dual. It has only one column, called Dummy, and a row containing the value X. It serves as a test for the users.
Dynamic Performance Tables Oracle maintains a set of tables called dynamic performance tables. They store all the database activity and cannot be changed or altered by the DBAs, who only can create synonyms to them. The owner of the tables having synonyms with information and starting with V_$, such as in V$DATAFILE, is the SYS user.
Views The following table shows all the views of a data dictionary. Their names are more or less self-explanatory. To find out more information about any of these views, see Oracle’s reference guide. ALL_ALL_TABLES ALL_ARGUMENTS ALL_ASSOCIATIONS ALL_CATALOG ALL_CLUSTERS ALL_CLUSTER_HASH_EXPRESSIONS ALL_COL_COMMENTS ALL_COL_PRIVS ALL_COL_PRIVS_MADE ALL_COL_PRIVS_RECD ALL_COLL_TYPES ALL_CONS_COLUMNS ALL_CONSTRAINTS ALL_CONTEXT
ALL_DB_LINKS ALL_DEF_AUDIT_OPTS ALL_DEPENDENCIES ALL_DIMENSIONS ALL_DIM_ATTRIBUTES ALL_DIM_CHILD_OF ALL_DIM_HIERARCHIES ALL_DIM_JOIN_KEY ALL_DIM_LEVELS ALL_DIM_LEVEL_KEY ALL_DIRECTORIES ALL_ERRORS ALL_IND_COLUMNS ALL_IND_EXPRESSIONS
59
Chapter 2—Data Dictionary
ALL_IND_PARTITIONS ALL_IND_SUBPARTITIONS ALL_INDEXES ALL_INDEXTYPES ALL_INDEXTYPE_OPERATORS ALL_JOBS ALL_LABELS ALL_LIBRARIES ALL_LOBS ALL_LOB_PARTITIONS ALL_LOB_SUBPARTITIONS ALL_METHOD_PARAMS ALL_METHOD_RESULTS ALL_MVIEW_AGGREGATES ALL_MVIEW_ANALYSIS ALL_MVIEW_DETAIL_RELATIONS ALL_MVIEW_JOINS ALL_MVIEW_KEYS ALL_NESTED_TABLES ALL_OBJECT_TABLES ALL_OBJECTS ALL_OPANCILLARY ALL_OPARGUMENTS ALL_OPBINDINGS ALL_OPERATORS ALL_OUTLINE_HINTS ALL_OUTLINES ALL_PART_COL_STATISTICS ALL_PART_HISTOGRAMS ALL_PART_INDEXES ALL_PART_KEY_COLUMNS ALL_PART_LOBS ALL_PART_TABLES ALL_PARTIAL_DROP_TABS ALL_POLICIES ALL_QUEUES ALL_REFRESH 60
ALL_REFRESH_CHILDREN ALL_REFRESH_DEPENDENCIES ALL_REFS ALL_REGISTERED_SNAPSHOTS ALL_REPCATLOG ALL_REPCOLUMN ALL_REPCOLUMN_GROUP ALL_REPCONFLICT ALL_REPDDL ALL_REPGENERATED ALL_REPGENOBJECTS ALL_REPGROUP ALL_REPGROUPED_COLUMN ALL_REPKEY_COLUMNS ALL_REPOBJECT ALL_REPPARAMETER_COLUMN ALL_REPPRIORITY ALL_REPPRIORITY_GROUP ALL_REPPROP ALL_REPRESOLUTION ALL_REPRESOL_STATS_CONTROL ALL_REPRESOLUTION_METHOD ALL_REPRESOLUTION_STATISTICS ALL_REPSITES ALL_SEQUENCES ALL_SNAPSHOT_LOGS ALL_SNAPSHOT_REFRESH_TIMES ALL_SNAPSHOTS ALL_SOURCE ALL_SUBPART_COL_STATISTICS ALL_SUBPART_HISTOGRAMS ALL_SUBPART_KEY_COLUMNS ALL_SUMDELTA ALL_SUMMARIES ALL_SYNONYMS ALL_TAB_COL_STATISTICS ALL_TAB_COLUMNS
Data Dictionary—Chapter 2
ALL_TAB_COMMENTS ALL_TAB_HISTOGRAMS ALL_TAB_PARTITIONS ALL_TAB_PRIVS ALL_TAB_PRIVS_MADE ALL_TAB_PRIVS_RECD ALL_TAB_SUBPARTITIONS ALL_TABLES ALL_TRIGGERS ALL_TRIGGER_COLS ALL_TYPE_ATTRS ALL_TYPE_METHODS ALL_TYPES ALL_UNUSED_COL_TABS ALL_UPDATABLE_COLUMNS ALL_USERS ALL_USTATS ALL_VARRAYS ALL_VIEWS AUDIT_ACTIONS CATALOG CAT CHAINED_ROWS CLU CODE_PIECES CODE_SIZE COL COLS COLUMN_PRIVILEGES DBA_2PC_NEIGHBORS DBA_2PC_PENDING DBA_ALL_TABLES DBA_ANALYZE_OBJECTS DBA_ASSOCIATIONS DBA_AUDIT_EXISTS DBA_AUDIT_OBJECT DBA_AUDIT_SESSION
DBA_AUDIT_STATEMENT DBA_AUDIT_TRAIL DBA_BLOCKERS DBA_CATALOG DBA_CLU_COLUMNS DBA_CLUSTERS DBA_CLUSTER_HASH_EXPRESSIONS DBA_COL_COMMENTS DBA_COL_PRIVS DBA_COLL_TYPES DBA_CONSTRAINTS DBA_CONS_COLUMNS DBA_CONTEXT DBA_DATA_FILES DBA_DB_LINKS DBA_DDL_LOCKS DBA_DEPENDENCIES DBA_DIMENSIONS DBA_DIM_ATTRIBUTES DBA_DIM_CHILD_OF DBA_DIM_JOIN_KEY DBA_DIM_HIERARCHIES DBA_DIM_LEVELS DBA_DIM_LEVEL_KEY DBA_DIRECTORIES DBA_DML_LOCKS DBA_ERRORS DBA_EXP_FILES DBA_EXP_OBJECTS DBA_EXP_VERSION DBA_EXTENTS DBA_FREE_SPACE DBA_FREE_SPACE_COALESCED DBA_INDEXES DBA_IND_COLUMNS DBA_IND_EXPRESSIONS DBA_IND_PARTITIONS 61
Chapter 2—Data Dictionary
DBA_IND_SUBPARTITIONS DBA_INDEXTYPES DBA_INDEXTYPE_OPERATORS DBA_JOBS DBA_JOBS_RUNNING DBA_LIBRARIES DBA_LOBS DBA_LOB_PARTITIONS DBA_LOB_SUBPARTITIONS DBA_LOCKS DBA_LOCK_INTERNAL DBA_METHOD_PARAMS DBA_METHOD_RESULTS DBA_MVIEW_AGGREGATES DBA_MVIEW_ANALYSIS DBA_MVIEW_DETAIL_RELATIONS DBA_MVIEW_JOINS DBA_MVIEW_KEYS DBA_NESTED_TABLES DBA_OBJECT_SIZE DBA_OBJECT_TABLES DBA_OBJECTS DBA_OBJ_AUDIT_OPTS DBA_OPANCILLARY DBA_OPARGUMENTS DBA_OPBINDINGS DBA_OPERATORS DBA_OUTLINE_HINTS DBA_OUTLINES DBA_PART_COL_STATISTICS DBA_PART_HISTOGRAMS DBA_PART_INDEXES DBA_PART_KEY_COLUMNS DBA_PART_LOBS DBA_PART_TABLES DBA_PARTIAL_DROP_TABS
62
DBA_PENDING_TRANSACTIONS DBA_POLICIES DBA_PRIV_AUDIT_OPTS DBA_PROFILES DBA_QUEUE_SCHEDULES DBA_QUEUE_TABLES DBA_QUEUES DBA_RCHILD DBA_REFRESH DBA_REFRESH_CHILDREN DBA_REFS DBA_REGISTERED_SNAPSHOT_GROUPS DBA_REGISTERED_SNAPSHOTS DBA_REPCATLOG DBA_REPCAT_REFRESH_TEMPLATES DBA_REPCAT_TEMPLATE_OBJECTS DBA_REPCAT_TEMPLATE_PARMS DBA_REPCAT_TEMPLATE_SITES DBA_REPCAT_USER_AUTHORIZATIONS DBA_REPCAT_USER_PARM_VALUES DBA_REPCOLUMN DBA_REPCOLUMN_GROUP DBA_REPCONFLICT DBA_REPDDL DBA_REPGENERATED DBA_REPGENOBJECTS DBA_REPGROUP DBA_REPGROUPED_COLUMN DBA_REPKEY_COLUMNS DBA_REPOBJECT DBA_REPPARAMETER_COLUMN DBA_REPPRIORITY DBA_REPPRIORITY_GROUP DBA_REPPROP DBA_REPRESOLUTION DBA_REPRESOLUTION_METHOD
Data Dictionary—Chapter 2
DBA_REPRESOL_STATS_CONTROL DBA_REPSITES DBA_RGROUP DBA_ROLES DBA_ROLE_PRIVS DBA_ROLLBACK_SEGS DBA_RSRC_CONSUMER_GROUP_PRIVS DBA_RSRC_CONSUMER_GROUPS DBA_RSRC_MANAGER_SYSTEM_PRIVS DBA_RSRC_PLANS DBA_RSRC_PLAN_DIRECTIVES DBA_RULESETS DBA_SEGMENTS DBA_SEQUENCES DBA_SNAPSHOT_LOGS DBA_SNAPSHOT_LOG_FILTER_COLS DBA_SNAPSHOT_REFRESH_TIMES DBA_SNAPSHOTS DBA_SOURCE DBA_STMT_AUDIT_OPTS DBA_SUBPART_COL_STATISTICS DBA_SUBPART_HISTOGRAMS DBA_SUBPART_KEY_COLUMNS DBA_SYNONYMS DBA_SYS_PRIVS DBA_TAB_COL_STATISTICS DBA_TAB_COLUMNS DBA_TAB_COMMENTS DBA_TAB_HISTOGRAMS DBA_TAB_PARTITIONS DBA_TAB_PRIVS DBA_TAB_SUBPARTITIONS DBA_TABLES DBA_TABLESPACES DBA_TEMP_FILES DBA_TRIGGERS DBA_TRIGGER_COLS
DBA_TS_QUOTAS DBA_TYPE_ATTRS DBA_TYPE_METHODS DBA_TYPES DBA_UNUSED_COL_TABS DBA_UPDATABLE_COLUMNS DBA_USERS DBA_USTATS DBA_VARRAYS DBA_VIEWS DBA_WAITERS DBMS_ALERT_INFO DBMS_LOCK_ALLOCATED DEFCALL DEFCALLDEST DEFDEFAULTDEST DEFERRCOUNT DEFERROR DEFLOB DEFPROPAGATOR DEFSCHEDULE DEFTRAN DEFTRANDEST DEPTREE DICT DICTIONARY DICT_COLUMNS ERROR_SIZE EXCEPTIONS FILE_LOCK FILE_PING FILEXT$ GLOBAL_NAME HS_ALL_CAPS HS_ALL_DD HS_ALL_INITS HS_BASE_CAPS 63
Chapter 2—Data Dictionary
HS_BASE_DD HS_CLASS_CAPS HS_CLASS_DD HS_CLASS_INIT HS_EXTERNAL_OBJECT_PRIVILEGES HS_EXTERNAL_OBJECTS HS_EXTERNAL_USER_PRIVILEGES HS_FDS_CLASS HS_FDS_INST HS_INST_CAPS HS_INST_DD HS_INST_INIT IDEPTREE IND INDEX_HISTOGRAM INDEX_STATS NLS_DATABASE_PARAMETERS NLS_INSTANCE_PARAMETERS NLS_SESSION_PARAMETERS OBJ ORPHAN_KEY_TABLE PARSED_PIECES PARSED_SIZE PLAN_TABLE PLUGGABLE_SET_CHECK PRODUCT_COMPONENT_VERSION PROXY_USERS PSTUBTBL PUBLICSYN PUBLIC_DEPENDENCY QUEUE_PRIVILEGES RC REPAIR_TABLE RESOURCE_COST RESOURCE_MAP ROLE_ROLE_PRIVS ROLE_SYS_PRIVS 64
ROLE_TAB_PRIVS SEQ SESSION_CONTEXT SESSION_PRIVS SESSION_ROLES SOURCE_SIZE STMT_AUDIT_OPTION_MAP SYN SYNONYMS SYSCATALOG SYSFILES SYSSEGOBJ SYSTEM_PRIVILEGE_MAP SYS_OBJECTS TAB TABLE_PRIVILEGES TABLE_PRIVILEGE_MAP TABS TABQUOTAS TRUSTED_SERVERS TS_PITR_CHECK TS_PITR_OBJECTS_TO_BE_DROPPED UNI_PLUGGABLE_SET_CHECK USER_ALL_TABLES USER_ARGUMENTS USER_ASSOCIATIONS USER_AUDIT_OBJECT USER_AUDIT_SESSION USER_AUDIT_STATEMENT USER_AUDIT_TRAIL USER_CATALOG USER_CLUSTERS USER_CLUSTER_HASH_EXPRESSIONS USER_CLU_COLUMNS USER_COL_COMMENTS USER_COL_PRIVS USER_COL_PRIVS_MADE
Data Dictionary—Chapter 2
USER_COL_PRIVS_RECD USER_COLL_TYPES USER_CONSTRAINTS USER_CONS_COLUMNS USER_DB_LINKS USER_DEPENDENCIES USER_DIMENSIONS USER_DIM_ATTRIBUTES USER_DIM_CHILD_OF USER_DIM_JOIN_KEY USER_DIM_HIERARCHIES USER_DIM_LEVELS USER_DIM_LEVEL_KEY USER_ERRORS USER_EXTENTS USER_FREE_SPACE USER_INDEXES USER_IND_COLUMNS USER_IND_EXPRESSIONS USER_IND_PARTITIONS USER_IND_SUBPARTITIONS USER_INDEXTYPES USER_INDEXTYPE_OPERATORS USER_JOBS USER_LIBRARIES USER_LOBS USER_LOB_PARTITIONS USER_LOB_SUBPARTITIONS USER_METHOD_PARAMS USER_METHOD_RESULTS USER_MVIEW_AGGREGATES USER_MVIEW_ANALYSIS USER_MVIEW_DETAIL_RELATIONS USER_MVIEW_JOINS USER_MVIEW_KEYS USER_NESTED_TABLES USER_OBJECT_TABLES
USER_OBJECTS USER_OBJECT_SIZE USER_OBJ_AUDIT_OPTS USER_OPANCILLARY USER_OPARGUMENTS USER_OPBINDINGS USER_OPERATORS USER_OUTLINE_HINTS USER_OUTLINES USER_PART_COL_STATISTICS USER_PART_HISTOGRAMS USER_PART_KEY_COLUMNS USER_PART_INDEXES USER_PART_LOBS USER_PART_TABLES USER_PARTIAL_DROP_TABS USER_PASSWORD_LIMITS USER_POLICIES USER_QUEUE_SCHEDULES USER_QUEUE_TABLES USER_QUEUES USER_REFRESH USER_REFRESH_CHILDREN USER_REFS USER_REGISTERED_SNAPSHOTS USER_REPCATLOG USER_REPCOLUMN USER_REPCOLUMN_GROUP USER_REPCONFLICT USER_REPDDL USER_REPGENERATED USER_REPGENOBJECTS USER_REPGROUP USER_REPGROUPED_COLUMN USER_REPKEY_COLUMNS USER_REPOBJECT USER_REPPARAMETER_COLUMN 65
Chapter 2—Data Dictionary
USER_REPPRIORITY USER_REPPRIORITY_GROUP USER_REPPROP USER_REPRESOLUTION USER_REPRESOL_STATS_CONTROL USER_REPRESOLUTION_METHOD USER_REPRESOLUTION_STATISTICS USER_REPSITES USER_RESOURCE_LIMITS USER_ROLE_PRIVS USER_RSRC_CONSUMER_GROUP_PRIVS USER_RSRC_MANAGER_SYSTEM_PRIVS USER_RULESETS USER_SEGMENTS USER_SEQUENCES USER_SNAPSHOTS USER_SNAPSHOT_LOGS USER_SNAPSHOT_REFRESH_TIMES USER_SOURCE USER_SUBPART_COL_STATISTICS USER_SUBPART_HISTOGRAMS USER_SUBPART_KEY_COLUMNS USER_SYNONYMS USER_SYS_PRIVS
USER_TAB_COL_STATISTICS USER_TAB_COLUMNS USER_TAB_COMMENTS USER_TAB_HISTOGRAMS USER_TAB_PARTITIONS USER_TAB_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD USER_TAB_SUBPARTITIONS USER_TABLES USER_TABLESPACES USER_TRIGGERS USER_TRIGGER_COLS USER_TS_QUOTAS USER_TYPES USER_TYPE_ATTRS USER_TYPE_METHODS USER_UNUSED_COL_TABS USER_UPDATABLE_COLUMNS USER_USERS USER_USTATS USER_VARRAYS USER_VIEWS
This chapter described the data dictionary and its importance to the database. The next chapter explores tablespaces and datafiles.
66
Chapter 3
Tablespaces and Datafiles Oracle stores the logical part of data in the tablespaces, and the physical part in the datafiles. The datafiles, in turn, are associated to a tablespace.
Tablespace (one or more datafiles)
Table
Table
Index
Index
Index
Index
Index
Index
Index
Index
Index
Table
Datafiles (physical structures associated with only one tablespace)
Figure 3.1:
Index
Objects (stored in tablespaces; may span several datafiles)
Tablespaces and datafiles.
67
Chapter 3—Tablespaces and Datafiles
One or more units of logical storage form a database, and each tablespace is comprised of one or more files called datafiles. In the example in Figure 3.1, the database has a tablespace formed by two datafiles.
Tablespaces A tablespace is divided into logical units called segments, which are subdivided into extents.
System Tablespace Each Oracle database has a System tablespace that is automatically created. It contains the data dictionary and is stored in the file named datafile1. All data generated by the storage of the PL/SQL programs, such as procedures, functions, packages, and triggers, are also maintained in the System tablespace.
Creating Tablespaces While a small database can function perfectly well with a single tablespace, Oracle recommends the creation of at least another tablespace for the storage of user data. The creation of multiple tablespaces provides for better management of the space and performance of the database. Tablespaces are created and maintained by the DBA. These tablespaces create and change their size, and change the segment settings and the read and write attributes, along with other actions.
68
Tablespaces and Datafiles—Chapter 3
Database Single tablespace
System Tablespace
DATA1.ORA
DATA2.ORA
DATA3.ORA
Database size and tablespace size increase with the addition of datafiles ALTER TABLESPACE system ADD DATAFILE ‘DATA2.ORA’
ALTER TABLESPACE system ADD DATAFILE ‘DATA3.ORA’
Figure 3.2:
System tablespace structure.
Allocation of Space A tablespace allocates space in the extents. These spaces can be of two types: dictionary-managed or locally managed. Their management depends on how the tablespace was configured.
Dictionary-Managed Tablespaces In this type of management, Oracle updates the data dictionary as soon as the extent is allocated or freed. This is the only method existing up to version 8.1, and is the default.
Locally Managed Tablespaces This new type of management contains a bitmap in each datafile in order to control its allocation of space. Each bit of the bitmap corresponds to a block or group of blocks. When an extent is 69
Chapter 3—Tablespaces and Datafiles
allocated or freed, Oracle changes the state of the bitmap to reflect these changes. The type of management is specified by the EXTENT MANAGEMENT LOCAL parameter of the CREATE DATABASE command for the System tablespace, or the CREATE TABLESPACE command for other types of tablespaces.
Online and Offline Tablespaces A tablespace can be available (online) or unavailable (offline). The System tablespace is always available. It must be online to grant access permission to the users. It is necessary to set it offline when you want to perform tasks such as backup or table maintenance. Oracle also sets a tablespace offline when certain types of errors occur accidentally.
Read-Only Tablespaces It is common to create a tablespace with the read-only attribute when you want to eliminate backups of parts of a database, such as tables that are not updated often. As the default, every tablespace is created with the Read-Write attribute. To create it as read only you must use the Read-Only attribute of the ALTER TABLESPACE command.
Temporary Tablespaces It is possible to create temporary tablespaces for the storage of data that is also temporary, such as a table sort. The sorting operation is generated by the ORDER BY, GROUP BY, and ANALYZE parameters.
70
Tablespaces and Datafiles—Chapter 3
This type of tablespace can be used just for the sort operation, with its segment being shared by several operations. A locally managed temporary tablespace is created with the CREATE TEMPORARY TABLESPACE command, and generates tempfiles instead of datafiles. The tablespaces that are managed through the data dictionary are created with the Temporary option of the CREATE TABLESPACE command.
Transporting Tablespaces Among Databases Oracle allows a copy of part or all of the tablespace among the existing databases. This operation is much faster than using the export/import utility. Moving the tablespaces allows you to move the tables’ indexes, thus eliminating the need to rebuild them. Only those indexes with the same characteristics may be moved between databases that are located in the same platform. Transporting the tablespaces is very useful when you create a data warehouse or data marts.
Datafiles The tablespace is formed by one or more datafiles. Oracle creates a datafile using the amount of space previously specified. When a datafile is created, the physical space is formatted and saved to store the tablespace data. All the schema objects are stored in one specific tablespace. However, these objects can be physically stored in one or more datafiles, i.e., they can be divided to allocate the space the best way possible. The size of a datafile can be changed after it is created.
71
Chapter 3—Tablespaces and Datafiles
Database System Tablespace
DATA1.ORA
Users Tablespace
DATA2.ORA
DATA3.ORA
20 M
20 M
ALTER DATABASE DATAFILE ‘DATA3.ORA’ AUTOEXTEND ON NEXT 20M MAXSIZE 1000M;
Figure 3.3:
Users tablespace structure.
With the exception of the datafiles of the System tablespace, all other datafiles are set as offline when the tablespace of which they are part is unavailable. This chapter explained tablespaces and datafiles, which contain the logical and physical parts of data, respectively. The next chapter shows how data blocks, extents, and segments are used.
72
Chapter 4
Data Blocks, Extents, and Segments This chapter shows how the data blocks, extents, and segments are stored and their relationship. The smallest unit Oracle uses to allocate space is a data block, or logic block. These, in turn, are grouped in extents that store a specific type of information.
Figure 4.1:
Data blocks, extents, and segments.
73
Chapter 4—Data Blocks, Extents, and Segments
The extents are grouped in segments that store data relating to a type of structure. A segment, for example, is used to store data and other indexes of a table. When the extents of a segment are filled, Oracle allocates another extent to that segment. Since they are deallocated as they are required, a segment may or may not be continuous in the disk.
Data Blocks Data blocks are the smallest unit of I/O used by the database. A data block’s size is defined during the creation of a database and its format is always the same, regardless of the type of data it stores. Figure 4.2 shows the structure of the data block. Database Block Common and Variable Header Table Directory Row Directory Free Space Row Data
Figure 4.2:
Components of a data block.
Data Header
Table Directory
74
Description Contains information such as the address of the block and the type of segment (for example: data, index, or rollback). Contains information about the tables that have rows in this block.
Data Blocks, Extents, and Segments—Chapter 4
Data Row Directory Overhead
Free space Row data
Description Contains information about the rows maintained in the block. The header, table directory, and row directory are called, collectively, an overhead. This part of the data block normally is fixed between 84 and 107 bytes. The space reserved for the insertion of new rows or updating of rows that increase in size. The part that contains the table or index.
Understanding PCTFREE, PCTUSED, and Row Chaining Another important concept is the use of the space management parameters PCTFREE and PCTUSED. These control the space used for the insertion and updating of rows of tables inside a group of data blocks. These parameters are specified during the creation of a table or cluster. PCTFREE indicates the amount of space that must be left for the update of the data block’s rows. Data Block
PCTFREE = 20
20% Free Space
Block allows row inserts until 80% is occupied, leaving 20% free for updates to existing rows in the block
Figure 4.3:
Data block specified with PCTFREE.
75
Chapter 4—Data Blocks, Extents, and Segments
The PCTUSED parameter adjusts the minimum percentage that can be used for data in a row, before new rows are added to the block. After a block has reached the limit determined by PCTFREE, Oracle considers it unavailable for insertions until the percentage of use is below the percentage determined by PCTUSED. These parameters are specified in the space management command CREATE TABLE. If PCTUSED 45 was specified, the segment would be considered unavailable for use until the amount of space was below 45%. Consider the next figure:
Data Block
PCTUSED = 40
61% Free Space No new rows are inserted until amount of used space falls below 40%
Figure 4.4:
Data block specified with PCTUSED.
For each data segment or index, Oracle maintains one or more lists of free blocks allocated to them. When an INSERT command is used, the database checks the list of free blocks and uses the first one that is available. If the free space in that block is not sufficient to accommodate the contents of the command, Oracle takes the block out of the list of free blocks. In some situations, data in a row cannot fit in one data block. When a row is inserted for the first time and does not fit in a block, Oracle stores this row 76
Data Blocks, Extents, and Segments—Chapter 4
in a block chain or sequence reserved for that segment. In case it is already written, and an update makes it exceed the size of the block, all of it will be migrated to a new data block.
Extents If the data blocks pertaining to the initial extent of a segment are filled, Oracle automatically allocates an additional extent to that segment. The new extent will be the same size or bigger than the previous extent. The storage characteristics of the extents are specified by the STORAGE parameter of the CREATE TABLE command. If this is omitted, the default is assumed.
Segments A segment is a set of extents containing all the logic data of the tablespace. Oracle uses four distinct types, which are described below.
Data Segments Data segments store data in a non-partitioned table, a partition of a table, or a cluster of tables. They are created and modified with the CREATE TABLE or ALTER TABLE commands.
Index Segments Non-partitioned Oracle indexes have a segment to store their data. Partitioned indexes have a segment for each partition of the index. These segments are created with the CREATE INDEX command. The index and data segments of a table can be created in different tablespaces.
77
Chapter 4—Data Blocks, Extents, and Segments
Temporary Segments When a query is executed, Oracle automatically allocates disk space that is used in the processing of that query. This temporarily allocated space is made through the temporary segments. Its creation depends on the amount of processed data. If it is possible to execute the query only in memory, it is done without creating temporary segments. The commands that can create them are: CREATE INDEX, SELECT with ORDER BY, SELECT with DISTINCT, SELECT with GROUP BY, SELECT with UNION, SELECT with INTERSECT, and SELECT with MINUS.
Rollback Segments Every database has one or more rollback segments. These write the old values of data that were changed in each operation. They are used to recover the database in case a transaction is not successfully executed. Information in a rollback segment is formed by several entries that store the number of file, the identification of the block corresponding to the piece of changed data, and the old value for this piece of data. Each entry of the segment is associated to the process; therefore, they are quickly found in case there is the need to undo a transaction that was already concluded. Whenever a transaction is initiated, Oracle allocates a segment. During this activity, the user process describes rollback data only in the segment associated to the transaction. When the transaction is ended (committed), Oracle frees rollback information, without destroying it immediately. Data blocks, extents, and segments were discussed in this chapter. In the next chapter, the last chapter of the first part of the book, we will examine the characteristics of Oracle’s schema objects.
78
Chapter 5
Schema Objects Each database user has a schema, which is a collection of objects formed by tables, views, sequences, synonyms, indexes, clusters, database links, snapshots, procedures, functions, and packages. This chapter gives an overview of the main objects of a schema. By definition, schema objects are logical structures of data stored in one or more tablespaces. There is a relationship between a schema and the tablespaces. A schema can contain objects located in different tablespaces. Database Data Tablespace
System Tablespace
Table
Index
Cluster
Index
Index
Index
Index
Index
Index
Index
Index
Index
Index
Index
Table
Table
Table
Index
Index
Table
DBFILE1
Drive 1
Figure 5.1:
DBFILE3
DBFILE2
Drive 1
Schema objects.
79
Chapter 5—Schema Objects
Tables Tables are a basic unit of storage in a database. The data is stored in rows and columns. A table is identified by a name that reflects the information it stores. A table of employees, for example, can be named EMP, and the column that will contain the names of those employees can be called Ename. Each column stores a different type of data (data type), such as number, text, date, or image. The contents of a column can be blank (null permitted) or may be required. A row in the table stores data relating to only one record, such as all data of a particular employee.
Rows
Columns
7329 7499 7521 7566
ENAME
JOB
MGR
HIREDATE
SMITH ALLEN WARD JONES
CLERK SALESMAN SALESMAN MANAGER
7902 7698 7698 7839
DEC-17-88 FEB-20-88 FEB-22-88 APR-02-88
Column not allowing nulls
Figure 5.2:
Column names
SAL
COMM
DEPTNO
800.00 1600.00 1250.00 2975.00
300.00 300.00 500.00
20 30 30 20
Column allowing nulls
Table structure.
When a table is created, Oracle allocates space in a tablespace to maintain future data of the table. As we saw in the previous chapter, Oracle tries to store a row of the table as one piece, so it can be inserted in one data block. If it doesn’t fit, it will be divided and written in several data blocks. The parts of a row are linked through the use of a row identifier called a rowid. For each row or part of it, a header is written before the area of data containing information about the parts, the columns inside the piece, and the cluster keys, if used. A row inserted completely in a block has a header of at least 3 bytes. 80
Schema Objects—Chapter 5
After the header, each column stores its data size, which requires from 1 to 3 bytes, depending on the amount of data to be stored. To save space, a null value adjusts the size of the column to zero. Row Header
Column Data
Row Piece in a Database Block
Row Overhead Number of Columns Cluster Key ID (if clustered) ROWID of Chained Row Pieces (if any) Column Length Column Value
Figure 5.3:
Database Block
Storing a row in a data block.
The rowid identifies each row or piece through its location or address. The rowid exists as long as the row exists. The order of columns is identical for all the rows in a table. While the effects of a query and the display of a table shows the columns in the order specified by the CREATE TABLE command, physically they can assume other positions. For instance, a column with the data type long is always stored at the end. TIP: Columns that store many null values should be specified at the end of the table definition so the row occupies less space.
81
Chapter 5—Schema Objects
Nested Tables Oracle allows the creation of a table in which one of the columns has the table data type, i.e., one table can be nested inside another, as if the table were a value of that column. In this case, the nested table is stored outside of the row of the table that contains it. Oracle stores an identifier in the row that makes the link with the external table.
Temporary Tables As the default, the tables are created as permanent, i.e., they exist until they are specifically eliminated or changed. With the CREATE TEMPORARY TABLE command, Oracle allows the creation of a table that exists only for the duration of a transaction or session. The SQL DML commands that change data in a temporary table generate entries for the rollback redo logs rather than the redo log files. A temporary table can have indexes created for it with the INDEX command. These indexes, like views and triggers, also are eliminated with the table at the end of the session or transaction. This type of table can have its structure replicated but not its data.
Views A view is a way to visualize parts of a table or several tables as if they were a single table. A view can contain columns from different tables, and only the rows that fulfill some condition. A view can be defined as a virtual table, i.e., it does not exist physically as do the tables used for its creation. Let’s say the local database has a view called Sales, and shows columns of the CUSTOMER, PRODUCTS, and SALES_ORDER tables.
82
Schema Objects—Chapter 5
The EMP table in the following example has several columns and rows containing data about employees who work in different departments.
Base Table
EMP EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPT NO
7329 7499 7521
SMITH ALLEN WARD JONES
CLERK SALESMAN SALESMAN MANAGER
7902 7698 7698 7839
DEC-17-88 FEB-20-88 FEB-20-88 APR-02-88
300.00 300.00 5.00
800.00 1600.00 1250.00 2975.00
20 30 30 20
7566
View
STAFF EMPNO
ENAME
JOB
MGR
DEPT NO
7329 7499 7521
SMITH ALLEN WARD JONES
CLERK SALESMAN SALESMAN MANAGER
7902 7698 7698 7839
20 30 30 20
7566
Figure 5.4:
The STAFF view is based on the EMP table.
Using this concept, we can create a view that shows only the data that is relevant to the user. The manager of a department, for instance, could have a view showing data about his or her employees. Once created, the user would use this table just like any other table that can be queried. Unlike a table, a view does not have physical space allocated to its data. A view is created by a query that uses origin or base tables to extract data. The base tables can be tables or other views. The definition of a view is stored in a data dictionary, which is also responsible for storing the query that generated the table.
83
Chapter 5—Schema Objects
How a View Works The definition of a view is stored in the data dictionary as text containing the SQL command used to create a view. When a view is referred to by a SQL command, Oracle combines this command with that of the view definition to return data. Oracle maintains control of the dependencies of a view. When a table used by a view is eliminated or changed, Oracle determines when the table can be used in the definition of the view.
Join Views A join view is defined as a view that has more than one table specified in the FROM clause, and does not contain the following clauses: DISTINCT, AGGREGATION, GROUP BY, START WITH, CONNECT BY, ROWNUM, and the operations (UNION ALL, INTERSECT, etc.). This type of view allows the UPDATE, INSERT, and DELETE commands to change data in the tables. To check whether a view can be used, see the data dictionary views ALL_UPDATABLE_COLUMNS, DBA_UPDATABLE_COLUMNS, and USER_UPDATABLE_COLUMNS.
Sequences Oracle has a generator of sequential numbers in a multiuser environment that is very useful. An order code, for example, that is automatically created in a system can use the sequence generator. Even when several users simultaneously access this generator, it creates a unique number for each user. The numbers of the sequence are whole numbers with up to 38 digits. Oracle stores their definitions in a table of the database dictionary that is in the System tablespace. A sequence number can be generated by a SQL command. Once generated, it is
84
Schema Objects—Chapter 5
available only to that sequence. Therefore, when several users generate sequences, other users will not see them.
Synonyms A synonym is an alias, or code name, for a schema object. It consists of the definition of an entry in the data dictionary, where the alias is associated to an object. There are many advantages to using synonyms. They allow, for example, the hiding of the name of an object and its owner, thus simplifying a SQL command by shortening the name of the object. For example: select * from Scott.emp
could be changed to: select * from tab1.
A synonym can be public, accessible to all users, or private, belonging only to a certain schema.
Indexes Indexes are a data structure associated to tables with the objective of reducing data access time. A table can have one or more indexes associated to it. Indexes, such as the one in this book, reduce the time needed to access information. Instead of skimming the book to find out where a desired subject is located, you just go to the index, which is arranged alphabetically. There you locate the subject, and go immediately to the specified page. Things work similarly with Oracle, which offers several types of indexing for a table, such as B*-tree, B*-tree cluster, hash cluster, reverse key, and bitmap.
85
Chapter 5—Schema Objects
An index does not change how the SQL commands are specified. It simply increases the speed when accessing the rows of a table. Once created, Oracle updates the index when a row is added, eliminated, or changed. While the index speeds up access to queries, the insert, delete, and update operations can slow down if there are many indexes associated to the table. An index can be unique or non-unique. Unique indexes do not allow more than one row to have the same value for the indexed column. Using this type of index is one of the ways to guarantee the integrity of a table, thus preventing identical codes from being written to distinct records. A composite index is based on more than one column. Oracle uses the B*-tree index to balance the access time to any row of a table.
KING MILLER TURNER
TURNER WARD
MILLER SCOTT SMITH
KING MARTIN
JAMES JONES
BLAKE CLARK FORD
BLAKE-ROWID CLARK-ROWID FORD-ROWID
Figure 5.5:
86
A B*-tree index balances access time.
ADAMS ALLEN
Schema Objects—Chapter 5
The upper branches of the B*-tree index contain data that points to a lower branch, which contains the index and the rowid of the table associated to the index.
Clusters Clusters are groups of tables and, at the same time, an alternate method that shares the same blocks, since they have common columns that are frequently used. The EMP and DEPT tables, for example, have in common the Deptno column. When those tables are clustered, the rows of both tables are put in the same data blocks, as shown in the next figure: Clustered Key (DEPTNO) 10
EMP TABLE
DNAME
LOC
SALES
BOSTON
EMPNO
ENAME
. . .
1000 1321 1841
SMITH JONES WARD
. . . . . . . . .
DNAME
LOC
ADMIN
NEW YORK
EMPNO
ENAME
DEPTNO
. . .
932 1000 1139 1277 1321 1841
KEHR SMITH WILSON NORMAN JONES WARD
20 10 20 20 10 10
. . . . . .
. . . . . .
. . . . . .
DEPT Table 20
Figure 5.6:
EMPNO
ENAME
. . .
932 1139 1277
KEHR WILSON NORMAN
. . . . . . . . .
DEPTNO
DNAME
LOC
10 20
SALES ADMIN
BOSTON NEW YORK
Clustered Tables
Unclustered Tables
Related data stored together, more efficiently
Related data stored apart, taking up more space
This disposition reduces the time of disk I/O.
87
Chapter 5—Schema Objects
Hash Clusters Hash clusters can be created through a method called hashing. Hashing improves the performance of data recovery. Oracle uses a HASH function to generate a distribution of numeric values also called Hash that are based in the keys of a cluster.
Stored Procedures and Functions Procedures and functions are objects that group a set of SQL or PL/SQL commands. A procedure can be executed in SQL*Plus or through a call made by an Oracle application. Procedures and functions are identical, except that a function always returns a value, and procedures do not. Database Applications Program code Program code
Stored Procedure
HIRE_EMP (...); Program code ode
HIRE_EMP (...); Program code
BEGIN
HIRE_EMP (...); END;
Progr
Program code
Program code HIRE_EMP (...); Program code
Database
Figure 5.7:
88
Commands are grouped in stored procedures.
Schema Objects—Chapter 5
Packages A package is a group of procedures and functions stored together with cursors and variables. A procedure that is inside a package can be invoked through the specification of the name of this package, from a point, or by the name of the procedure, such as is shown in the next example. Notice the hire_emp function contained in the emp_mgmt package is triggered. EXECUTE emp_mgmt.hire_emp (‘TSMITH’, ‘CLERK’, 1037, SYSDATE, 500, NULL, 20); Database Applications
EMP_MGMT
Program code
FIRE_EMP(...)
EMP_MGMT.FIRE_EMP (...);
BEGIN
Program code
END;
EMP_MGMT.HIRE_EMP (...); Program code HIRE_EMP(...) BEGIN
Program code
END;
EMP_MGMT.HIRE_EMP (...); Program code EMP_MGMT.SAL_RAISE (...); SAL_RAISE(...) Program code BEGIN END;
Database
Figure 5.8:
Triggering a function in a package.
89
Chapter 5—Schema Objects
Triggers Triggers, which are a special type of procedure, are automatically executed when an INSERT, UPDATE, or DELETE command is executed. A trigger can either contain SQL and PL/SQL commands to be executed as a unit or call the stored procedures. The main difference between a trigger and a procedure is that procedures are executed through a call made by the user, while triggers are triggered by the database.
Roles A role is a method for distributing privileges for working with a database. When you create a database object you can distribute the privilege or assign privileges to a role. If a role is granted to a user, he or she obtains all the privileges associated to that role. User Scott, for example, has two roles assigned to him—Connect and Resource. These, in turn, contain specific privileges.
Database Links A database link is an object that describes a path from one database to another. It is used to perform the connection to a remote database, and requires that the SQL program SQL*Net is run on each of the machines.
Snapshots A snapshot, also called a materialized view, is a copy of part of a table or the entire table. It reflects the current status of the table that is being copied. The origin table is known as the master table. There are two types of snapshots: Read-Only, also known as publish-and-subscribe replication, and Updatable, also known as update-anywhere replication. The Read-Only snapshot does not 90
Schema Objects—Chapter 5
allow changes, while the Updatable snapshot can make changes in the local copy, which periodically updates the master table.
Users Any person who accesses an Oracle database is a user. Each user has a name and a password. During the installation of this database, the administrator creates some default users and passwords that are used to access Oracle for the first time. This chapter reviewed the schema objects, which are logical data structures. This ends the discussion of basic database concepts. The next part of this book introduces SQL.
91
Part II
SQL In the second part of the book you will learn how the SQL*Plus utility works and receive an introduction to the SQL language. Chapter 6: SQL*PLus Chapter 7: Basic SQL
93
Chapter 6
SQL*Plus This chapter shows you SQL*Plus, a tool that allows the handling of a database through individual and interactive execution of the SQL commands. In addition to the direct execution of SQL commands, SQL*Plus allows the configuration of the PL/SQL commands. PL/SQL is an Oracle extension to the standard SQL. While this may be executed both in the character and graphic modes, SQL*Plus shows the results only in the character mode. SQL*Plus is simple to operate and represents the fastest way to query and create quick reports. By using the PL/SQL language extensions, you can create stored procedures. To configure SQL*Plus, click on the Start button, then on Programs | Oracle Home | Application Development | SQL*Plus.
Figure 6.1: Configuring SQL*Plus.
If the user is not connected to the database, the user name, password, and host string are required. For the local database, it is not necessary to specify the string.
95
Chapter 6—SQL*Plus
Figure 6.2: Logging on in SQL*Plus.
The database is then configured. If it is already configured, the SQL*Plus screen will be displayed immediately.
Figure 6.3: The initial SQL*Plus screen.
The line with the SQL> prompt is where you enter the SQL commands. The SQL*Plus interface allows a SQL command to occupy several lines. It will execute the command only when the semicolon (;) is typed and the Enter key is pressed. To execute the last command typed in the buffer, the user types the slash (/) and presses the Enter key. Consider the two next examples, in which the contents of the DEPT and EMP tables are displayed using only one command line. For now, don’t worry about the SQL command that is shown; we will examine it later. The SELECT command retrieves and displays the contents of a table. The asterisk (*) indicates that all the columns of the DEPT table should be displayed.
96
SQL*Plus—Chapter 6
Figure 6.4: Displaying the fields of the DEPT table.
Figure 6.5: Contents of the EMP table.
In the next example, three lines are used to execute the SELECT command, which shows the employees with salaries above $2,500. When you reach the end of a line, press the Enter key to go to the next line.
97
Chapter 6—SQL*Plus
Figure 6.6: A single command can take up several lines.
Menus The following menus are useful in SQL*Plus.
File Menu The File menu contains the following options: Open opens a file of SQL commands that was previously written with the extension .sql. Save allows the writing to the buffer of a text file that receives the extension .sql as default. The Replace suboption changes the contents of an existing file with the contents of the buffer. The Append suboption adds the contents of the buffer to the specified file. Save As writes the contents of the buffer or the file that was configured with another name. Spool stores the results of a query in a file. As the default, the file created has the extension .lst. To disable Spool for queries, you must activate the Spool Off option. Run lists and executes the SQL command or a PL/SQL block that is stored in the buffer.
98
SQL*Plus—Chapter 6
Cancel interrupts the operation that is being executed. Exit makes a commit of all the changes made to the database.
Edit Menu The Edit menu includes the following options: Copy sends the selected text to the Windows clipboard. Paste pastes the contents of the clipboard to the command line of SQL*Plus, with a maximum size of 3,625 characters. Clear clears the contents of the screen and buffer. Editor opens an editor in which files of PL/SQL commands and their settings can be edited. As the default, Windows Notepad is selected. The name of the file defaults to afiedt.buf. Whenever the editor is called by the Invoke Editor option, the contents of the buffer are automatically transferred to it.
Figure 6.7: Windows Notepad showing the contents of the buffer.
Find Menu The Find menu contains the Find and Find Next options. Find opens a dialog box in which the user can type text to search for. After clicking on the OK button in this dialog box, the occurrence of the text is highlighted. Find Next finds the next occurrence. The search is always initiated from the current screen; however, you can use the cursor keys if you want to start from the beginning of the text.
99
Chapter 6—SQL*Plus
Options Menu The Options menu allows you to change SQL*Plus elements. The Environment option opens a dialog box that has two parts. The Define Options list allows you to change the environment elements, such as variables and characteristics of SQL*Plus, the printing of column headers, and the formatting of numeric fields.
Figure 6.8: The Environment dialog.
The Screen Buffer area controls the number of characters and lines that are maintained and displayed by SQL*Plus. As the default, the buffer is adjusted to display up to 1,000 lines, with 100 characters. The line width can be adjusted in the Buffer Width field, with values ranging from 80 to 1,000 characters, while the number of lines can be set in the Buffer Length field, with values varying from 100 to 2,000 lines. To change a parameter, just select it and change the status of the command, or enter a new value for it. The following figure shows the HEADING parameter, which defaults to Enable and will be changed to Disable.
100
SQL*Plus—Chapter 6
Figure 6.9: Setting options for headings.
Examine the next screen, in which the SELECT command was executed to change the status of HEADING, and then the SELECT command was executed again.
Figure 6.10: The effect of disabling the column headings.
Most of these parameters can be changed through the SET command directly from the edit line.
101
Chapter 6—SQL*Plus
Commands SQL*Plus is not noted for its ease of use. It does not store the typed commands so that you can access and execute them directly later. To change the contents of the edit buffer, you need to use special commands. The edit resources are particularly useful when editing procedures, functions, or triggers. Below is a list of SQL*Plus commands. Later in this chapter, we will show you the commands used most often. Command
@ @@ / ACCEPT APPEND BREAK BTITLE CHANGE CLEAR COLUMN COMPUTE CONNECT COPY DEFINE DEL DESCRIBE DISCONNECT
102
Description Executes the specified file of commands. Executes a file of nested commands. Executes the command or PL/SQL block. Reads a line of entries and stores it in a user variable. Adds the text to the end of the current line. Specifies where and how the formatting must change a report, or enumerates the current settings. Positions and formats a title at the end of each page of the report. Changes the text of the current line. Reinitiates the current value of the adjustments made to the specified action. Specifies the attributes to a certain column, and displays the current status of all columns. Computes and displays the summary lines, and displays the Compute settings. Connects the user to the database. Copies data from a query to a local or remote table. Specifies a user variable, and assigns to it a value of type char. Deletes one or more lines of the buffer. Enumerates the definitions of the columns for the table, synonym, or current/specified view. Executes a commit of the pending changes, and disconnects the user from the database without leaving SQL*Plus.
SQL*Plus—Chapter 6
Command EDIT EXECUTE EXIT GET HELP HOST INPUT LIST PAUSE
PRINT PROMPT REMARK REPFOOTER REPHEADER RUN RUNFORM SAVE SET SHOW SPOOL SQLPLUS START
Description Invokes a word editor of the operating system, transferring to it the contents of the buffer. Executes a PL/SQL command. Terminates SQL*Plus and returns to the operating system. Loads a text file to the SQL buffer. Enables the help system. Executes a command of the operating system without leaving SQL*Plus. Adds one or more lines after the current line of the buffer. Lists one or more lines of the SQL buffer. Displays a blank line following another line containing text, and waits for the user to press Return, or displays two empty lines and waits for the user to answer. Displays the contents of a bind variable. Sends the specified message to the screen. Starts a comment line. Positions and formats a footer at the end of each current report, or enumerates the current definition. Positions and formats a header at the end of each current report, or enumerates the current definition. Enumerates and executes the SQL command that is stored in the buffer. Executes an application of the SQL*Forms from SQL*Plus. Saves the contents of the SQL buffer to a text file. Attributes the contents to a system variable. Displays the value of a system or environment variable. Stores the results of a query in a text file, and optionally sends them to a printer. Starts SQL*Plus from the operating system. Executes the contents of the file of the specified commands.
103
Chapter 6—SQL*Plus
Command STORE TIMING TTITLE UNDEFINE VARIABLE WHENEVER OSERROR WHENEVER SQLERROR
Description Saves the environment attributes of the current session of SQL*Plus in a text file. Records the time elapsed, or displays the active timers. Positions and formats the title at the top of each page of the report. Deletes one or more variables that were previously defined. Declares a bind variable. Stops the execution of SQL*Plus if an operating system command generates an error. Stops the execution of SQL*Plus if a SQL or PL/SQL command generates an error
For help with command syntax, type HELP name_of_command: HELP prompt
Editing the Command Line Once a command is typed and executed, it is possible to perform several editing operations. The next table shows the specific syntax of the commands used in line editing:
104
Command APPEND text
Abbreviation A text
CHANGE /old/new
C /old/new
CHANGE /text CLEAR BUFFER DEL DEL n DEL * DEL n *
C /text CL BUFF (none) (none) (none) (none)
Purpose Adds the text to the end of the line. Changes the old text into the new text. Deletes the text of the line. Deletes all the lines. Deletes the current line. Deletes line n. Deletes the current line. Deletes from line n up to the current line.
SQL*Plus—Chapter 6
Command DEL LAST DEL m n
Abbreviation (none) (none)
DEL * n
(none)
INPUT INPUT text
I I text
LIST LIST n LIST * LIST n *
L L n or n L* Ln*
LIST LAST LIST m n
L LAST Lmn
LIST * n
L*n
Purpose Deletes the last line. Deletes all the lines from m to n. Deletes from the current line up to line n. Adds lines. Adds the line with the specified text. Enumerates all the lines. Enumerates line n. Enumerates the current line. Enumerates from line n up to the current line. Enumerates the last line. Enumerates from line m up to line n. Enumerates from the current line up to line n.
Correcting Errors Typing errors are the main problem when executing a command. In the next example, the command has the field name “Deptno” typed as “Dep.” When executed, SQL*Plus shows an error. Examine the following: SQL> select * from emp 2 where dep=20 3 and sal>2000; where dep=20 * ERROR on line 2: ORA-00904: invalid name in the column.
105
Chapter 6—SQL*Plus
Changing a Line To solve this problem, we can use the command L2 to tell SQL*Plus to display line 2. Then, we use the c/dep/deptno command to change the word “Dep” to “Deptno,” and use RUN to execute the command line: SQL> L2 2* where dep=20 SQL> c/dep/deptno 2* where deptno=20 SQL> run 1 select * from emp 2 where deptno=20 3* and sal >2000 EMPNO ----7566 7788 7902
ENAME ----JONES SCOTT FORD
JOB ------MANAGER ANALYST ANALYST
MGR ---7839 7566 7566
HIREDATE -------04/02/81 04/19/87 12/03/81
SAL ---2975 3000 3000
COMM DEPTNO ---- -----20 20 20
Adding a New Line To insert a new line after the current line, you must use the INPUT command. Consider the next example. After executing the first command, we decide to add one more line to it: SQL> run 1 2 3*
106
select * from emp where deptno=20 and sal>2000
SQL*Plus—Chapter 6 EMPNO ----7566 7788 7902
ENAME ----JONES SCOTT FORD
JOB ------MANAGER ANALYST ANALYST
MGR ---7839 7566 7566
HIREDATE -------04/02/81 04/19/87 12/03/81
SAL ---2975 3000 3000
COMM ----
DEPTNO -----20 20 20
Just press I to open a new line. You must type the rest of the command and/or press the Enter key to open another line. Then, you see the inclusion in the line order by hiredate, which will organize the table by hire date: SQL> i 4 order by hiredate; EMPNO ----7566 7902 7788
ENAME ----JONES FORD SCOTT
JOB ------MANAGER ANALYST ANALYST
MGR ---7839 7566 7566
HIREDATE -------04/02/81 12/03/81 04/19/87
SAL ---2975 3000 3000
COMM ----
DEPTNO -----20 20 20
Adding Text to the End of a Line To add text to the end of a specific line of the buffer, use the APPEND command. First use the LIST command, followed by the line you want to edit. Then enter the APPEND command, followed by the text. If the text starts with a blank character, leave two spaces between the word “append” and the beginning of the word. Otherwise, it will be attached to the last character of the current line. Following is the procedure to include another restriction to the second line of the buffer. After executing the APPEND command, press L to see the command as a whole and RUN to execute it. When you specify strings of text, include them inside single quotation marks.
107
Chapter 6—SQL*Plus SQL> L2 2* where deptno=20 SQL> append and job=’ANALYST’ 2* where deptno=20 and job=’ANALYST’ SQL> l 1 select * from emp 2 where deptno=20 and job=’ANALYST’ 3 and sal>2000 4* order by hiredate SQL> run 1 select * from emp 2 where deptno=20 and job=’ANALYST’ 3 and sal>2000 4* order by hiredate EMPNO ----7902 7788
ENAME ----FORD SCOTT
JOB MGR ------ANALYST ANALYST
HIREDATE ---- -------7566 12/03/81 7566 04/19/87
To insert a line before line 1, you must specify 0 (zero), followed by the text of the new line.
Deleting Lines To delete a line from the buffer, use the DEL command. If you specify this command without any parameters, it will delete the current line. If it is specified with a number, it will delete the specified line. SQL> del 3 SQL> l 1 select * from emp 2 where deptno=20 and job=’ANALYST’ 3* order by hiredate
108
SQL*Plus—Chapter 6
The DESCRIBE Command This command is very useful when the developer wants to access the characteristics of a table’s fields directly in the data dictionary. Let’s say you forget the correct name of a column in a table. By using the DESCRIBE command, you can have a quick view of the structure of the specified table. Syntax: DESCRIBE name_of_table.
Here are some examples: SQL> describe dept Name Null? ------------DEPTNO NOT NULL DNAME LOC SQL> describe emp;
Type -----------NUMBER(2) VARCHAR2(14) VARCHAR2(13)
Name -------EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Type -----------NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)
Null? -------NOT NULL
109
Chapter 6—SQL*Plus
The COLUMN Command While quite limited in its interaction and display capabilities, SQL*Plus offers some improvement when making changes to columns with the COLUMN command. These are the parameters of the command: ALI[AS] alias CLE[AR] FOLD_A[FTER] FOLD_B[EFORE] FOR[MAT] format HEA[DING] text JUS[TIFY] {L[EFT]|C[ENTER]|C[ENTER]|R[IGHT]} LIKE {expr|alias} NEWL[INE] NEW_V[ALUE] variable NOPRI[NT]|PRI[NT] NUL[L] text OLD_V[ALUE] variable ON|OFF WRA[PPED]|WOR[D_WRAPPED]|TRU[NCATED]
We’ll examine some of these parameters and their uses in the following sections.
Changing Headers Column titles that are displayed by SQL*Plus reflect the name given to the column in the table. Often, it is not easy to understand the name, since there is no standard format. You can define a title for a column that is more easily understood by using the HEADING parameter, as the following shows: Syntax: COLUMN name_of_column HEADING title 110
SQL*Plus—Chapter 6
To change some of the column titles in the EMP table, insert the following commands: COLUMN DEPTNO HEADING Department COLUMN ENAME HEADING LastName COLUMN SAL HEADING Salary SQL> COLUMN COMM HEADING Commission SQL> COLUMN HIREDATE HEADING Hired SQL> select * from emp where deptno=20 2 ; EMPNO ----7369 7566 7788 7876 7902
LastName -------SMITH JONES SCOTT ADAMS FORD
JOB MGR -------- ---CLERK 7902 MANAGER 7839 ANALYST 7566 CLERK 7788 ANALYST 7566
Hired -------12/17/80 04/02/81 04/19/87 05/23/87 12/03/81
Salary -----800 2975 3000 1100 3000
Commission Department ---------- ---------20 20 20 20 20
If the title has more than one word, enclose them in single or double quotation marks. If the title is too long for one line, use the vertical bar to start a new line. SQL> COLUMN empno HEADING “Employee|ID” SQL> select empno,ename,sal from emp where deptno=30; Employee ID -------7499 7521 7654 7698 7844 7900
LastName
Salary
-------ALLEN WARD MARTIN BLAKE TURNER JAMES
-----1600 1250 1250 2850 1500 950
111
Chapter 6—SQL*Plus
To change the style of the line below the title, use the SET UNDERLINE command followed by the desired character: SQL> set underline = SQL> select * from dept 2; Department ========== 10 20 30 40
DNAME ========== ACCOUNTING RESEARCH SALES OPERATIONS
LOC ======== NEW YORK DALLAS CHICAGO BOSTON
WARNING: The hyphen must be specified in quotation marks; otherwise, SQL* Plus will misinterpret it.
Formatting Numeric Columns Using the FORMAT parameter, you can change the appearance and precision of the display of a numeric column. As the default, it is displayed with a size of 10 characters. Values greater than this are rounded. Syntax: COLUMN name_of_column FORMAT style
The format can contain numbers, commas, dollar signs, brackets, and leading zeros. Element 9 0 $ B MI S
112
Example 9999 0999 $9999 B9999 9999MI S9999
Description Displays a number in its position. Displays a zero in its position. Inserts a dollar sign in front of the number. Displays zero values as blank. Displays “–” after a negative value. Displays “+” for positive values and “–” for negative values.
SQL*Plus—Chapter 6
Element PR D
Example 9999PR 99D99
G
9G999
L , . V
L999 9,999 99.99 999V99
EEEE RN or rn
9.999EEEE RN
DATE
DATE
Description Displays the negative value inside “<>”. Displays the decimal part separated from the integer part. Displays the group separator in the specified position. Displays the current symbol in the position. Displays a comma in the position. Displays a period in the position. Multiplies the value by 10n, where n is the value following v. Displays the number in scientific notation. Displays Roman numerals. The value can be between 1 and 3999. Displays the value in the date format MM/DD/YY for Julian values.
To display the Sal field with a dollar sign, you can use the following command: SQL> COLUMN SAL FORMAT $99,990 select ename,sal from emp where deptno=20 ENAME ----SMITH JONES SCOTT ADAMS FORD
SAL ----$800 $2,975 $3,000 $1,100 $3,000
To change the width of a column, use the element A followed by the number of characters that the column must contain: SQL> COLUMN ENAME FORMAT A4 SQL> select ename,sal from emp where deptno=20;
113
Chapter 6—SQL*Plus ENAME ----SMITH JONES SCOTT ADAMS FORD
SAL ----800 2,975 3,000 1,100 3,000
Copying Attributes from Columns You can apply the formatting attributes from one column to another column. This saves you time when creating the formats. In this case, you must use the LIKE clause of the COLUMN command. Consider the following example: SQL> column comm like sal SQL> select ename,sal,comm from emp where deptno=30 ENAME -----ALLEN WARD MARTIN BLAKE TURNER JAMES
SAL ----1,600 1,250 1,250 2,850 1,500 950
COMM ----300 500 1,400 0
Displaying the Attributes of a Column To display the current attributes of a column, use the COLUMN command followed by the name of the column: COLUMN column_name
114
SQL*Plus—Chapter 6
Here is an example: SQL> column sal; COLUMN sal ON FORMAT 99,999 SQL>
To list the attributes of all the columns, enter the COLUMN command without specifying a name for it: COLUMN
To delete the definition of a column’s attributes, use the following syntax: COLUMN column_name CLEAR
To delete the definition of all the columns, use the COLUMNS clause of the CLEAR command: SQL> CLEAR COLUMNS columns cleared
Temporarily Disabling the Attributes of a Column If you want to temporarily disable the attributes of a column, use the on/off option of the COLUMN command. To disable the attributes, use: COLUMN column_name OFF
To enable the attributes, use: COLUMN column_name ON
115
Chapter 6—SQL*Plus
The SAVE Command SQL*Plus allows you to store one or more commands in a file called a command file. This operation consists of writing the contents of the buffer in a text file that can be executed later. To save the current command or PL/SQL block, use the SAVE command followed by a filename: SAVE file_name
SQL*Plus adds the extension .sql to the name provided. In the next example, we list the contents of the buffer. The command specifies the employees who do not work in department 10, by descending order of salary. Then, we write a file called depdif10. SQL> l 1 select ename,sal , comm from emp 2 where deptno<>10 3* order by sal desc SQL> save depdif10 File depdif10 created
The INPUT command allows you to enter several command lines in the buffer without executing them. In the next example we create a query that shows the commissions of salesmen and format its columns. If this is a frequent task, we can save it in the machine for subsequent use. First, the contents of the buffer must be cleared: SQL> CLEAR BUFFER
Then, the INPUT command is typed without the semicolon at the end of the line and without the commands that will be written: SQL> input 1 column ename heading Salesman 2 column sal heading Salary format $99,999 3 column comm like sal heading Commission 116
SQL*Plus—Chapter 6 4 select empno,ename,sal,comm 5 from emp 6 where job="SALESMAN" 7
After pressing the Enter key in the last line, we write the file: SQL> save sales Creating file sales SQL>
The GET Command To load the contents of a command file to the buffer, use the GET command followed by the name of the file: GET file_name SQL> get depdif10 1 select ename,sal, comm from emp 2 where deptno<>10 3* order by sal desc SQL> run 1 select ename,sal, comm from emp 2 where deptno<>10 3* order by sal desc Salesman -------SCOTT FORD JONES BLAKE ALLEN TURNER WARD
Salary -----$3,000 $3,000 $2,975 $2,850 $1,600 $1,500 $1,250
Commission ----------
$300 $0 $500 117
Chapter 6—SQL*Plus MARTIN ADAMS JAMES SMITH
$1,250 $1,100 $950 $800
$1,400
The RUN command will work only when the file contains SQL or PL/SQL commands. If we try to load the sales file with the GET command and execute RUN, an error will occur in the first line. In this case, you must use the START command.
The START Command The START command recovers the file and executes it immediately: START file_name
If the file has the extension .sql, you don’t have to specify it: SQL> clear buffer buffer contents removed SQL> start sales EMPNO ----7499 7521 7654 7844 SQL>
118
Salesman -------ALLEN WARD MARTIN TURNER
Salary -----$1,600 $1,250 $1,250 $1,500
Commission ---------$300 $500 $1,400 $0
SQL*Plus—Chapter 6
The EDIT Command Using the EDIT command we can ask the default editor of Windows (normally Notepad.exe) to format the contents of the command file: SQL>EDIT sales
This command opens the editor.
Figure 6.11: Formatting file contents in Notepad.
SQL*Plus is the main tool for Oracle developers. It’s essential that you master it if you want to access the database quickly and execute instant queries. The next chapter introduces the SQL language, which is the basic tool for accessing data in a relational database.
119
Chapter 7
Basic SQL SQL—the Structured Query Language—is the basic tool for accessing data in a relational database. Mastering SQL is the first and most important step you have to take to become a database expert. In recent years, the SQL language has left the mainframe and been extended to the desktop. This is due to the fact that relational databases have also expanded their platforms, and today there are versions that execute on computers ranging from a PC to a mainframe. In addition, the Internet has popularized this language. Because of its appropriate structure for the client/server architecture, more and more applications and pages that access relational databases are being created with the SQL language. This chapter does not intend to turn you into a SQL expert. It simply gives you an overview of this type of language, so you can create your first queries with SQL. For those who wish to become experts, we recommend reading books specifically about SQL, such as Learn SQL (Wordware Publishing). Learn SQL teaches the SQL standard, and contains appendixes with the extensions of the language for major databases, including a complete list of the syntax for Oracle commands.
121
Chapter 7—Basic SQL
Oracle and SQL Although there are some standards for the SQL language, most database vendors have created their own extensions to expand the characteristics of these applications. This is the case with Oracle and PL/SQL. Some of these commands are covered in this and the next chapters; however, we will concentrate on the main commands of the SQL language.
SQL Language Basics You will be able to perform most activities related to querying and manipulating a database by learning just a few commands and functions. The main commands and functions that will be discussed in this chapter are listed below: Commands SELECT INSERT DELETE UPDATE COMMIT ROLLBACK
Functions SUM() AVG() MAX() MIN() COUNT() SYSDATE()
Types of SQL Declarations The SQL declarations, or commands, are divided into two major categories, according to their functionality. They are the data definition language (DDL) commands and the data manipulation language (DML) commands.
122
Basic SQL—Chapter 7
DDL (Data Definition Language) The DDL, or data definition language, is the part of the SQL language used to define data and objects in a database. When these commands are used, the Oracle data dictionary receives some entries. In this category are the commands described below. They are: Command CREATE TABLE CREATE INDEX ALTER TABLE DROP TABLE DROP INDEX GRANT
Function Creates a table Creates an index Changes or inserts a column of a table Eliminates a table from the database Eliminates an index Grants access privileges to a user
DML (Data Manipulation Language) DML, the data manipulation language, is the part of SQL used to recover or manipulate data. It contains the commands responsible for queries and changes made to the tables. The following are some of the most important commands in this category: Command SELECT INSERT DELETE UPDATE
Function Recovers data from a table or view; this is the main command in SQL Inserts a row in a table Deletes a row from the table Changes the contents of the columns (fields) of the table.
At the end of this chapter is a list containing Oracle’s main commands. See the online help for guidance on the syntax.
123
Chapter 7—Basic SQL
The SELECT Command The SELECT command is the essence of the SQL language. You have seen it in many of the previous examples, and it is explained here in detail. Syntax: SELECT [DISTINCT | ALL] { * | { [schema.]{table | view}.* | expr [c_alias] } [, { [schema.]{table | view}.* | expr [c_alias] } ] ... } FROM [schema.]{table | view} [t_alias] [, [schema.]{table | view} [t_alias] ] ... [WHERE condition ] [GROUP BY expr [, expr] ... [HAVING condition] ] [{UNION | UNION ALL |MINUS} SELECT command ] [ORDER BY {expr | position} [ASC | DESC] [, {expr | position} [ASC | DESC]] ...]
Arguments: DISTINCT Returns only one copy of each set of duplicated rows, that is, the rows that have the same content as another. SQL> select distinct job from emp; JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN
124
Basic SQL—Chapter 7
ALL This is the default. It returns all the selected rows. * Selects all the columns of tables or views specified in FROM. table.* Selects all the columns of the specified table. view.* Selects all the columns of the specified view. expr Selects an expression, normally the name of a column or an expression, formed by a table or view specified in a snapshot. c_alias Creates an alias for the column. schema This is the schema that contains the table. The user’s schema is used when no schema is specified. The following example shows what happens when someone tries to display data from a table in another schema. The result is an error. Then, the name of the schema to which the table belongs is specified. Let’s use a user other than Scott. SQL> select * from job 2 ; select * from job * ERROR at line 1: ORA-00942: table or view does not exist SQL> select * from demo.job;
125
Chapter 7—Basic SQL JOB_ID -----667 668 669 670 671 672
FUNCTION ----------CLERK STAFF ANALYST SALESPERSON MANAGER PRESIDENT
6 lines selected.
t_alias Creates an alias, view, or snapshot of the table. WHERE Filters the rows that will be displayed by the query. Without this clause, all the rows are displayed. GROUP BY Groups the selected rows based on the value of expr in each row, and returns only one row of information for each group. For example, in the EMP table we can use this clause to total or view information about departments or functions: SQL> select deptno, min(sal), max(sal), sum(sal) from emp group by deptno; DEPTNO -----10 20 30
MIN(SAL) -------1300 1000 950
MAX(SAL) -------5000 3000 2850
SUM(SAL) -------8750 11075 9400
SQL> select job, sum(sal) from emp group by job;
126
Basic SQL—Chapter 7 JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN
SUM(SAL) -------6000 4350 8275 5000 5600
The next example generates an error, because the Ename field does not make sense in this context: SQL> select deptno, ename from emp group by deptno; select deptno, ename from emp group by deptno * ERROR at line 1: ORA-00979: not a GROUP BY expression
The list of expressions may contain only the following expressions: constants, group functions, user functions, uid and sysdate, and expressions identical to those used by GROUP BY. HAVING Filters the rows returned, displaying only those rows where the expression is true. SQL> select job, min(sal), max(sal) from emp 2 group by job; JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN
MIN(SAL) -------3000 950 2450 5000 1250
MAX(SAL) -------3000 1300 2975 5000 1600
127
Chapter 7—Basic SQL SQL> select job, min(sal), max(sal) from emp 2 group by job 3 having job <> ‘MANAGER’; JOB --------ANALYST CLERK PRESIDENT SALESMAN
MIN(SAL) -------3000 950 5000 1250
MAX(SAL) -------3000 1300 5000 1600
UNION Returns all the unique rows selected by any query. UNION ALL Returns all the rows selected by the queries, including duplicates. MINUS Selects all the rows selected by the first query, but not by the second query. ORDER BY expr Organizes the rows returned by the SELECT command. expr The expression, generally a field, by which the rows will be sorted. The default is ASC; it sorts in ascending order. DESC sorts in descending order. SQL> select * from emp order by job; EMPNO ----7788 7902 7369 7876 7934
128
ENAME -----SCOTT FORD SMITH ADAMS MILLER
JOB ------ANALYST ANALYST CLERK CLERK CLERK
MGR ---7566 7566 7902 7788 7782
HIREDATE ---------APR-19-87 DEC-03-81 DEC-17-80 MAY-23-87 JAN-23-82
SAL ---3000 3000 1000 1100 1300
COMM ----
DEPTNO -----20 20 20 20 10
Basic SQL—Chapter 7 7900 7566 7782 7698 7839 7499 7654 7844 7521
JAMES JONES CLARK BLAKE KING ALLEN MARTIN TURNER WARD
CLERK MANAGER MANAGER MANAGER PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN
7698 7839 7839 7839 7698 7698 7698 7698
DEC-03-81 APR-02-81 JUN-09-81 MAY-01-81 NOV-17-81 FEB-20-81 SEP-28-81 SEP-08-81 FEB-22-81
950 2975 2450 2850 5000 1600 1250 1500 1250
300 1400 0 500
30 20 10 30 10 30 30 30 30
Here are some examples showing the use of ORDER BY: SQL> select * from dept; DEPTNO -----10 20 30 40
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS
LOC -------NEW YORK DALLAS CHICAGO BOSTON
SQL> select * from dept order by dname; DEPTNO -----10 40 20 30
DNAME ---------ACCOUNTING OPERATIONS RESEARCH SALES
LOC -------NEW YORK BOSTON DALLAS CHICAGO
SQL> select * from dept order by dname DESC; DEPTNO -----30 20
DNAME ---------SALES RESEARCH
LOC -------CHICAGO DALLAS 129
Chapter 7—Basic SQL 40 10
OPERATIONS ACCOUNTING
BOSTON NEW YORK
The next example combines GROUP BY, HAVING, and ORDER BY: SQL> l 1 select job, min(sal), max(sal) from emp 2 group by job 3 having job <> ‘MANAGER’ 4* order by job DESC SQL> / JOB --------SALESMAN PRESIDENT CLERK ANALYST
MIN(SAL) -------1250 5000 950 3000
MAX(SAL) -------1600 5000 1300 3000
All the columns specified in ORDER BY or GROUP BY must be specified in the list of columns and expressions of the SELECT command.
Data Types Before we continue our discussion of commands, let’s turn our attention to the data types that can be stored in an Oracle database. When creating a table you must provide certain information, such as the name of the table, and names and data types for each column. The SQL*Plus DESCRIBE command shows the structure of a table. The characteristics of the EMP table are:
130
Basic SQL—Chapter 7
Figure 7.1: Using the DESCRIBE command.
Eight columns form this table, with data types like number, varchar2, and date. Other types are also available; their use will depend on what was decided during the database planning session. In Oracle, data stored in a table can be of the types described below.
Oracle 8 Data Types Oracle 8 has several standard data types. In addition, you can create your own. Below is a list of the data types supported by Oracle: Data Type BFILE BLOB CHAR(size) CLOB DATE LONG
Description Contains a locator for the external binary file. The maximum size is 4 Gbytes. A binary object with a maximum size of 4 Gbytes. A fixed field with a maximum size of 2,000 bytes. A binary object containing characters of type single byte. It allows a maximum size of 4 Gbytes. A valid date from 1/1/4712 B.C. to 12/31/4712 A.D. A variable character with a size up to 2 Gbytes.
131
Chapter 7—Basic SQL
Data Type LONG RAW NCHAR(size) NCLOB
NVARCHAR2(size) NUMBER(p,s)
RAW(size) ROWID MLSLABEL VARCHAR2(size)
Description Variable of the type raw binary, with a size up to 2 Gbytes. Data with fixed size, of type character, and with a maximum size of 2,000 bytes. Object of type character containing characters of type multi byte. It has a fixed size of up to 4 Gbytes. Data of type character, with variable size limited to 4,000 bytes. Data of type number with precision p and scale s. The precision may vary from 1 to 38, and the scale from –84 to +127. Data of type raw binary with maximum size of 2,000 bytes. Hexadecimal string that represents the unique address of a row of the table. Binary format of a label of the operating system. This is not used anymore. Data of character type with variable size limited to 4,000 bytes.
Synonyms Some synonyms have been created for compatibility between Oracle 8 and the SQL-92 language: ANSI SQL Data Type CHARACTER(n) CHAR(n) CHARACTER VARYING(n) CHAR VARYING(n) NATIONAL CHARACTER(n) NATIONAL CHAR(n) NCHAR(n) NATIONAL CHARACTER VARYING(n) NATIONAL CHAR VARYING(n)
132
Oracle Data Type CHAR(n) VARCHAR(n)
NCHAR(n)
Basic SQL—Chapter 7
ANSI SQL Data Type NCHAR VARYING(n) NUMERIC(p,s) DECIMAL(p,s) INTEGER INT SMALLINT FLOAT(b) DOUBLE PRECISION REAL
Oracle Data Type NVARCHAR2(n) NUMBER(p,s)
NUMBER(38)
NUMBER
Numeric Data Type The number type is used to store numeric values of various types, such as negative and positive numbers, or floating point. Floating-point numbers have precision of 38 digits. The definition of a number is as follows: Number(p,s) p is the precision of up to 38 digits, and s is the scale, i.e., the numbers to the right of the decimal point. The s parameter may be omitted. In this case the scale is zero or an integer number.
Character Data Type Oracle works with four variations of character data. The char type must be used in situations where a field of fixed size is appropriate. The standard size is 1 byte and the maximum size is 255 bytes. The varchar2 type must be used for fields of variable size, with a maximum size of 2,000 characters, such as the fields of the memo type. While it has variable size, the maximum size it can occupy must be specified. The long type is similar to varchar2, but it stores up to 2 GB of information, and has some restrictions. Only one column in a table may have the long type. In addition, it cannot be indexed, or passed as an argument for a function or
133
Chapter 7—Basic SQL
procedure. It also cannot be used in the WHERE, ORDER BY, and GROUP BY clauses.
Date Data Type Oracle stores dates in a date format consisting of the century, year, month, day, hour, minute, and second. All of this data is stored for each field of date type. If only the date is given, the hour is written as 12:00 A.M. If only the time is given, the date is stored as the first day of the current month. A date can be manipulated through the addition or subtraction of days. The following example shows the Hiredate column and a calculated column that shows the date one week after the hire date: SQL> select hiredate, hiredate+7 from emp; HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81
HIREDATE+7 ---------12/24/80 02/27/81 03/01/81 04/09/81 10/05/81
In the next example the sysdate constant is used. It contains the current date to calculate the number of days that the employee has been working for the company. SQL> select ename, hiredate, sysdate-hiredate from emp ENAME -----SMITH ALLEN WARD
134
HIREDATE -------12/17/80 02/20/81 02/22/81
SYSDATE-HIREDATE ---------------6718,4082 6653,4082 6651,4082
Basic SQL—Chapter 7 JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER
04/02/81 09/28/81 05/01/81 06/09/81 04/19/87 11/17/81 09/08/81 05/23/87 12/03/81 12/03/81 01/23/82
6612,4082 6433,4082 6583,4082 6544,4082 4404,4082 6383,4082 6453,4082 4370,4082 6367,4082 6367,4082 6316,4082
14 lines selected.
Binary Data Type Oracle stores binary data in the raw and long raw formats. The raw format stores up to 2,000 bytes and the long raw format stores up to 2 GB. This type of field is appropriate for the storage of sounds or images.
Rowid In Chapter 5 you saw that each row of a table has an identifier, or address. To obtain the address of a row you must use rowid. Consider this next example: SQL> select rowid, deptno, dname, loc from dept; ROWID -----------------AAACqoAACAAAAD9AAA AAACqoAACAAAAD9AAB AAACqoAACAAAAD9AAC AAACqoAACAAAAD9AAD
DEPTNO -----10 20 30 40
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS
LOC -------NEW YORK DALLAS CHICAGO BOSTON
135
Chapter 7—Basic SQL
The rowid data type can have the following formats:
: :
Extended rowid: supports relative addresses of tablespaces and identifies the rows in tables and partitioned indexes. The tables created by Oracle8i always assume this rowid format. Restricted rowid: available only for compatibility with previous versions.
The format returned by Id had the following formatting through version 7.x: BBBBBBBB.RRRR.FFFFF, where BBBBBBBB is the data block, RRRR the row, and FFFFF the file that represents the table. In version 8 the format was changed to four parts: OOOOOOFFFBBBBBBRRR, where:
: : : :
OOOOOO: the number of objects that identifies the database segment. The schema objects in the same segment have the same data object number. FFF: the number of the datafile that contains the row. BBBBBB: the data block that contains the row. The numbers of blocks relate to the datafile, and not to the tablespace. RRR: number of the row in the block.
Expressions and Operators Oracle supports many of the common operators found in most languages. The operators act on the operands, i.e., on the elements that will be analyzed by the operator. There are two classes of operators—unary operators, which act on only one operand, and binary operators, which act on two or more operands.
136
Basic SQL—Chapter 7
Precedence of Operators There are several types of operators. When more than one type is present in an expression, they are evaluated according to the following precedence order: 1. Unary operators 2. Division and multiplication 3. Addition and subtraction 4. Comparison operators 5. NOT operator 6. AND operator 7. OR operator
Types of Operators Below are the types of operators that are supported by Oracle: Type Arithmetic Operate on numeric operands
Character Manipulate strings Comparison Check for similarities and differences
Name
Value/Description
Multiplication Division Subtraction Addition
* / – +
Concatenation
||
Equal to Not equal to Greater than Less than
= != > <
137
Chapter 7—Basic SQL
Type Comparison (cont.)
Name Greater than or equal to Less than or equal to Null
Value/Description >= <= IS NULL
Logical Manipulate comparison NOT expressions AND OR Set Combine the results of UNION two queries in one query INTERSECT
MINUS
Returns the rows selected by any query Returns the rows selected by both queries Returns the rows selected by the first but not the second query
Here are some examples, beginning with the multiplication operator:
Figure 7.2: Operator examples.
138
Basic SQL—Chapter 7
The next example shows how to concatenate, or link, character strings, using the || operator: SQL> select ename || ‘ works as ‘ || job from emp; ENAME||’WORKSAS’||JOB -----------------------SMITH works as CLERK ALLEN works as SALESMAN WARD works as SALESMAN JONES works as MANAGER MARTIN works as SALESMAN BLAKE works as MANAGER
The next example shows the use of a comparison operator. These operators are generally used to compare the contents of a column with a certain value: SQL> select * from emp where comm <>0; EMPNO ----7499 7521 7654
ENAME -----ALLEN WARD MARTIN
JOB -------SALESMAN SALESMAN SALESMAN
MGR ---7698 7698 7698
HIREDATE -------02/20/81 02/02/81 09/08/81
SAL ---1600 1250 1250
COMM ---300 500 1400
DEPTNO -----30 30 30
SAL ---5000
COMM ----
DEPTNO -----10
SQL> select * from emp where sal >3000; EMPNO ----7839
ENAME ----KING
JOB MGR --------- ---PRESIDENT
HIREDATE -------11/17/81
139
Chapter 7—Basic SQL SQL> select * from emp where sal >=3000; EMPNO ----7788 7839 7902
ENAME ----SCOTT KING FORD
JOB --------ANALYST PRESIDENT ANALYST
MGR ---7566 7566
HIREDATE -------04/19/87 11/17/81 12/03/81
SAL COMM ---- ---3000 5000 3000
DEPTNO -----20 10 20
SAL ---800 1600 1250 2975 1250 2850 2450 1500 1100 950 1300
DEPTNO -----20 30 30 20 30 30 10 30 20 30 10
SQL> select * from emp where sal <3000; EMPNO ----7369 7499 7521 7566 7654 7698 7782 7844 7876 7900 7934
ENAME -----SMITH ALLEN WARD JONES MARTIN BLAKE CLARK TURNER ADAMS JAMES MILLER
JOB -------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER SALESMAN CLERK CLERK LERK
MGR ---7902 7698 7698 7839 7698 7839 7839 7698 7788 7698 7782
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81 05/01/81 06/09/81 09/08/81 05/23/87 12/03/81 01/23/82
COMM ---300 500 1400
0
11 lines selected.
The next example shows the use of logical operators combined with other operators: SQL> select * from emp where deptno=30 and sal >2000; EMPNO ----7698
140
ENAME ----LAKE
JOB ------MANAGER
MGR ---7839
HIREDATE SAL -------- ---05/01/81 2850
COMM ----
DEPTNO -----30
Basic SQL—Chapter 7 SQL> select * from emp where deptno<>30 and sal >2000; EMPNO ----7566 7782 7788 7839 7902
ENAME ----JONES CLARK SCOTT KING FORD
JOB --------MANAGER MANAGER ANALYST PRESIDENT ANALYST
MGR ---7839 7839 7566 7566
HIREDATE -------04/02/81 06/09/81 04/19/87 11/17/81 12/03/81
SAL ---2975 2450 3000 5000 3000
COMM ----
DEPTNO -----20 10 20 10 20
SQL> select * from emp where sal <1000 or sal >3000; EMPNO ----7369 7839 7900
ENAME ----SMITH KING JAMES
JOB --------CLERK PRESIDENT CLERK
MGR ---7902 7698
HIREDATE -------12/17/80 11/17/81 12/03/81
SAL ---800 5000 950
COMM ----
DEPTNO -----20 10 30
If you combine more than one logical operator, pay attention to the precedence order. The AND operator is analyzed first and then the OR operator. Now examine the same example with different precedence orders. We want to list all the employees with salaries above $2,500, and who work in department 10 or 30. In the first example, Deptno=30 and Sal>2500 are analyzed as one condition and Deptno=10 as another condition: SQL> select * from emp where deptno=10 or deptno=30 and sal >2500 EMPNO ----7698 7782 7839 7934
ENAME -----BLAKE CLARK KING MILLER
JOB -------MANAGER MANAGER PRESIDENT CLERK
MGR ---7839 7839 7782
HIREDATE -------05/01/81 06/09/81 11/17/81 01/23/82
SAL ---2850 2450 5000 1300
COMM ----
DEPTNO -----30 10 10 10
141
Chapter 7—Basic SQL
To change the logic so that only employees of departments 10 or 30 who earn salaries above $2,500 are listed, you have to place the first condition in parentheses. This forces it to be analyzed first, and its result is then compared to the second expression, Sal>2500. SQL> select * from emp where (deptno=10 or deptno=30) and sal >2500; EMPNO ----7698 7839
ENAME ----BLAKE KING
JOB MGR --------- ---MANAGER 7839 PRESIDENT
HIREDATE -------05/01/81 11/17/81
SAL ---2850 5000
COMM ----
DEPTNO -----30 10
SQL>
Functions A SQL function is a routine that performs a specific operation and returns the result. It is similar to a procedure, except that a procedure does not return any value. A function can receive parameters that will be used in its processing. The basic syntax of a function is: Funcname(arg1,arg2,…ARGn)
Arguments: Funcname The name of the function, such as ABS or LOWER. arg1 and arg2 are the optional parameters of the function. SQL functions can be of two types: single row functions, or scalar, and group functions, or aggregated. A single row function returns the result for each row of a table or view. A group function returns only one result for a group of rows. 142
Basic SQL—Chapter 7
For example, the LOWER function converts its argument to lowercase. In the following example, this function acts on all the rows of a table: SQL> select dname, lower(dname) from dept; DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS
LOWER(DNAME) -----------accounting research sales operations
Those functions can be used in SELECT commands that have the WHERE, START WITH, or CONNECT BY clauses. However, they cannot be used with GROUP BY. SQL> select ename, lower(ename) from emp where deptno=10 ENAME ------CLARK KING MILLER
LOWER(ENAME) ----------clark king miller
The group functions process a group of rows in the table, and return the result. Most of them act on all the rows of the default table. They accept the following parameters: DISTINCT Makes the function act only on the rows that have different values. ALL Makes the function consider all the values (rows), including duplicates. This is the default.
143
Chapter 7—Basic SQL
With the exception of the COUNT function, all other functions ignore null values. The group functions are: AVG Returns the arithmetic average of n. Syntax: AVG([DISTINCT|ALL] n)
COUNT Returns the number of rows of the query. Syntax: COUNT({* | [DISTINCT|ALL] expr})
Expr represents the field or non-null expression. MAX Returns the maximum value of expr. Syntax: MAX([DISTINCT|ALL] expr)
MIN Returns the minimum value of expr. Syntax: MIN([DISTINCT|ALL] expr)
Following are several examples of these functions: SQL> select min(sal), max(sal), avg(sal) from emp; MIN(SAL) -------950
144
MAX(SAL) -------5000
AVG(SAL) -------2087.5
Basic SQL—Chapter 7 SQL> select count(*) from emp; COUNT(*) -------14 SQL> select count(comm) from emp; COUNT(COMM) ----------4
The above example returns only the rows with values other than NULL. Note the following example returns only the number of rows with unique department codes: SQL> select count(deptno) from emp; COUNT(DEPTNO) ------------14 SQL> select count(distinct deptno) from emp; COUNT(DISTINCTDEPTNO) --------------------3
The INSERT Command This command inserts a new row in the table and fills the columns with specific values. It is not necessary to assign contents to all fields.
145
Chapter 7—Basic SQL
Basic syntax: INSERT INTO schema.table (columns) VALUES (values)
This example inserts a new row in the DEPT table: SQL> select * from dept; DEPTNO -----10 20 30 40
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS
LOC -------NEW YORK DALLAS CHICAGO BOSTON
SQL> insert into dept values (50,’MARKETING’,’SAO PAULO’); 1 line created. SQL> SELECT * FROM DEPT; DEPTNO -----10 20 30 40 50
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS MARKETING
LOC -------NEW YORK DALLAS CHICAGO BOSTON SAO PAULO
The following example adds a new row with data for all of the fields. Note that you don’t have to specify a name for the fields (columns), because the command assumes that the first value is assigned to the first column, the second value to the second column, and so on.
146
Basic SQL—Chapter 7 SQL> INSERT INTO emp VALUES (7777, ‘RAMALHO’, ‘MANAGER’,7902, SYSDATE, 1200, NULL, 20) 1 line created. SQL> SELECT * FROM EMP WHERE DEPTNO=20; EMPNO ----7369 7566 7788 7876 7902 7777
ENAME ------SMITH JONES SCOTT ADAMS FORD RAMALHO
JOB ------CLERK MANAGER ANALYST CLERK ANALYST MANAGER
MGR ---7902 7839 7566 7788 7566 7902
HIREDATE -------12/17/80 04/02/81 04/19/87 05/23/87 12/03/81 05/10/99
SAL ---800 2975 3000 1100 3000 1200
COMM ----
DEPTNO -----20 20 20 20 20 20
6 lines created.
This example inserts only some fields in the row. In this case, you must specify a SELECT clause with the names of columns to be used: SQL> insert into (select empno,ename,hiredate From emp) values (8888,’PARKER’,sysdate); 1 line created. SQL> select * from emp; EMPNO ----7369 7499 7521 7566 7654
ENAME ------SMITH ALLEN WARD JONES MARTIN
JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN
MGR ---7902 7698 7698 7839 7698
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81
SAL ---800 1600 1250 2975 1250
COMM ---300 500 1400
DEPTNO -----20 30 30 20 30 147
Chapter 7—Basic SQL 7698 7782 7788 7839 7844 7876 7900 7902 7934 7777 8888
BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER RAMALHO PARKER
MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK MANAGER
7839 7839 7566 7698 7788 7698 7566 7782 7902
05/01/81 06/09/81 04/19/87 11/17/81 09/08/81 05/23/87 12/03/81 12/03/81 01/23/82 05/10/99 05/10/99
2850 2450 3000 5000 1500 1100 950 3000 1300 1200
0
30 10 20 10 30 20 30 20 10 20
16 lines selected.
Data Integrity When a row is inserted, Oracle checks the table definitions to see whether any restrictions are being applied to the table. In the case of the EMP table, the Empno field is a unique primary key, which does not allow duplicates. If we try to re-insert the record for Parker, an error will be generated: SQL> insert into (select empno,ename,hiredate From emp) values (8888,’PARKER’,sysdate); insert into (select empno,ename,hiredate From emp) values (8888,’PARKER’,sysdate) * ERROR on line 1: ORA-00001: exclusive restriction (SCOTT.PK_EMP) violated
After inserting the row for employee 8888, the command generated an error, since the key, in this case, the employee number, does not allow duplicates.
148
Basic SQL—Chapter 7
The UPDATE Command The UPDATE command allows the updating of one or more fields of a row or group of rows in a table or a view. The contents of each field must be adjusted with the SET clause. When more than one column is updated, the column=value pairs must be separated by commas. Basic syntax: UPDATE schema.table SET column=value WHERE condition
The next example shows that only some fields of employee 8888 are updated: SQL> update emp set job=’CLERK’, MGR=7839, SAL=2000, DEPTNO=10 WHERE EMPNO=8888; 1 line updated. SQL> select * from emp where empno=8888; EMPNO ----8888
ENAME -----PARKER
JOB ----CLERK
MGR ---7839
HIREDATE SAL -------- ---05/10/99 2000
COMM ----
DEPTNO -----10
The DELETE Command The DELETE command removes rows that match a specified condition from a table or view. Basic syntax: DELETE FROM schema.table WHERE condition
149
Chapter 7—Basic SQL
The next example inserts a row in the DEPT table, and then deletes it: SQL> insert into dept VALUES (60,’MEDIA’,’SAO JOSE’); 1 line created. SQL> select * from dept; DEPTNO -----10 20 30 40 50 60
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS MARKETING MEDIA
LOC --------NEW YORK DALLAS CHICAGO BOSTON SAO PAULO SAO JOSE
6 lines selected. SQL> delete from dept where deptno=60; 1 line deleted. SQL> select * from dept; DEPTNO -----10 20 30 40 50
150
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS MARKETING
LOC -------NEW YORK DALLAS CHICAGO BOSTON SAO PAULO
Basic SQL—Chapter 7
Transactions In addition to the DML and DDL commands we have seen so far, a third category of commands, called TPL (transaction process language), is included in SQL. The commands in this category write to the database the changes made by the DML and DDL commands, and recover the database’s status when something goes wrong. Imagine a situation in which several tables must be updated to reflect a complete transaction. For example, when issuing a sales order, the system updates the inventory, creates a record in the billing table, and updates the payable accounts. If a problem occurs during the update process, one of the tables may not be updated. Oracle has two commands that allow writing data after a successful operation or after recovering the previous situation to the beginning of processing: COMMIT and ROLLBACK. COMMIT writes a transaction to the database. Its basic syntax is: COMMIT [WORK]
ROLLBACK restores a transaction. It recovers the database to the position where it was after the last COMMIT command was executed. Its syntax is: ROLLBACK
The next example shows the contents of the DEPT table. Then a new row is inserted in the table. Imagine that in addition to this particular row, some rows were also inserted in other tables, or data was updated in other locations. In the middle of this process, there is a power outage and the tables are only partially updated. SQL> insert into dept values (70,’PLANT’,’DALLAS’); 1 line created.
151
Chapter 7—Basic SQL SQL> select * from dept; DEPTNO -----10 20 30 40 50 70
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS MARKETING PLANT
LOC --------NEW YORK DALLAS CHICAGO BOSTON SAO PAULO DALLAS
6 lines selected.
It may seem that the row was correctly written to the database. However, it has not yet been written. The row will be written only when the session is ended, or when a COMMIT command is executed. SQL> rollback; Rollback complete. SQL> select * from dept; DEPTNO -----10 20 30 40
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS
LOC -------NEW YORK DALLAS CHICAGO BOSTON
SQL>
Note that the marketing department and plant rows were not definitely written and, therefore, these rows were eliminated when the recovery was performed. 152
Basic SQL—Chapter 7
Here is the same example where COMMIT is executed: SQL> insert into dept values (70,’PLANT’,’DALLAS’); 1 line created. SQL> commit; Validation complete. SQL> rollback; Rollback complete. SQL> select * from dept; DEPTNO -----10 20 30 40 70
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS PLANT
LOC -------NEW YORK DALLAS CHICAGO BOSTON DALLAS
With these basic commands you are able to perform most recovery and table maintenance activities in an Oracle database. In the next chapters you will see many other SQL commands and Oracle extensions (PL/SQL). The following section lists the main PL/SQL commands, which improve the functionality of the SQL language.
153
Chapter 7—Basic SQL
PL/SQL Commands ALTER CLUSTER
COMMENT
ALTER DATABASE
CREATE CLUSTER
ALTER FUNCTION
CREATE CONTROLFILE
ALTER INDEX
CREATE DATABASE
ALTER PACKAGE
CREATE DATABASE LINK
ALTER PROCEDURE
CREATE FUNCTION
ALTER PROFILE
CREATE INDEX
ALTER RESOURCE COST
CREATE PACKAGE
ALTER ROLE
CREATE PACKAGE BODY
ALTER ROLLBACK SEGMENT
CREATE PROCEDURE
ALTER SEQUENCE
CREATE PROFILE
ALTER SESSION
CREATE ROLE
ALTER SNAPSHOT
CREATE ROLLBACK SEGMENT
ALTER SNAPSHOT LOG
CREATE SEQUENCE
ALTER SYSTEM
CREATE SNAPSHOT
ALTER TABLE
CREATE SNAPSHOT LOG
ALTER TABLESPACE
CREATE SYNONYM
ALTER TRIGGER
CREATE TABLE
ALTER USER
CREATE TABLESPACE
ALTER VIEW
CREATE TRIGGER
ANALYZE
CREATE USER
AUDIT
CREATE VIEW
154
Basic SQL—Chapter 7
DROP CLUSTER
DROP SNAPSHOT LOG
DROP DATABASE LINK
DROP SYNONYM
DROP FUNCTION
DROP TABLE
DROP INDEX
DROP TABLESPACE
DROP PACKAGE
EXPLAIN PLAN
DROP PROCEDURE
NOAUDIT
DROP PROFILE
RENAME
DROP ROLE
REVOKE
DROP ROLLBACK SEGMENT
SAVEPOINT
DROP SEQUENCE
SET TRANSACTION
DROP SNAPSHOT
TRUNCATE
This chapter introduced you to the SQL language. With this information you are able to query and navigate database tables. This chapter ends the section on SQL. The next section discusses schema objects, including indexes, sequences, views, and synonyms.
155
Part III
SCHEMA OBJECTS The third part is dedicated to the creation and maintenance of Oracle’s schema objects, such as tables, indexes, views, users, and sequences. The reader will learn how to use the SQL commands that work with these objects. Chapter 8: Data Integrity Chapter 9: Creating and Maintaining Tables Chapter 10: Indexes Chapter 11: Sequences Chapter 12: Views Chapter 13: Users, Privileges, and Roles Chapter 14: Synonyms
157
Chapter 8
Data Integrity Before creating tables and indexes, the Oracle developer must understand the concept of data integrity, which is implemented through constraints and triggers. In this chapter, we will discuss the theory of constraints. Triggers are explored in Chapter 16. A major part of the database developer’s tasks is guaranteeing the integrity and consistency of data stored in the tables. It may seem only logical that a date field contains a date or that a numeric field contains only numbers, but this requires planning, as well as the specification of predefined rules. Data integrity can be defined as rules created by the developer, or DBA, in order to assure the consistency of information maintained in the tables. Take a look at the DEPT and EMP tables below: Each Value in the DNAME column must be unique.
Table DEPT DEPTNO DNAME 20 30
LOC
RESEARCH DALLAS CHICAGO SALES Each value in the DEPTNO column must match a value in the DEPTNO column of the DEPT table.
Each row must have a value for the ENAME column.
Table EMP EMPNO
ENAME
6666 7329 7499 7521 7566
MULDER SMITH ALLEN WARD JONES
… Other Columns... SAL
Each row must have a value for the EMPNO column, and the value must be unique.
Figure 8.1:
5500.00 9000.00 7500.00 5000.00 2975.00
COMM
DEPTNO
100.00 200.00 400.00
20 20 30 30 30
Each value in the SAL column must be less than 10,000
The DEPT and EMP tables.
159
Chapter 8—Data Integrity
When these tables were created, the following integrity rules were stipulated:
: : : : :
The Deptno column of the DEPT table cannot contain duplicate values. The value must be unique. For example, there can’t be two departments with the code 20. The Ename column of the EMP table cannot be left blank. Other columns may have null values, allowing them to be left empty. The Deptno column of the EMP table can contain only those department numbers that correspond to the Deptno column of the DEPT table. The Sal column contains only values below 10,000. The Empno column cannot be empty, and must be unique.
Types of Integrity There are several ways to force data integrity in a table’s columns. Many of them are defined as rules, and are applied to the structures of the table. Constraints are created and/or changed with the CREATE TABLE and ALTER TABLE commands. The rules that can be applied to the columns are described below.
Nulls The null rule allows a row to have a null value (absence of a value) assigned to it, meaning the field can be left blank.
Unique Values The unique value rule means that each value in a particular column is unique, such as Deptno in the DEPT table.
160
Data Integrity—Chapter 8
Primary Key Values The primary key value rule specifies that each row of a table must be identified by a unique value.
Referential Integrity The referential integrity rule determines that the value or group of fields corresponds to the key fields of other tables. For example, the Deptno column of the EMP table accepts only the values that are registered in the Deptno column of the DEPT table. This rule also allows you to specify the type of data manipulation that is allowed on the specified values. Reference Restrict Set to Null Set to Default Cascade
No Action
Description Disables the updating or deletion of the specified data. When specified data is updated or deleted, all the associated data is adjusted to null. When specified data is updated or deleted, all the dependent data is adjusted to the default value. When specified data is updated, all the dependent data is updated too. If a row that is referenced is deleted, all the dependent rows will also be deleted. Disables the updating and deletion of specified data. This is the default operation in Oracle.
Most of these rules are defined as constraints or database triggers.
Triggers Using database triggers is another way to force data integrity. Database triggers are routines written in PL/SQL that are triggered when an insert, update, or delete operation is executed. Triggers are discussed more thoroughly in Chapter 16.
161
Chapter 8—Data Integrity
Integrity Constraints A constraint is a declarative method for defining the rule for a column. Oracle has the following constraints. Their names are similar to those of the integrity rules:
: : : : :
NOT NULL
for rules associated with nulls.
UNIQUE KEY
for unique value rules.
PRIMARY KEY
for rules associated with primary keys.
FOREIGN KEY
for rules associated with referential integrity.
CHECK
for complex rules.
Understanding Constraints Constraints are generated through the SQL commands when a table is created or changed. Once a constraint is created, the database itself applies it, without the need for additional programming. If a SQL command tries to violate a constraint, Oracle cancels the operation, forcing a rollback of the command action. If the Sal field, for example, has a constraint that limits the maximum value to 10,000, and someone tries to insert 11,000, an error message is displayed and the operation is cancelled. Constraints are associated to a specific table and are stored in the data dictionary. Every application that uses a particular table will be restricted by its constraints. Constraints take some processing time to be applied. When rows are inserted individually, the overhead is not noticeable. However, sometimes it is necessary to load thousands of rows in batch processing. In this case, if the information was previously checked, the constraints can be temporarily disabled in order to regain more processing time. Now we will take a look at each of Oracle’s constraints.
162
Data Integrity—Chapter 8
NOT NULL Constraints As the default, Oracle allows all columns to accept null values. The NOT NULL constraint requires that the columns of the table always contain a value. For example, the Ename column of the EMP table has this constraint, while the Comm column allows null values to be accepted. Remember that a NULL is the absence of a value.
UNIQUE KEY Constraints Each of the values in the rows in a column or groups of columns that form the key are required by the UNIQUE KEY constraint to be unique. The Dname column of the DEPT table, for example, has the UNIQUE constraint, because there cannot be more than one department with the same name. The Loc column, on the other hand, can contain duplicate values, because there can be different departments in the same city. The column (or columns) used to define the UNIQUE KEY is also called the UNIQUE KEY. Let’s say a table contains the Area and Number columns. You can use the UNIQUE KEY concept, so that you can insert duplicate area codes and telephone numbers. For example, the telephone number 222-2222 can exist both in Dallas (Area = 214) and in Fort Worth (Area = 817). If a UNIQUE KEY formed by the Area and Number columns is specified, the constraint will not allow the same telephone number to be registered twice in the same city, since Area + Number results in a duplicate key. Oracle forces this type of integrity through indexes. Remember that there is a limit of 32 columns that can be used to compose a UNIQUE KEY. The UNIQUE KEY constraints can be combined with NOT NULL. In this case, Oracle allows the field to be left blank, but it must have two identical values. By including NOT NULL, the user is forced to insert a value, and cannot work with an existing value.
163
Chapter 8—Data Integrity
PRIMARY KEY Constraints The column (or group of columns) included in the definition of the constraint is called the PRIMARY KEY. Each table should have at least one primary key. Figure 8.2 shows the DEPT table, where the Deptno column is the primary key. Therefore, null and duplicate values are not allowed.
FOREIGN KEY Constraints This type of constraint allows the relationship among the tables to be established through the columns with identical content. You must understand the following terminology: Type FOREIGN KEY
Referenced or PARENT KEY
Dependent or child table
Referenced or parent table
Description This is the column (or group of columns) specific to the current table in the definition of the referential integrity constraint, which links to the key field or PRIMARY KEY of the table. The unique key or primary key of the table, which is specified by the FOREIGN KEY. The table or child table containing the FOREIGN KEY, which is dependent on the value of another table. The parent table, i.e., the table referenced by the child table, which tries to find an identical value when specified in the column with the FOREIGN KEY constraint.
For each row of the child table, there must be a corresponding row in the parent table. Several columns can form FOREIGN KEYs. In this case, the primary key of the parent table must have the same characteristics
164
Data Integrity—Chapter 8
(number of columns and data types), and must be limited to 32 columns. The next figure shows that the Deptno column of the EMP table was defined with the FOREIGN KEY constraint, and that it is associated to the DEPT table through the Deptno field. The names of the FOREIGN KEY and PARENT KEY columns do not need to be the same; however, having the same name helps to understand the association. Parent Key Primary key of referenced table.
Table DEPT DEPTNO DNAME 20 30
LOC
RESEARCH DALLAS SALES CHICAGO
Foreign Key (values in dependent table must match a value in unique key or primary key of referenced table).
Referenced or Parent Table.
Table EMP EMPNO
ENAME
JOB
7329 7499 7521 7566
SMITH ALLEN WARD JONES
CEO VP-SALES MANAGER SALESMAN
Figure 8.2:
MGR
HIREDATE
SAL
7329 7499 7521
17-DEC-85 20-FEB-90 22-FEB-90 02-APR-90
9000.00 300.00 500.00
COMM
DEPTNO
100.00 200.00 400.00
20 30 30 20
Defining constraints.
SELF-REFERENTIAL Constraints Another type of referential integrity is the SELF-REFERENTIAL constraint, which references a column in the table itself. Here, the PARENT KEY is in the table itself, and not in an external table. A practical application of this type of constraint is the EMP table. The Mgr column contains an employee number that corresponds to the employee’s manager. To prevent incorrect employee codes from being inserted, you can apply SELF-REFERENTIAL integrity, specifying the Empno column.
165
Chapter 8—Data Integrity
Primary Key of referenced table Referenced or Parent Table
Dependent or Child Table
Foreign Key (values in dependent table must match a value in unique key or primary key of referenced table).
Table EMP EMPNO
ENAME
JOB
MGR
7329 7499 7521 7566
SMITH ALLEN WARD JONES
CEO VP-SALES MANAGER SALESMAN
7329 7329 7499 7521
Figure 8.3:
FORD
MANAGER
SAL 9,000.00 7,500.00 5,000.00 2,975.00
COMM
DEPTNO
100.00 200.00 400.00
20 30 30 30
This row violates the referential constraint, because “7331” is not present in the referenced table’s primary key, therefore, it is not allowed in the table.
INSERT INTO 7571
HIREDATE
7331
23-FEB-90
5,000.00
200.00
30
Using SELF-REFERENTIAL integrity constraints.
Actions Based on Referential Integrity The referential integrity constraints can specify specific actions in the rows of the child tables when the value of the parent table is changed. For example, imagine that department 20 closes. What happens to the rows of the EMP table that refer to it? Or what if the department code changes. What do you do now? Using the three actions associated to the referential integrity constraint, we can resolve these situations. The actions are described as follows:
:
:
166
The No Action (default) option says that the specified keys cannot be updated or deleted, since they violate the referential integrity, i.e., as long as there is an employee associated to a department, the department row in the DEPT table cannot be deleted. Delete Cascade indicates that when a row containing the specified keys is deleted, all the rows of the child table that depend on it are also deleted. In this case, the elimination of
Data Integrity—Chapter 8
:
the row for department 20 in the DEPT table would also eliminate all the rows of employees having this department code. Delete Set Null indicates that when a row containing the specified keys is deleted, all the rows of the child table that depend on it will have their values adjusted to NULL. In this case, the elimination of the row for department 20 would assign NULL to all the rows of employees having this department code.
CHECK Constraints CHECK, the last type of constraint, allows the creation of a routine written in PL/SQL that performs complex tests and returns a value (true or false). When a DML command results in false, the command is undone.
Deferred Constraints A constraint can have its checking postponed until the end of the transaction. In this case, the system causes a rollback of the entire transaction if it is not undone. In the case of a constraint of immediate action, only the last command executed is undone, if it is unsuccessful. The constants can be defined as Deferrable, Not Deferrable, Initially Deferred, or Initially Immediate, using the keywords enclosed in parentheses. To change how a constraint is executed, you use the SET CONSTRAINTS command. With the CREATE TABLE or ALTER TABLE commands, the user can enable or disable the checking of the constraints for new changes of the table, or use the options validate/novalidate to force the integrity on existing data. With the MODIFY CONSTRAINT option of the ALTER TABLE command, you can change the following status of the constraints: deferrable, not deferrable, initially deferred, initially immediate,
167
Chapter 8—Data Integrity
rely/norely, using index, enable/disable, validate/not validate, and exceptions into. The next chapter shows in detail how to create and maintain tables, and the importance of using constraints.
168
Chapter 9
Creating and Maintaining Tables In the chapters about the SQL language, you learned how to perform some table operations, such as SELECT, INSERT, UPDATE, and DELETE. In the previous chapter you saw that during the design of a table’s structure, you can add constraints to enforce the data integrity. Before creating a table, you must analyze and define the database’s structure and functionality, following the seven steps of system development. The tables should be created only after the logical structure is ready. It is important to note that tables containing new types of objects cannot be imported by versions of Oracle previous to Oracle 8.
The CREATE TABLE Command The complete syntax of the CREATE TABLE command is included at the end of this chapter. However, below is a summary of the syntax. The CREATE TABLE command creates a new table through the following operations: 1. Definition of the columns 2. Definition of the table organization
169
Chapter 9—Creating and Maintaining Tables 3. Integrity constraints 4. Tablespace of the table 5. Storage characteristics 6. An optional cluster 7. Query data 8. Rate of parallelism used in the creation of the table, and default rate of parallelism for the queries of the table 9. Definition of partitions 10. Arrangement by index or heap (the storage area that allows random access)
Basic syntax: CREATE TABLE schema.table (column1 datatype DEFAULT expr column_constraint, ...columnX ) PCTFREE integer PCTUSED integer INITRANS integer MAXTRANS integer TABLESPACE tablespace STORAGE storage_clause ENABLE enable_clause DISABLE disable_clause AS subquery PARALLEL parallel_clause CACHE NOCACHE ( column datatype ) RECOVERABLE UNRECOVERABLE table_constraint
170
Creating and Maintaining Tables—Chapter 9
Arguments: schema An optional parameter that indicates the schema to which the table belongs. table The name of the table to be created. datatype Specifies the column’s data type. Up to 254 columns are allowed. DEFAULT This is optional, and indicates a default value for the column. CONSTRAINT This is optional and indicates some integrity control that applies to the column; for example, it must contain a value. TABLE CONSTRAINT This is optional and indicates some integrity control that applies to the table; for example, the primary key. PCTFREE This is optional and indicates the percentage of each data block that will be reserved for future updating in the table. The default value is 10. PCTUSED This is optional and indicates the minimum percentage of used space that Oracle must maintain before a data block is eligible for a row insertion. The default value is 40. INITRANS The default value is 1. It can vary from 1 to 255 and indicates the number of transactions assigned inside the data block of the table. MAXTRANS Indicates the maximum number of transactions that can update a data block.
171
Chapter 9—Creating and Maintaining Tables
TABLESPACE This is optional; it indicates a tablespace different from that used as default. CLUSTER This is optional; it indicates that the table is part of a cluster. ENABLE This is optional; it links the integrity restrictions. DISABLE This is optional; it disables the integrity restrictions. Before we start creating a simple table, let’s analyze the following table, based on the knowledge we have so far, and try to understand its structure: CREATE TABLE emp ( empno NUMBER(5) PRIMARY KEY, ename VARCHAR2(15) NOT NULL, job VARCHAR2(10), mgr NUMBER(5), hiredate DATE DEFAULT (sysdate), sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(3) NOT NULL CONSTRAINT dept_fkey REFERENCES dept) PCTFREE 10 PCTUSED 40 TABLESPACE users STORAGE ( INITIAL 50K NEXT 50K MAXEXTENTS 10 PCTINCREASE 25 );
This command creates a table called EMP in the Users tablespace. It initially allocates 50 Kbytes of space, and specifies 10% of free space and 40% of space that is used for the PCTUSED parameter. The Empno column is of type number with a size of 5, and is the 172
Creating and Maintaining Tables—Chapter 9
primary key of the table. The Ename column can contain data up to 15 characters and does not allow null values. The Hiredate column defaults to the system date if no value is specified. The Deptno column does not allow null values and has a FOREIGN KEY constraint, which references the DEPT table. Let’s create a simple table: SQL> create table newone 2 (firstcol number (4), 3 secondcol varchar (30), 4 thirdcol date ); Table created.
The structure of the table is: SQL> describe newone; Name Null? --------- ----FIRSTCOL SECONDCOL THIRDCOL
Type -----------NUMBER(4) VARCHAR2(30) DATE
SQL>
In the next example, the primary key (index), and some constraints are created: SQL> create table newagain 2 (first number(4) constraint pk_new primary key, 3 second date default sysdate, 4 third varchar(20) not null); Table created.
Now, let’s try to insert some records:
173
Chapter 9—Creating and Maintaining Tables SQL> insert into newagain values (1111,’10/10/1999’,’aaaa’); 1 row created.
Three values are assigned to the three columns. SQL> insert into newagain values (2222, ,’bbbb’); insert into newagain values (2222, ,’bbbb’) * ERROR on row 1: ORA-00936: missing expression
Because the second column has a default option, we’ve omitted the specification. This causes an error. When you don’t specify the names of the fields, all the fields must be given. The following shows the proper way to specify this information: SQL> insert into newagain values (2222,’ ‘,’bbbb’); 1 row created.
Here there is no error, since we assigned a blank value for the field. In addition, by specifying values only for the first and third columns, as shown below, no error resulted: SQL> insert into newagain (first,third) values (3333,’cccc’); 1 row created.
Let’s try to insert a null value in the third column. Note that the constraint blocked this action: SQL> insert into newagain values (4444,’12/12/1999’, null); insert into newagain values (4444,’12/12/1999’, null) * ERROR on row 1: ORA-01400: it is not possible to insert NULL in (“SCOTT”."NEWAGAIN"."THIRD") 174
Creating and Maintaining Tables—Chapter 9
Below is the result of the insertion. Note that the third row has the data value generated by sysdate, while the second row accepts the blank value that we specified: SQL> select * from newagain; FIRST ----1111 2222 3333
SECOND -------10/10/99 05/12/99
THIRD ----aaaa bbbb cccc
The following example creates a table identical to EMP. This will help us understand constraints. Be sure to specify a name for the constraint when you create it: CREATE TABLE scott.emp (empno NUMBER CONSTRAINT pk_emp PRIMARY KEY, ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULL CONSTRAINT upper_ename CHECK (ename = UPPER(ename)), job VARCHAR2(9), mgr NUMBER CONSTRAINT fk_mgr REFERENCES scott.emp(empno), hiredate DATE DEFAULT SYSDATE, sal NUMBER(10,2) CONSTRAINT ck_sal CHECK (sal > 500), comm NUMBER(9,0) DEFAULT NULL, deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL CONSTRAINT fk_deptno REFERENCES scott.dept (deptno) ) PCTFREE 5 PCTUSED 75;
175
Chapter 9—Creating and Maintaining Tables
To demonstrate the above example, we will create several tables. In the first example, we create a PRIMARY KEY constraint to avoid duplicate codes, and a CHECK constraint, which, in turn, checks to see if the contents of the field are all uppercase. SQL> create table testaconstr 2 (empno NUMBER CONSTRAINT pk_emp PRIMARY KEY, 3 ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULL 4 CONSTRAINT upper_ename 5 CHECK (ename = UPPER(ename)), 6 job VARCHAR2(9) )
Now we insert a row, where the Ename field is not uppercase: SQL> insert into testaconstr values (111, ‘Ramalho’,’Manager’); insert into testaconstr values (111, ‘Ramalho’,’Manager’) * ERROR on row 1: ORA-02290: checking constraint (SCOTT.UPPER_ENAME) violated SQL> insert into testaconstr values(111,’RAMALHO’, ’Manager’); 1 row created. SQL> select * from testaconstr; EMPNO ENAME ----- ------111 RAMALHO
176
JOB ------Manager
Creating and Maintaining Tables—Chapter 9
Now insert another record, containing the same code for the Empno field: SQL> insert into testaconstr values (111,’SILVA’,’CLERK’); insert into testaconstr values (111,’SILVA’,’CLERK’) * ERROR on row 1: ORA-00001: unique constraint (SCOTT.PK_EMP2) violated
The constraint prevents the incorrect registration: SQL> run 1 2 3 4 5 6 7 8* )
create table democonstr2 (empno NUMBER CONSTRAINT pk_emp3 PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER CONSTRAINT fk_mgr REFERENCES democonstr2(empno), hiredate DATE DEFAULT SYSDATE
Now let’s insert a row in which an employee is the manager of his department, and therefore his code appears in both the Empno and Mgr columns: SQL> insert into democonstr2 values (2222,’SAROUT’,’Designer’,2222,’12/05/1999’); 1 row created.
Let’s try to insert another record. In this example, the manager’s record has not been created yet: 1* insert into democonstr2 values (3333,’ARANTES’,Writer,1111,’12/05/1999’) insert into democonstr2 values (3333,’ARANTES’,Writer,1111,’12/05/1999’) *
177
Chapter 9—Creating and Maintaining Tables ERROR on row 1: ORA-02291: integrity constraint (SCOTT.FK_MGR) violated parent key not found
In this case, you first have to register the manager’s record, or assign the value NULL to it, an option that is accepted by the column constraint, as shown in the next example: SQL> insert into democonstr2 values (3333,’ARANTES’,Writer,null,’12/05/1999’) 1 row created. SQL> select * from democonstr2; EMPNO ----2222 3333
ENAME ------SAROUT ARANTES
JOB -------Designer Writer
MGR ---2222
HIREDATE -------12/05/99 12/05/99
And now our third example: create table democonstr3 (empno NUMBER CONSTRAINT pk_emp4 primary key, ename VARCHAR2(10), sal NUMBER(10,2) CONSTRAINT ck_sal CHECK (sal > 500), deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL CONSTRAINT fk_dep REFERENCES scott.dept(deptno) )
Let’s try to insert a record with a salary below $500. A constraint immediately interrupts the attempt: SQL> insert into democonstr3 values (333,’SCORMIN’,400,20); insert into democonstr3 values (333,’SCORMIN’,400,20) *
178
Creating and Maintaining Tables—Chapter 9 ERROR on row 1: ORA-02290: checking constraint (SCOTT.CK_SAL) violated
Now insert the correct record, changing the amount from $400 to $800, and executing the RUN command: SQL> c/400/800 1* insert into democonstr3 values (333,’SCORMIN’,800,20) SQL> run 1* insert into democonstr3 values (333,’SCORMIN’,800,20) 1 row created.
Now let’s try to insert a record with an incorrect department code: SQL> insert into democonstr3 values (444,’TEODOZIO’,1200,80) insert into democonstr3 values (444,’TEODOZIO’,1200,80) * ERROR on row 1: ORA-02291: integrity restriction (SCOTT.FK_DEP) violated parent key not found
Because of the constraint, the operation was voided.
Creating a Table with the Contents of Another Table Using the AS option, we can create a table with the SELECT command to recover the structure and data of another table. The next example creates a table called NEWEMP with all the columns of the EMP table and only the rows of department 20:
179
Chapter 9—Creating and Maintaining Tables SQL> create table newemp 2 as select * from emp 3 where deptno=20; Table created. SQL> select * from newemp; EMPNO ----7369 7566 7788 7876 7902
ENAME ----SMITH JONES SCOTT ADAMS FORD
JOB ------CLERK MANAGER ANALYST CLERK ANALYST
MGR ---7902 7839 7566 7788 7566
HIREDATE -------12/17/80 04/02/81 04/19/87 05/23/87 12/03/81
SAL ---800 2975 3000 1100 3000
COMM ----
DEPTNO -----20 20 20 20 20
Using the PARALLEL Option To create or read a table that uses all the parallel execution servers possible, use the PARALLEL option. Such a resource will depend on the computer where the query is executed. SQL> create table newemp2 2 parallel 3 as select * from emp; Table created.
Use parallelism in the creation of a table, since Oracle uses parallel execution servers to create a table. After the table is created, searches in the table are also faster, because the same parallelism rate is used to access it.
Constraint Disabling The following table is created with a primary key. However, it will remain disabled. This is an interesting resource, used when the
180
Creating and Maintaining Tables—Chapter 9
table is created from another table. The data is ready, and the creation of the table takes less time, since the checking is omitted: SQL> CREATE TABLE dept1 2 (deptno NUMBER (2) PRIMARY KEY DISABLE, 3 dname VARCHAR2(10), 4 loc VARCHAR2(9) );
However, this option will allow the creation of duplicate keys, as the next two commands show: SQL> insert into dept1 values(10,’aaaa’,’aaaa’); 1 row created. SQL> insert into dept1 values(10,’bbbb’,’bbbbb’); 1 row created.
Modifying Tables There are several reasons for making changes to tables. These include adding or removing columns and constraints; changing characteristics of columns, such as data type, size, and default value; changing storage parameters or the space used by data blocks; and removing or disabling triggers and constraints associated to the table.
Considerations and Limitations Not all the parameters of a table can be changed. A column can have its width increased or, if there are no rows in the table, it can be decreased. The INITIAL and MINEXTENTS parameters cannot be changed, while changes in the remaining storage parameters will only be effective after the allocation of new extents.
181
Chapter 9—Creating and Maintaining Tables
The ALTER TABLE Command The command responsible for modifying tables is ALTER TABLE. Its syntax is similar to the syntax of the CREATE TABLE command. The only difference is that you specify the parameter you want to change. Following are some examples. To change the space used by the data blocks, use the following: ALTER TABLE newemp PCTFREE 30 PCTUSED 60;
Using the PARALLEL Option A table created in the default serial mode can have its processing paralleled through the PARALLEL option: ALTER TABLE newemp PARALLEL;
Enabling a Constraint To enable a constraint that was disabled or created with the DISABLE option, use the ENABLE option. In the next example the primary key of the DEPT1 table is reactivated: SQL> ALTER TABLE DEPT1 2 ENABLE PRIMARY KEY; ALTER TABLE DEPT1 * ERROR on row 1: ORA-02437: it is not possible to validate (SCOTT.SYS_C001275
182
Creating and Maintaining Tables—Chapter 9
This error occurred because there are two rows with the same contents for the primary key, as shown below: SQL> SELECT * FROM DEPT1; DEPTNO -----10 10
DNAME ----aaaa bbbb
LOC ----aaaa bbbbb
After we delete the redundant row, we change the table again. Now we are successful: SQL> DELETE FROM DEPT1 WHERE DNAME=’aaaa’; 1 row deleted. SQL> ALTER TABLE DEPT1 2 ENABLE PRIMARY KEY; Table changed.
Changing a Column To change the characteristics of a column, you use the MODIFY option, and specify the characteristics for the column. The following example adds a NOT NULL constraint to the Sal column of the NEWEMP table: ALTER TABLE newemp MODIFY (sal NUMBER CONSTRAINT nn_sal NOT NULL);
After this modification, we can change the value to 0, but we cannot assign NULL to the column: SQL> update newemp 2 set sal=0 where empno=7369; 1 row updated.
183
Chapter 9—Creating and Maintaining Tables SQL> update newemp set sal=null where empno=7369; update newemp set sal=null where empno=7369 * ERROR on row 1: ORA-01407: it is not possible to update (“SCOTT”."NEWEMP"."SAL") to NULL.
When you change a column, be sure to respect the constraints of the table. Next, we will change the width of the State column to 4: ALTER TABLE dept1 MODIFY (state varchar(4));
To add a default value to a column: ALTER TABLE NEWEMP2 MODIFY (SAL DEFAULT 0), (COMM DEFAULT 0);
Adding Columns By using the ADD option, we can add new columns to the table. In the following example, we add a State column to the DEPT1 table: SQL> alter table dept1 2 add (state varchar(2)); Table changed. SQL> describe dept1;
184
Creating and Maintaining Tables—Chapter 9 Name -----DEPTNO DNAME LOC STATE
Null? ----NOT
Type -------------NULL NUMBER(2) VARCHAR2(10) VARCHAR2(9) VARCHAR2(2)
Eliminating a Column To eliminate a column, use the DROP option. In the next example, we will eliminate the Comm column from the NEWEMP2 table: SQL> ALTER TABLE NEWEMP2 2 SQL> select * from newemp2; EMPNO ----7369 7499 7521
ENAME ----SMITH ALLEN WARD
JOB -------CLERK SALESMAN SALESMAN
MGR ---7902 7698 7698
HIREDATE -------12/17/80 02/20/81 02/22/81
SAL ---800 1600 1250
COMM ---300 500
DEPTNO -----20 30 30
14 rows selected.
SQL> alter table newemp2 2 drop (comm); Table changed. SQL> select * from newemp2;
185
Chapter 9—Creating and Maintaining Tables EMPNO ----7369 7499
ENAME ----SMITH ALLEN
JOB -------CLERK SALESMAN
MGR ---7902 7698
HIREDATE -------12/17/80 02/20/81
SAL ---800 1600
DEPTNO -----20 30
It is not possible to delete an object type column, a key column in a partitioned key, or a column that is the PARENT KEY of another table. Also, you cannot delete a column from nested tables.
Deleting a Table To remove a table from a database, use the DROP TABLE command: Syntax: DROP TABLE schema.name_of_table
Example: SQL> drop table demo1; Table dropped.
If the deleted table has a primary or unique key referenced by the FOREIGN KEYs of other tables, and you want to delete a constraint of the other table, use the CASCADE CONSTRAINTS option: DROP TABLE table CASCADE CONSTRAINTS;
Index-Organized Tables Index-organized tables consist of a table with rows grouped in the same sequence as the primary key, i.e., physically the rows of the table are in the same order as the index entries. This type of table allows fast access to queries that involve the query of a specific 186
Creating and Maintaining Tables—Chapter 9
piece of data or a predetermined range of results. Updating this type of table reduces storage space, since it eliminates the duplication of key columns in the indexes and tables. This type of table is created with the CREATE TABLE command and the ORGANIZATION INDEX option, which indicates that the table will be index-organized. In this case, the primary key must be specified. You can also specify a ROW OVERFLOW option, which preserves the cluster of indexes through the storage of column values that exceed the space assigned in a separate extent. The Overflow tablespace is defined as a percentage of the block size. When the size of a row is greater than the value specified by the PCTTHRESHOLD parameter, the values of columns that are not a key are stored in the Overflow tablespace. The following example shows all the parameters for the creation of an index-organized table. Initially, we have created a tablespace called Test3a, using the CREATE TABLESPACE command: SQL> connect system/manager Connected. SQL> CREATE TABLESPACE test3a 2 DATAFILE ‘tabspace_file5.dbf’ SIZE 2M 3 MINIMUM EXTENT 64K 4 DEFAULT STORAGE (INITIAL 128K NEXT 128K) 5 LOGGING; Tablespace created.
Then, we create the index-organized table: SQL> CREATE TABLE test3 2 title char(20), 3 doc_id NUMBER, 4 value NUMBER, 5 comments VARCHAR2(512), 6 CONSTRAINT pk_docindex PRIMARY KEY (title, doc_id)) 7 ORGANIZATION INDEX TABLESPACE test3a 187
Chapter 9—Creating and Maintaining Tables 8 PCTTHRESHOLD 20 9 OVERFLOW TABLESPACE test3a; Table created.
In the example, the ORGANIZATION INDEX option indicates that the key and non-key columns are in an index defined by the columns that specify the primary key (title, doc_id).
CREATE TABLE Command Syntax Here is the complete syntax of the CREATE TABLE command: CREATE TABLE [schema.] table [({ column datatype [DEFAULT expr] [WITH ROWID] [SCOPE IS [schema.] scope_table_name] [column_constraint] ... | table_constraint | REF (ref_column_name) WITH ROWID | SCOPE FOR (ref_column_name) IS [schema.]scope_table_name} [, {column datatype [DEFAULT expr] [WITH ROWID] [SCOPE IS [schema.] scope_table_name] [column_constraint] ... | table_constraint | REF (ref_column_name) WITH ROWID | SCOPE FOR (ref_column_name) IS [schema.]scope_table_name} ] ...) ] [ {[ORGANIZATION {HEAP | INDEX} | PCTTHRESHOLD [INCLUDING column_name] [OVERFLOW [physical_attributes_clause | TABLESPACE tablespace] ...] | physical_attributes_clause | TABLESPACE tablespace | LOB (lob_item [, lob_item ...]) STORE AS [lob_segname] [( TABLESPACE tablespace | STORAGE storage_clause | CHUNK integer 188
Creating and Maintaining Tables—Chapter 9 | PCTVERSION integer | CACHE | NOCACHE LOGGING | NOCACHE NOLOGGING | INDEX [lob_index_name] [( TABLESPACE tablespace | STORAGE storage_clause | INITRANS integer | MAXTRANS integer ) ...])] | NESTED TABLE nested_item STORE AS storage_table | {LOGGING | NOLOGGING}] ... | CLUSTER cluster (column [, column] ...)}] [PARALLEL parallel_clause] [PARTITION BY RANGE (column_list) (PARTITION [partition_name] VALUES LESS THAN (value_list) [physical_attributes_clause | TABLESPACE tablespace | {LOGGING | NOLOGGING}] ... [ ENABLE enable_clause | DISABLE disable_clause] ... [AS subquery] [CACHE | NOCACHE] physical_attributes_clause ::= [ PCTFREE integer | PCTUSED integer | INITRANS integer | MAXTRANS integer | STORAGE storage_clause ]
Arguments: schema The schema that will contain the synonym. If the schema is omitted, Oracle creates a synonym in the user’s schema. table The name of the table (or object table) to be created. A partitioned table cannot be a clustered table or an object table.
189
Chapter 9—Creating and Maintaining Tables
OF object_type Explicitly creates an object_type table. Each row will contain an instance of the object, and each instance will be assigned to only one object identifier (OID), which is generated by the system when a row is inserted. column Specifies the column name of a table. A table can have up to 1,000 columns. You can only omit the column definitions when you use the AS clause. attribute Specifies the name of the qualified column in an object item. datatype This is the column’s data type. You can omit the data types only when the command also designates a column as part of a foreign key in a referential integrity constraint. Oracle automatically attributes to the column the data type of the column corresponding to the referenced key in the referential integrity constraint. The valid data types are: REF object_type, VARRAYs, and nested tables. DEFAULT Specifies a value to be attributed to the column when a subsequent INSERT command omits a value to it. The data type of the expression must be equal to the data type of the column. The column also must be large enough to accommodate the expression. column_ref_clause Allows the detailed specification of a REF column: WITH ROWID Stores the rowid and the REF value in the column or attribute. Storing a REF value with a rowid can improve the performance of the operations without referencial integrity, but also uses more space. The default storage of REF values is without rowids.
190
Creating and Maintaining Tables—Chapter 9
SCOPE IS scope_table_name Restricts the scope of the values of the REF column to scope_table_name. The REF values for the column must precede the REF values obtained in the object table specified in the clause. You can specify only one scope table for each REF column. scope_table_name The name of the object table in which the object instances (the same type as the REF column) are stored. The values of the REF column point to the objects in the scope table. You must have the SELECT privilege or the SELECT ANY TABLE system privilege on the table. column_constraint Defines an integrity constraint as part of the column definition. table_constraint Defines an integrity constraint as part of the table definition. table_ref_clause Defines an integrity constraint as part of the column definition. SCOPE FOR. . . IS Restricts the scope of values of the REF column in ref_column or ref_attribute to scope_table_name. The REF values for the column or attribute must come from the REF values obtained from the object table specified in the clause. ref_column or ref_attribute The name of the REF column of an object table, or a built-in attribute in an object column of a relational table. The values of the REF column point to the objects of the scope table.
191
Chapter 9—Creating and Maintaining Tables
REF The reference to a row in an object table. You can specify the name of a REF column of an object or relational table (ref_column), or a built-in REF attribute in an object column (ref_attribute). OIDINDEX Specifies an index in the column of the hidden object identifier and/or the specification of the storage for the index. Both the storage_specification and the index must be specified. index The name of the index in the hidden object identifier. When not specified, Oracle generates a name. physical_attributes_clause Specifies the values of the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters, and the storage characteristics of the table. PCTFREE Specifies the percentage of space in each data block of the table, object table OIDINDEX, or partition reserved for future updates in the rows of the table. The PCTFREE value must be a value between 0 and 99. A block is filled with inserts of new rows when the value is 0. The default value is 10, and reserves 10% of each block for the updates in the existing rows, allowing inserts of new rows to fill a maximum of 90% of each block. PCTFREE has the same function in the PARTITION clause, and in the commands that create and change clusters, indexes, snapshots, and snapshot logs. The combination of PCTFREE and PCTUSED determines whether new rows will be inserted in the existing data blocks or in new data blocks. PCTUSED Specifies the minimum percentage of used space that Oracle maintains for each data block in the table, object table OIDINDEX, or overflow data segment of the table organized by indexes. A block can have rows inserted when its physical 192
Creating and Maintaining Tables—Chapter 9
space is below PCTUSED. PCTUSED is specified as a positive integer between 1 and 99; its default value is 40. PCTUSED has the same function in the PARTITION clause, and in the commands that create and change clusters, indexes, snapshots, and snapshot logs. PCTUSED is not a valid table characteristic for index-organized tables (those with the ORGANIZATION INDEX option). The sum of PCTFREE and PCTUSED must be less than 100. You can use PCTFREE and PCTUSED together to better use the space of a table. INITRANS Specifies the initial number of transaction entries allocated to each block in the table, object table OIDINDEX, partition, index segment LOB, or data overflow segment. This number ranges from 1 to 255, and its default value is 1. Generally, the default value of INITRANS must not be changed. Each transaction that updates a block requires the entry of the transaction in the block. The size of an entry depends on the operating system you are using. This parameter guarantees that the minimum number of concurrent transactions updates the block, and helps minimize the cost of allocating a transaction entry. The INITRANS parameter has the same function in the PARTITION clause, and in the commands that create and change clusters, indexes, snapshots, and snapshot logs. The minimum value and default value for a cluster or index is 2, instead of 1. MAXTRANS Specifies the maximum number of concurrent transactions, which can be updated by a data block allocated to the table, object table OIDINDEX, partition, index segment LOB, or overflow data segments, organized by indexes. This limit does not apply to queries. It can vary from 1 to 255, and its default value is a function of the data block size. The default value of MAXTRANS should not be changed.
193
Chapter 9—Creating and Maintaining Tables
If the number of concurrent transactions that update a block exceeds the INITRANS value, Oracle dynamically allocates transaction entries in the block until the value of MAXTRANS is exceeded, or the block runs out of free space. MAXTRANS has the same function as the PARTITION clause, and in the commands that create and change clusters, indexes, snapshots, and snapshot logs. storage_clause Specifies the storage characteristics of the table, object table OIDINDEX, partition, storage LOB, index segment LOB, or overflow data segment in the table organized by indexes. This clause has performance ramifications in large tables. The storage should be allocated to minimize the allocation of the additional space. TABLESPACE Specifies the tablespace in which Oracle creates the table, object table OIDINDEX, partition, storage LOB, index segment LOB, or overflow data segment of the index-organized table. If this option is omitted, Oracle creates an item in the default tablespace of the owner of the schema in which the table is contained. For non-partitioned tables, the value specified for TABLESPACE is the real physical attribute of the segment associated to the table. For partitioned tables, the value specified for TABLESPACE is the default physical attribute of the segments associated to all the partitions specified in the CREATE command (and in the subsequent ALTER TABLE and ADD PARTITION commands), unless you specify TABLESPACE in the PARTITION clause. LOGGING/NOLOGGING Specifies the creation of the table (and any index needed due to the constraints), partition, or LOB storage characteristics that will be recorded in the log repetition file. Also specifies that the subsequent operations of DIRECT LOADER (SQL*), and direct load INSERT to the table, partition, or LOB storage are registered (LOGGING) or non-registered (NOLOGGING). If the LOGGING/NOLOGGING clause is omitted, the record
194
Creating and Maintaining Tables—Chapter 9
attribute or table partition assumes the default value of the record attribute of the tablespace in which it resides. If you omit the LOGGING/NOLOGGING clause for LOBs, LOGGING will be used when CACHE is specified (since you cannot have CACHE NOLOGGING). Otherwise, the record attribute assumes the default value of the record attribute of the tablespace in which it resides. For non-partitioned tables, the value specified for LOGGING is the real physical attribute of the segment associated to the table. For partitioned tables, the value specified is the default physical attribute of the segments associated to all the partitions specified in the CREATE command (and in subsequent ALTER TABLE and ADD PARTITION commands), unless you specify LOGGING/NOLOGGING in the PARTITION clause. In LOGGING mode, data is modified with the minimum log (to mark new invalid extensions and to write changes in the dictionary). When applied to media recovery, the invalid extension logs mark a range of blocks as logically corrupted, because repetitive data is not totally recorded. Therefore, if you cannot lose this table, make a backup after the operation. The size of a repetition log generated by an operation in NOLOGGING mode is significantly smaller than the log generated with the LOGGING option. If the database is executed in the ARCHIVELOG mode, the recovery of media from the backup made before the LOGGING operation restores the table. However, the recovery of media from the backup made after the NOLOGGING operation does not restore the table. The table log attribute is independent of its item attributes. NOLOGGING is not a valid argument for the creation of index-organized tables. ORGANIZATION INDEX Specifies that the table is created as an index-organized table. In an index-organized table, the rows of data are maintained in an index defined in the primary key of the table.
195
Chapter 9—Creating and Maintaining Tables
ORGANIZATION HEAP Specifies that the rows of data in the table are stored in no special order. This is the default value. index_organized_table_clause PCTTHRESHOLD integer Specifies the percentage of space reserved in the index block for a row in the index-organized table. Any part of the row exceeding the specified limit is stored in the area. PCTTHRESHOLD should be a value between 0 and 50. OVERFLOW Specifies that the rows of the index-organized table that exceed the specified limit are stored in the data segment defined in this clause. If OVERFLOW is not specified, the rows that exceed the limit of PCTTHRESHOLD are rejected. INCLUDING column_name Specifies a column where a row of the indexorganized table will be divided into the index and overflow parts. All the columns after column_name should be stored in the overflow data segment. column_name can be the name of the last column of the primary key, or any other column that is not the primary key. RECOVERABLE This option no longer exists. RECOVERABLE is not a valid argument for the creation of partitioned tables or tables with the LOB storage characteristics. UNRECOVERABLE This option no longer exists. It specifies that the creation of the table (and any index required due to constraints) will not be registered in the repetition log. This argument can only be specified with the AS subquery clause. UNRECOVERABLE is
196
Creating and Maintaining Tables—Chapter 9
not a valid argument for the creation of partitioned tables or index-organized tables. LOB_storage_clause LOB Specifies the LOB storage characteristics. lob_item The name of the LOB column or LOB object attribute to which you explicitly define the tablespace and the storage characteristics different from those of the table. STORE AS lob_segname Specifies the name of LOB data segments. You cannot use lob_segment if you specify more than one lob_item. lob_parameters ENABLE STORAGE IN ROW Specifies that the LOB value will be stored inline if its size is less than approximately 4,000 bytes, less the system control information. DISABLE STORAGE IN ROW Specifies that the LOB value will be stored offline regardless of its size. Note that the LOB locator is always stored in the row, regardless of where the LOB value is stored. CHUNK integer Specifies the number of bytes to be allocated for the manipulation of LOBs. If integer is not a multiple of the database’s block size, Oracle will round up (in bytes) to the next multiple. For example, if the database’s block size is 2,048 and the integer is 2,050, Oracle will allocate 4,096 bytes (two blocks). The maximum value is 32,768 (32 K). 197
Chapter 9—Creating and Maintaining Tables
PCTVERSION integer The maximum percentage of global space for the LOB, used to create new versions of LOB. The default value is 10, which means that older versions of LOB data won’t be overwritten until 10% of the global space of the LOB is used. INDEX lob_index_name The name of the LOB index segment. You cannot specify lob_index_name if you determine more than one lob_item in the associated list of lob_item. Note that you cannot change the LOB index using the ALTER INDEX command; this can only be done with the ALTER TABLE command. NESTED TABLE. . . STORE AS. . . Specifies storage_table as the name of the storage table, in which the rows of all the nested_item values reside. You should include this clause when creating a table with nested columns. Nested_item is the name of the column. storage_table The name of the storage table created in the same schema and same tablespace as its parent table. CLUSTER Specifies that the table will be part of the cluster. The columns listed in this clause are the table columns corresponding to the cluster columns. Generally, the cluster columns of a table are the columns or column that form its primary key or part of it. Specifies a column of the table for each column in the cluster key. The columns are compared by position, not by name. A clustered table uses the allocation of space of the cluster. However, do not use the PCTFREE, PCTUSED, INITRANS, or MAXTRANS parameters, the TABLESPACE option, or the STORAGE clause with the CLUSTER option. Object tables cannot be part of a cluster.
198
Creating and Maintaining Tables—Chapter 9
table_partitioning_clause PARTITION BY RANGE Specifies that the table will be partitioned at the value intervals of column_list. column_list An ordered list of columns used to determine to which partition a row belongs. You cannot specify more than 16 columns in column_list. A column_list cannot contain a pseudo-column rowid, or any other column with the rowid or long data types. PARTITION partition_name Specifies the physical partition clause. If partition_name is omitted, Oracle generates a name in the form of SYS_Pn for this partition. VALUES LESS THAN Specifies the upper limit non-inclusive of the current partition. value_list An ordered list of values corresponding to the column_list in the PARTITION BY RANGE clause. You can replace the MAXVALUE argument with any literal in value_list. MAXVALUE specifies a maximum value that will always sort higher than any other value, including NULL. The specification of a value for MAXVALUE other than the upper limit of the partition imposes an implicit integrity constraint on the table. parallel_clause Specifies the rates of parallelism for the creation of the table, and the default rate of parallelism for queries in the table already created. This is not a valid option for creating indexorganized tables.
199
Chapter 9—Creating and Maintaining Tables
enable_clause Enables an integrity constraint. disable_clause Disables an integrity constraint. The constraints specified in the ENABLE and DISABLE clauses of a CREATE TABLE command should be defined in the command. You can also enable or disable the constraints with the ENABLE and DISABLE arguments of the CONSTRAINT clause. If you define a constraint but do not enable or disable it explicitly, Oracle enables it by default. You cannot use the ENABLE and DISABLE clauses in a CREATE TABLE command to enable or disable the triggers. AS subquery Inserts the rows returned by the subquery of the table after its creation. The number of columns in the table must be equal to the number of expressions in the subquery. The column definitions can only specify names, default values, and integrity constraints, not data types. Oracle derives the data types and sizes from the subquery, and also follows these rules for integrity constraints:
: : :
200
Oracle automatically defines any NOT NULL constraint in the columns of the new table, which existed in those corresponding columns of the selected table, if the subquery specifies the column instead of an expression containing it. A CREATE TABLE command cannot contain an AS clause or the definition of a referential integrity constraint. If a CREATE TABLE command contains an AS clause and a CONSTRAINT clause, or an ENABLE clause with the EXCEPTIONS option, Oracle ignores the EXCEPTIONS option. If any row violates the constraint, Oracle will not create the table and returns an error message.
Creating and Maintaining Tables—Chapter 9
If all the expressions of the subquery are columns instead of expressions, you can omit the table definition columns. In this case, the names of the columns in the table will be the same as those in the subquery column. For object tables, the subquery can contain an expression corresponding to the type of table or the number of high-level attributes of the table type. CACHE Specifies that the most frequently accessed data blocks are put in the most recently used part of the RLU list of the buffer cache, when a complete scan of the table is done. This option is useful for small search tables. As a parameter of the LOB storage clause, CACHE specifies that Oracle preallocates and retains the values of LOB data in the memory for fast access. This is not a valid argument for the creation of indexorganized tables. NOCACHE For data that is not frequently accessed, specifies that the accessed blocks for this table are put in the less used part of the RLU list of the buffer cache, when a complete scan of the table is done. For LOBs, the value of LOB is put in the less used part of the RLU list and is not placed on the buffer cache. This is the default behavior. However, it is not a valid argument for the creation of index-organized tables. As a parameter of the LOB storage clause, NOCACHE specifies that the LOB values are not preallocated in the memory. This is the storage default LOB. This chapter discussed how to create and maintain tables in a database, including using constraints. The ALTER TABLE and CREATE TABLE commands were also presented. The next chapter looks at creating and using indexes.
201
Chapter 10
Indexes Oracle has two resources that provide quick access to and uniquely identify the rows of a table. In a previous chapter, you learned that a pseudo-column called rowid identifies each row in a database. Although the rowid adequately identifies a row inside a table, it is not convenient for applications that mostly use specific codes to access records, such as the employee code, product code, etc. To speed row access in a table, Oracle uses the concept of indexes. These are similar to indexes found in a book, where you can quickly find the pages containing a specific topic by locating the index, finding the topic, and turning to the desired page. In the case of Oracle, the index is an optional structure associated to tables and clusters that allows a faster execution of the SQL commands.
Figure 10.1:
An index speeds row access in a table.
203
Chapter 10—Indexes
Although they do speed up access to a table’s rows, indexes are not appropriate for all tables. Some situations must be considered before creating an index. The presence of data in a column generally indicates that an index must be created for it. However, columns that have many rows with null values are not good candidates for indexing. The same is true for those columns containing many identical values. Also, tables with a small number of rows should not be indexed. Columns that are used as primary keys, on the other hand, should be indexed. When creating a table through Navigator, the column that is indicated as having a primary key is automatically indexed. Those columns used as FOREIGN KEY also should be indexed. A table can contain an unlimited number of indexes, but the more indexes there are, the more effort will be needed for management and updating. This can result in a performance hit, particularly in the update or insert operations, where in addition to creating and writing a new row, the database also has to update all the indexes. An index can be created using the contents of one or more columns of the database. When more than one column is used, the index is called composite. When defining the index, the most important column should come first. Unlike other databases, in Oracle the indexing of a table does not cause any logical reorganization of the rows when they are queried. To display the contents of a table in a certain order, you use the ORDER BY clause of the SELECT command. Indexes can be unique or non-unique. Unique indexes do not allow two rows of a table to have the same value. As the default, when a primary key is created, Oracle creates it as a unique index. The SQL commands used to query or update the tables do not change with the existence of an index. They are independent of the table, and can be created or deleted without affecting the data. The indexes occupy additional disk space to store
204
Indexes—Chapter 10
information relating to the position of the rows of the table. All the changes made to a table automatically update the indexes that were created.
When to Create Indexes An index can be created during the design process of the table structure by using the PRIMARY KEY constraint. However, often it is better to create it later, particularly when the table has existing data that will be loaded with utilities. In this case, whenever a row is inserted, the indexes are updated, requiring more processing time. On the other hand, creating an index and then creating a table and filling it with data will require extra space for the organization of the indexes. Columns of type lobs, long, and long raw cannot be indexed.
Creating Indexes There are several ways to create indexes. The following discussion gives details on each.
Creating Indexes with Constraints When creating a constraint using UNIQUE or PRIMARY KEY, Oracle automatically creates an index if the constraint is enabled. No other command is necessary to create the index. Through the PRIMARY KEY or UNIQUE constraint it is possible to create an index if the ENABLE and USING INDEX options are used, as in the following example: CREATE TABLE emp ( empno NUMBER(5) PRIMARY KEY, . . . ) ENABLE PRIMARY KEY USING INDEX
205
Chapter 10—Indexes TABLESPACE users PCTFREE 0;
If you do not specify one of the storage options for the index, the alternatives used for the tablespace will be enabled.
Creating Indexes with the CREATE INDEX Command The CREATE INDEX command is responsible for the creation of simple indexes using a unique column, or composite indexes using more than one column. Basic syntax: CREATE [UNIQUE] INDEX name ON schema.table ( name_of_column ASC/DESC ,...) CLUSTER schema.cluster INITRANS integer MAXTRANS integer TABLESPACE tablespace STORAGE storage_clause PCTFREE integer NOSORT RECOVERABLE UNRECOVERABLE
Arguments: CLUSTER Indicates that the name of the key is indexed to a cluster. TABLESPACE Indicates the name of the tablespace for the creation of the index. Using a different tablespace for the index improves the performance, since there will be fewer disk access conflicts.
206
Indexes—Chapter 10
PCTFREE When an index is created, Oracle reserves disk space for the data blocks that are filled with their keys. PCTFREE indicates the space that should be left free and unused by the indexes. INITRANS and MAXTRANS Indicate the initial value and maximum space allocated for the transactions of the data blocks in the indexed segment. STORAGE Specifies the parameters stored by the index. Now we will use some commands to create and handle an index. First, we will check the contents and the order of the rows of the DEPARTMENT table of user Demo. To do that, we must be connected as this user: SQL> CONNECT DEMO/DEMO Connected.
After the connection, we will take a look at this user’s tables: SQL> SELECT TABLE_NAME FROM USER_TABLES; TABLE_NAME -----------CUSTOMER DEPARTMENT EMPLOYEE ITEM JOB LOCATION PRICE PRODUCT SALARY_GRADE SALES_ORDER
207
Chapter 10—Indexes
Now we will take a close look at the DEPARTMENT table: SQL> select * from department 2 / DEPARTMENT_ID ------------10 20 30 40 12 13 14 23 24 34 43
NAME ---------ACCOUNTING RESEARCH SALES OPERATIONS RESEARCH SALES OPERATIONS SALES OPERATIONS OPERATIONS SALES
LOCATION_ID ----------122 124 123 167 122 122 122 124 124 123 167
Let’s create an index called Depname based on the Name column of the DEPARTMENT table. SQL> create index depname on department (name); Index created.
After creating the index, a new query to the table will not show a physical order. However, the new index will be updated with each inclusion or change made to the database. You cannot create an index that uses only one column if it was already used by another index. However, you can create a composite index that includes a column that was already used by another index. Consider the next example: SQL> create index indname on department (name); create index indname on department (name) *
208
Indexes—Chapter 10 ERROR on row 1: ORA-01408: this list of columns is already indexed
Notice that you can use the Name column in the creation of a composite index, even though you have already used that column in a previous index: SQL> create index nameloc on department (name,location_id); Index created.
Note that the existence of these indexes does not change the execution of other SQL commands related to the table. Here is another example, where specific storage spaces are allocated for the index. First, we will connect as user Scott: SQL> connect scott/tiger Connected. SQL> SQL> SQL> CREATE INDEX ind_ename ON newemp2(ename) 2 TABLESPACE users 3 STORAGE (INITIAL 20K 4 NEXT 20k 5 PCTINCREASE 75) 6 PCTFREE 0; Index created.
Creating a Function-Based Index Function-based indexes improve the queries that use a value returned by a function or expression, since they store this value by expression/function of the index itself.
209
Chapter 10—Indexes
One advantage of using this type of index is the ability to include sorts based on keys containing words with accents, or disregarding the size of the letter in the field. For example, when a database’s contents include words in a language with accents, the use of national language support (NLS) helps to create a properly sorted index through the NLSSORT function. The next example shows the creation of an index with all the names converted to uppercase, using the UPPER function: CREATE INDEX x1 ON newemp2 (UPPER(ename));
Even when there are names in lowercase or combining lowercase and uppercase, the following SELECT command returns data from all the entries that include “Smith”: SELECT * FROM newemp2 WHERE UPPER(ename) = ‘SMITH’;
Now we will create an index based on the German language. It does not apply to the example tables we are using: CREATE INDEX nls_index ON t_table (NLSSORT(name, ‘NLS_SORT = German’));
Creating an Index Using Key Compression Oracle allows the creation of an index using key compression, a technique that helps to eliminate the duplicated values of a key column. Key compression breaks the key into two parts: a prefix and a suffix. Once created, the prefix is shared by all the entries of an index block. For example, if a Name field contains 1,000 records of people whose names start with “Maria,” the index creates the prefix maria, which is shared by all 1,000 records. Besides saving space and improving performance, the use of compressed indexes is indicated when you have indexes formed by several columns.
210
Indexes—Chapter 10
To create a compressed index, just add the COMPRESS clause, as shown in the following example: CREATE INDEX emp_test (ename) COMPRESS 1
Key compression can be disabled with the ALTER INDEX command and the NOCOMPRESS clause: ALTER INDEX emp_ename REBUILD NOCOMPRESS;
Changing an Index Changing an index is restricted to modifying the transaction and storage parameters. It is not possible to change the columns in the index. In this situation, the index must be deleted and re-created with a new definition. You can change the parameters of any index, including those created by Oracle for the PRIMARY KEY and UNIQUE KEY constraints, by using the ALTER INDEX command. The following command changes the index: SQL> alter 2 3 4
index pk_emp3 INITRANS 5 MAXTRANS 10 STORAGE (PCTINCREASE 50);
When you change the transactions inserted in the INITRANS and MAXTRANS parameters of an index, the new INITRANS parameter applies just to the data blocks allocated, while the new MAXTRANS parameter applies to all the blocks (current or subsequent) of an index. The storage of the INITIAL and MINEXTENTS parameters cannot be changed. All the new parameters for the storage of other parameters affect only the extents allocated to the index. 211
Chapter 10—Indexes
Re-creating an Index An index can be re-created by using the ALTER INDEX command. This operation is the equivalent of deleting and reconstructing the index, with the advantage of reorganizing the fragmentation of a block and providing better performance. To re-create an existing index, use the following format: ALTER INDEX index_name REBUILD;
The REBUILD option should be specified right after the name of the index when the ALTER INDEX command includes other options. During the creation of an index, Oracle applies an access block to the DML commands. However, you can re-create the index online, i.e., without applying a block to the table. This operation is necessary in systems that are constantly running. For this type of reconstruction, you must add the ONLINE option to the ALTER INDEX or CREATE INDEX command: SQL> CREATE INDEX indname ON dept1 (dname,loc) ONLINE; Index created. SQL> alter index indname rebuild online; Index changed.
Obtaining Information about Indexes With the USER_INDEXES view of the data dictionary, we can obtain information about the index of each user. See Figure 10.2.
212
Indexes—Chapter 10
Figure 10.2: Obtaining information about a user’s indexes.
Following is a query to this table, where the indexes we have just changed appear (pk_emp3): SQL> select index_name, table_name, uniqueness, ini_trans, max_trans from user_indexes; INDEX_NAME ----------INDNAME IND_ENAME PK_DEPT PK_EMP PK_EMP2 PK_EMP3 PK_EMP4 PK_NEWA SYS_C001275
TABLE_NAME ----------DEPT1 NEWEMP2 DEPT EMP TESTACONSTR DEMOCONSTR2 DEMOCONSTR3 NEWAGAIN DEPT1
UNIQUENESS ---------NONUNIQUE NONUNIQUE UNIQUE UNIQUE UNIQUE UNIQUE UNIQUE UNIQUE UNIQUE
INI_TRANS --------2 2 2 2 2 5 2 2 2
MAX_TRANS --------255 255 255 255 255 10 255 255 255
213
Chapter 10—Indexes
Eliminating an Index An index should be kept active only when it is being used effectively. Keeping an index that is not used frequently reduces the performance of the system and occupies unnecessary disk space. Simply creating an index for a column does not mean that there will be production gains, since the performance is affected by several factors. If you test and see that there are no performance gains with an index, simply remove it. From time to time, an index can become fragmented. In this case, we recommend that you delete and re-create it. The SQL command responsible for the elimination of an index is DROP INDEX. Syntax: DROP INDEX name
Example: DROP INDEX depemp
To eliminate an index, it must belong to your schema. It is not possible to exclude only the index associated to a UNIQUE KEY or PRIMARY KEY constraint. In this case, you must eliminate or disable the constraint itself: SQL> drop index pk_emp2; drop index pk_emp2 * ERROR on row 1: ORA-02429: it is not possible to eliminate the index used to create the unique/primary key SQL> drop index indname; Index deleted.
214
Indexes—Chapter 10
This chapter covered the creation and use of indexes. In the next chapter, we will discuss sequences, which are closely related to the use of indexes.
215
Chapter 11
Sequences Sequences help to ease the process of creating unique identifiers for a record in a database. A sequence is simply an automatic counter, which is enabled whenever it is accessed. The number generated by it can be used to update a column containing, for example, a product code or employee code. This guarantees that there are no two rows with the same code. When a sequence is created, it adopts some default values that are adequate for most situations. A default sequence has the following characteristics:
: : :
Always starts from the number 1. In ascending order. Increases by 1.
The CREATE SEQUENCE Command The SQL command used to create a sequence is the CREATE SEQUENCE command. Syntax: CREATE SEQUENCE name START WITH integer INCREMENT BY integer MINVALUE integer
217
Chapter 11—Sequences NOMINVALUE MAXVALUE integer NOMAXVALUE CYCLE NOCYCLE CACHE integer NOCACHE sequence ORDER NOORDER
Arguments: START WITH Indicates the initial value of the sequence. When used for the first time, it returns the value specified by this clause. INCREMENT BY Indicates the value by which the sequence will be incremented each time it is accessed. MAXVALUE Indicates the maximum value that the sequence may have. When omitted, the maximum value of the sequence can be 1.00e +27, or 10 to the power of 27. NOMAXVALUE Indicates that the sequence doesn’t have a predefined maximum value. CACHE Indicates the number of sequences that should be created directly in the cache memory. In a situation where there is a lot of access to the sequences, the higher the value specified, the less access to disk will occur. CYCLE/NOCYCLE CYCLE indicates that the sequence should return to the initial value when the maximum value is reached. NOCYCLE, in turn, prevents it from returning to the beginning.
218
Sequences—Chapter 11
Once a sequence number is used, it is available only to the session in which it was created. Thus, many users can use the sequence without the risk of obtaining a number that is being used by another session.
Pseudo-Columns Oracle has several pseudo-columns that behave as an extra column when a new table is created. We have seen one type of pseudo-column called rowid. In addition, the currval and nextval pseudo-columns are directly related to sequences. There are two additional pseudo-columns:
: :
level rownum
currval and nextval You’ve seen that a sequence is a schema object that generates a unique sequence number. These values normally are used as primary keys in tables. To access them you have to work with the contents of the two pseudo-columns:
: :
currval
Returns the current value of the sequence.
nextval
Increases the value of the sequence and returns the next value.
These two pseudo-columns need to be associated with the name of a sequence, as follows: NameOfSequence.CURRVAL NameOfSequence.NEXTVAL If it is in a remote server, you must specify the complete path for the database: Schema.sequence.CURRVAL@dblink Schema.sequence.NEXTVAL@dblink 219
Chapter 11—Sequences
Those two pseudo-columns can be used in the following situations:
: : :
In an INSERT command with the value of the VALUES clause. In the SET clause of the UPDATE command. In the list of columns of the SELECT command. In this case, the pseudo-columns cannot be used if the command has the ORDER BY, GROUP BY, DISTINCT, or SUBQUERY clauses.
The first time the nextval pseudo-column is accessed, it returns the initial value of the sequence. The next time it is accessed, its value is increased by the increment specified, and a new value is returned. The references made to currval always return the current value without changing its status.
rowid In previous chapters we’ve seen that a pseudo-column called rowid is created for each row of a table. According to its definition, this is another way to individualize each row of a table. The values of this column have the rowid or urowid data type. Although its code is more complex, rowid offers a faster and more practical way to access a row in the entire database. Here is the rowid code for the employees of department 30: SQL> SELECT ROWID, ename 2 FROM emp 3 WHERE deptno = 30; ROWID -----------------AAACqqAACAAAAEHAAB AAACqqAACAAAAEHAAC AAACqqAACAAAAEHAAE
220
ENAME -----ALLEN WARD MARTIN
Sequences—Chapter 11 AAACqqAACAAAAEHAAF AAACqqAACAAAAEHAAJ AAACqqAACAAAAEHAAL
BLAKE TURNER JAMES
rownum The rownum pseudo-column receives a number that corresponds to the position of a row in the set of rows returned by a query. The first column returned receives the number 1, the second column receives the number 2, and so on. Use rownum when you need to list just the initial rows and a query: SQL> SELECT * 2 FROM emp 3 WHERE ROWNUM < 9; EMPNO ----7369 7499 7521 7566 7654 7698 7782 7788
ENAME -----SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT
JOB -------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST
MGR ---7902 7698 7698 7839 7698 7839 7839 7566
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81 05/01/81 06/09/81 04/19/87
SAL ---800 1600 1250 2975 1250 2850 2450 3000
COMM ---300 500 1400
DEPTNO -----20 30 30 20 30 30 10 20
You cannot use the “greater than” operator (>), such as in the following example, to list just the rows after the 10th row. SQL> SELECT * 2 FROM emp 3 WHERE ROWNUM >10;
221
Chapter 11—Sequences
The “greater than” operator will return false; use the “less than” operator (<) instead.
Creating a Sequence A sequence is available only for the schema that has created it. All the sequences created in these examples are made under user Scott. The next example illustrates the creation of the Newseq sequence using the default values: SQL> create sequence newseq;
Checking a User’s List of Sequences To check the sequences that were created for a user and the values of their parameters, you use a table called USER_SEQUENCES. It displays the sequences of the current user: SQL> select * SEQUENCE_NAME ------------NEWSEQ
from user_sequences; MIN_VALUE MAX_VALUE INCREMENT_BY --------- --------- -----------1 1.000E+27 1
C N
O N
CACHE_SIZE ---------20
LAST_NUMBER ----------1
Note in this example that the minimum value is 1, the maximum value is virtually infinite, the sequence is increased by 1, and the last number is 1, since it has not been used yet. Next, let’s create a sequence with an initial value, an increment value, and the size of the cache specified by the current user: SQL> create sequence newseq2 start with 500 increment by 25 cache 30;
222
Sequences—Chapter 11 SQL> select * from user_sequences; SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY
C
O
CACHE_SIZE
LAST_NUMBER
------------- --------- --------- -----------NEWSEQ 1 1.000E+27 1 NEWSEQ2 1 1.000E+27 25
N N
N N
---------20 30
----------1 500
Note that the specification of START WITH updates the last_number column; in other words, beginning with this number the counter is incremented by the value 25 each time it is accessed. In this next example, the sequence is created with minimum and maximum values: SQL> create sequence newseq3 2 minvalue 1000 3 maxvalue 4000; Sequence created: SQL> select * from user_sequences; SEQUENCE_NAME ------------NEWSEQ NEWSEQ2 NEWSEQ3
MIN_VALUE --------1 1 1000
MAX_VALUE --------1,000E+27 1,000E+27 4000
INCREMENT_BY -----------1 25 1
C N N N
O N N N
CACHE_SIZE ---------20 30 20
LAST_NUMBER ----------1 500 1000
Deleting a Sequence The DROP SEQUENCE command removes the sequence from the schema in which it was created. In this example, Newseq2 is removed: SQL> drop sequence newseq2;
223
Chapter 11—Sequences
Changing a Sequence With the ALTER SEQUENCE command the user can change some of the sequence’s parameters. However, there are several restrictions. You are not allowed, for example, to change its initial value: SQL> alter initial sequence with newseq com 50; alter initial sequence newseq with 50 * ERROR on row 1: ORA-02283: it is not possible to alter the initial number of the sequence.
The minimum value for the table cannot be greater than the current value. Let’s re-create the Newseq2 sequence, and then try to change it: SQL> create initial sequence newseq2 with the value 500 incremented by 25 cache 30; Sequence created. SQL> alter sequence newseq2 with minimum value of 888; alter sequence newseq2 minvalue 888 * ERROR on row 1: ORA-04007: MINVALUE cannot be created to exceed the current value.
The increment value can be changed without any problems. In the next example, two successful changes were made to the Newseq2 sequence: SQL> alter the sequence newseq2 2 minvalue 30 3 increment by 20; Sequence altered.
224
Sequences—Chapter 11
SQL> select * from user_sequences; SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY
C
O
CACHE_SIZE LAST_NUMBER
------------- --------- --------- -----------NEWSEQ 1 1,000E+27 1 NEWSEQ2 30 1,000E+27 20
N N
N N
---------- ----------20 1 30 495
NEWSEQ3
N
N
20
1000
4000
1
1000
Using a Sequence The sequence is enabled the first time it is used, and displays its initial value: SQL> select newseq3.nextval from dual; NEXTVAL ------1000 SQL> run NEXTVAL ------1001
The second time it is used, it displays the value incremented by 1. Note the next two examples, where the access to currval does not change the value of the sequence: SQL> select newseq3.currval from dual; CURRVAL ------1001 SQL> run CURRVAL ------1001
225
Chapter 11—Sequences
Note that after using more than one value in the sequence, a query to the list of sequences displays the contents of last_number as 1020. This is due to the fact that 20 numbers were generated in the memory cache. SQL> select newseq3.nextval from dual; NEXTVAL ------1002 SQL> select * from user_sequences; SEQUENCE_NAME ------------NEWSEQ2 NEWSEQ3
MIN_VALUE --------30 1000
MAX_VALUE --------1.000E+27 4000
INCREMENT_BY -----------20 1
C N N
O N N
CACHE_SIZE ---------30 20
LAST_NUMBER ----------520 1020
After we execute the display of nextval 22 times, the contents of last_number is 1040, indicating that the next 20 numbers are in the cache. SQL> / NEXTVAL ------1022 SQL> select * SEQUENCE_NAME ------------NEWSEQ2 NEWSEQ3
from user_sequences; MIN_VALUE MAX_VALUE --------- --------30 1.000E+27 1000 4000
INCREMENT_BY -----------20 1
C N N
O N N
CACHE_SIZE ---------30 20
LAST_NUMBER ----------520 1040
Now that you’ve seen how sequences work, let’s take a look at a practical example. To do that, we need to insert some records in the EMP table using the Newseq3 sequence to create the employee code.
226
Sequences—Chapter 11
Initially, we check the current value of newseq3: SQL> SELECT NEWSEQ3.CURRVAL FROM DUAL; CURRVAL ------1022
Now we include a record, and then we repeat its inclusion: SQL> INSERT INTO EMP 2 VALUES (NEWSEQ3.NEXTVAL,’RAMALHO’,’CLERK’,2222,’JAN-10-93’, 3000,NULL,20); 1 row created. SQL> run 1 INSERT INTO EMP 2* VALUES (NEWSEQ3.NEXTVAL,’RAMALHO’,’CLERK’,2222,’JAN-10-93’, 3000,NULL,20) 1 row created.
Now that two rows have been inserted, we will check the Empno column: SQL> SELECT * FROM EMP WHERE DEPTNO=20; EMPNO ENAME JOB MGR HIREDATE ----- ------- ------- ---- -------7369 SMITH CLERK 7902 12/17/80 7566 JONES MANAGER 7839 04/02/81 7788 SCOTT ANALYST 7566 04/19/87 7876 ADAMS CLERK 7788 05/23/87 7902 FORD ANALYST 7566 12/03/81 1023 RAMALHO CLERK 2222 01/10/93 1024 RAMALHO CLERK 2222 01/10/93
SAL ---800 2975 3000 1100 3000 3000 3000
COMM ----
DEPTNO -----20 20 20 20 20 20 20
227
Chapter 11—Sequences
Observe the last two rows and note that new rows were inserted. The Empno codes that were generated are 1023 and 1024, respectively. A sequence is not necessarily associated to a particular table. Other tables can use it. Note that the Newseq3 sequence is used to include a row in the NEWONE table below. First we will insert two rows and examine the contents of this table: SQL> insert into newone values (0001, ‘Hammer’, ‘05/11/99’); 1 row created. SQL> insert into newone values (0002, ‘Screwdriver’, sysdate); 1 row created. SQL> select * from newone; FIRSTCOL SECONDCOL ---------------1 Hammer 2 Screwdriver
THIRDCOL -------05/11/99 05/15/99
Now we include a new row, using the Newseq3 sequence: SQL> insert into newone values (newseq3.nextval, ‘Drill’, ‘05/13/1999’); 1 row created. SQL> select * from newone; FIRSTCOL SECONDCOL THIRDCOL -------- ---------------1 Hammer 05/11/99 2 Screwdriver 05/15/99 1026 Drill 05/13/99
228
Sequences—Chapter 11
Obviously, the collective use of a sequence by many tables will depend on the logic of your application. This chapter showed the utility of sequences, one of the ways in which Oracle individualizes a row. In the next chapter you will learn about the view, which is another database object that is important for the manipulation of tables.
229
Chapter 12
Views A view is a virtual or logical table that allows the viewing or manipulating of the contents of one or more tables in a window. A view looks like and works similarly to a normal table, except that its contents can be drawn from several different tables or even other views. The tables containing the origin columns are called base tables. A view reflects the current contents of the base table, and is different from a snapshot, which displays only past data.
Base Table
View
EMP EMPNO
ENAME
JOB
MGR
7329 7499 7521 7566
SMITH ALLEN WARD JONES
CLERK SALESMAN SALESMAN MANAGER
7902 7698 7698 7839
17-DEC-88 20-FEB-88 22-FEB-88 02-APR-88
EMPNO
ENAME
JOB
MGR
DEPTNO
7329 7499 7521 7566
SMITH ALLEN WARD JONES
CLERK SALESMAN SALESMAN MANAGER
7902 7698 7698 7839
20 30 30 20
HIREDATE
SAL
COMM
DEPTNO
300.00 300.00 5.00
800.00 1600.00 1250.00 2975.00
20 30 30 20
STAFF
Figure 12.1:
A view’s contents are derived from a base table.
231
Chapter 12—Views
A view, unlike a table, has no physical space allocated to its data. It is created by a query that uses origin or base tables from which to extract data. The base tables can be tables or views. The definition of a view is stored in the data dictionary, which stores the query that generated the table.
How a View Works The definition of a table is stored in the dictionary as text, and contains the SQL commands used in the creation of the view. When a view is referenced by a SQL command, Oracle combines this command with that of the view’s definition, and returns the data. Oracle controls the dependencies of a view. When a table is deleted or changed by the view, Oracle determines when a new table will be available for use in the view’s definition.
Advantages of Using a View One major advantage of views is that they can restrict the viewing of a table’s contents by limiting the columns that are displayed and the rows that are filtered. The same view can be used by different users and display distinct information, depending on the way it was designed. A table for general use can be divided into specific views for certain users. For example, a table with employee data can display just the name and phone number for general users, and can include the salary for those users who have the proper permission to see it, such as the human resources department. Another advantage is that the execution of the SELECT command is simplified, which otherwise would involve a great number of fields in many tables, and would require the specification of a schema in every column. In addition, the names of columns can be changed, thus masking their origin and giving the user the 232
Views—Chapter 12
opportunity to provide a name that is more descriptive or easier to remember. A view can be referenced in the following SQL commands:
: : : : : :
COMMENT DELETE INSERT LOCK TABLE UPDATE SELECT
Restrictions on Using a View Insert, update, and delete operations cannot be performed in a view formed by columns from more than one table when there is a grouping function, a GROUP BY clause, or restriction operators. Also, views cannot mention the nextval or currval pseudocolumns. A row cannot be inserted in a view that has a base table containing a column with the NOT NULL restriction, and that has a default value specified. When the view selects the rowid, rownum, or level pseudo-columns, their alias must be specified in the query.
Properties and Privileges of a View A view is simply the execution of a SELECT command that uses the columns and restrictions specified in the design window. To see the SQL command responsible for the view’s design, you must open the view’s property window by clicking with the right mouse button on the view’s name and selecting the Properties option.
233
Chapter 12—Views
Creating a View The command responsible for creating and modifying views is CREATE VIEW. Syntax: CREATE [OR REPLACE] VIEW name AS SELECT field(s) FROM table(s) FORCE/NOFORCE WHERE condition WITH CHECK OPTION CONSTRAINT control WITH READ ONLY
OR REPLACE Re-creates an existing view. It functions as an alternative to ALTER VIEW (which does not exist in Oracle), and is used to change an existing view without having to drop and grant privileges. FORCE Allows the creation of a view even when the base table does not exist, and the user doesn’t have the privileges to create it. However, for the view to be used later, these situations must be resolved. NOFORCE Allows the creation of the view only when the user has the permissions and the specified tables exist. The default is NOFORCE. WITH READ ONLY Specifies that the INSERT, UPDATE, or DELETE commands cannot be executed in the view. WITH CHECK OPTION Allows the inclusion and update only of the rows that the view can select.
234
Views—Chapter 12
CONSTRAINT The name attributed to the restriction of the CHECK OPTION clause. If the view has been created with GROUP BY, CONNECT BY, or START WITH, or by the DISTINCT operator or group functions, the INSERT, UPDATE, and DELETE commands cannot be executed in the view.
A View Based on a Table The next examples were created with tables from user Demo. If you want to follow along, you must connect as user DEMO with the password DEMO in SQL*Plus. Let’s create two views based on data from a single table. A view can be created with all the columns of a table by using * to replace the names of the columns, as shown below: SQL> CREATE VIEW NEWDEP AS SELECT * FROM DEPARTMENT; View created. SQL> SELECT * DEPARTMENT_ID ------------10 20 30 40 12 13 14 23 24 34 43
FROM NEWDEP; NAME ---------ACCOUNTING RESEARCH SALES OPERATIONS RESEARCH SALES OPERATIONS SALES OPERATIONS OPERATIONS SALES
LOCATION_ID ----------122 124 123 167 122 122 122 124 124 123 167
235
Chapter 12—Views
The next example creates a view with specific columns from the EMPLOYEE table: SQL> create view empbasic as 2 select employee_id, last_name,first_name, salary from employee;
Here’s a partial list of the view’s contents: SQL> select EMPLOYEE_ID ----------7369 7499 7505 7506
* from empbasic where rownum <5; LAST_NAME FIRST_NAME SALARY ----------------------SMITH JOHN 800 ALLEN KEVIN 1600 DOYLE JEAN 2850 DENNIS LYNN 2750
A View Based on Two Tables (Join View) Next is an example of the creation of a view linking the DEPARTMENT and LOCATION tables. Let’s examine the contents of each of them: SQL> SQL> select LOCATION_ID ----------122 124 123 167
236
* from location; REGIONAL_GROUP -------------NEW YORK DALLAS CHICAGO BOSTON
Views—Chapter 12 SQL> select * DEPARTMENT_ID ------------10 20 30 40 12 13 14 23 24 34 43
from department; NAME LOCATION_ID -------------------ACCOUNTING 122 RESEARCH 124 SALES 123 OPERATIONS 167 RESEARCH 122 SALES 122 OPERATIONS 122 SALES 124 OPERATIONS 124 OPERATIONS 123 SALES 167
Now we are going to create a view using columns from both tables. Since there are two tables, you need to specify the name of each table before the name of the column, as shown below: SQL> create view gendep as 2 select department.name, department.location_id, 3 location.regional_group 4 from department,location 5 where department.location_id = location. location_id;
Note that the WHERE clause was used; it displays the records from both tables that contain the same value in the location_id field. Only 11 records corresponding to the 11 rows of the DEPARTMENT table are displayed, along with the regional_group field of the LOCATION table of the row with same location_id. Without the WHERE clause, a view with incorrect records would be created. Each record of the DEPARTMENT table would be listed five times, once for each different code in the location_id field.
237
Chapter 12—Views SQL> select NAME ---------ACCOUNTING RESEARCH SALES OPERATIONS RESEARCH SALES OPERATIONS SALES OPERATIONS OPERATIONS SALES
* from gendep; LOCATION_ID ----------122 124 123 167 122 122 122 124 124 123 167
REGIONAL_GROUP -------------NEW YORK DALLAS CHICAGO BOSTON NEW YORK NEW YORK NEW YORK DALLAS DALLAS CHICAGO BOSTON
Instead of using the name of the table with the name of the column, we can create an alias for it, thus reducing the size of the command. To do that, use the desired alias, preferably with just one letter to minimize typing, and specify this alias in the FROM clause after the name of the department, as shown in the following example: SQL> create view funcdep as 2 select e.employee_id, e.last_name, e.first_name,e.salary, 3 d.department_id, d.name from employee e, department d 4 where e.department_id=d.department_id
238
Views—Chapter 12
Here’s a partial list of the result: SQL> select * from funcdep order by name; EMPLOYEE_ID LAST_NAME FIRST_NAME SALARY DEPARTMENT_ID ----------- --------- ---------- ------ ------------7782 CLARKY CAROL 2450 10 7839 KING FRANCIS 5000 10 7934 MILLER BARBARA 1300 10 7507 BAKER LESLIE 2200 14 7609 LEWIS RICHARD 1800 24 7676 SOMMERS DENISE 1850 34
NAME ---------ACCOUNTING ACCOUNTING ACCOUNTING OPERATIONS OPERATIONS OPERATIONS
Using the SELECT Command in a View A view functions as a normal table for most operations. The SELECT command also works the same in a view. The next example shows a query that uses the WHERE clause: SQL>select * from empbasic where salary >=3000 EMPLOYEE_ID LAST_NAME FIRST_NAME ---------------------------7569 ALBERTS CHRIS 7788 SCOTT DONALD 7799 FISHER MATTHEW 7839 KING FRANCIS 7902 FORD JENNIFER
SALARY -----3000 3000 3000 5000 3000
SQL> select * from gendep order by regional_group NAME LOCATION_ID REGIONAL_GROUP --------------------------------OPERATIONS 167 BOSTON SALES 167 BOSTON SALES 123 CHICAGO OPERATIONS 123 CHICAGO RESEARCH 124 DALLAS
239
Chapter 12—Views OPERATIONS SALES ACCOUNTING RESEARCH SALES OPERATIONS
124 124 122 122 122 122
DALLAS DALLAS NEW YORK NEW YORK NEW YORK NEW YORK
Deleting a View To delete the definition of a view from the data dictionary, use the DROP VIEW command followed by the name of the view. This command does not affect the base tables. Syntax: DROP VIEW name_of_view
Using Views to Change Tables A view containing columns from a single table can be changed without any restrictions, and these changes can be displayed immediately in the base table. A join view, a view formed by columns from several tables, can be changed if the SELECT command that created it does not have:
: : : : :
240
The DISTINCT operator The AVG, COUNT, GLB, MAX, MIN, STDDEV, SUM, and VARIANCE functions The UNION, UNION ALL, INTERSECT, and MINUS operations The GROUP BY, HAVING, START WITH or CONNECT BY clauses A rownum pseudo-column
Views—Chapter 12
If these restrictions are followed, you can use the UPDATE, INSERT, or DELETE commands to change the data of the base tables that form the view. To find out which columns may be changed, use one of the following views of the data dictionary: Dictionary View USER_UPDATABLE_COLUMNS
DBA_UPDATABLE_COLUMNS
ALL_UPDATABLE_VIEWS
Description Displays all the columns of the user’s tables and views that can be changed. Displays all the columns of the DBA’s tables and views that can be changed. Displays all the columns of the tables that can be changed.
Next is an example showing the tables that can be changed in the Funcdep view: SQL> SELECT column_name, updatable 2 FROM user_updatable_columns 3 where table_name=’FUNCDEP’; COLUMN_NAME ------------LAST_NAME FIRST_NAME SALARY DEPARTMENT_ID NAME EMPLOYEE_ID
UPDATABLE --------YES YES YES NO NO YES
To understand the restrictions when changing composite views, you have to understand the concept of key-preserved tables. A key-preserved table is a table in which the key column has all of its rows as part of the union result. In other words, it has all of its keys preserved when the view is formed. 241
Chapter 12—Views
The UPDATE Command In the next example, let’s change the contents of the Salary field in the Funcdep view. We’ll give each employee in the accounting department a pay raise of 100%. The command to do this is: SQL> update funcdep 2 set salary=salary*2 3 where name=’ACCOUNTING’;
Compare these new values to the old ones listed earlier in this chapter: SQL> select EMPLOYEE_ID ----------7782 7839 7934
* from funcdep where name=’ACCOUNTING’; LAST_NAME FIRST_NAME SALARY NAME --------- -----------------------CLARKY CAROL 4900 ACCOUNTING KING FRANCIS 10000 ACCOUNTING MILLER BARBARA 2600 ACCOUNTING
You are also limited by the integrity constraints of the base tables. In the next example, we try to change the contents of the employee_id field: SQL> update funcdep 2 set employee_id=9999 3 where last_name=’CLARK’; update funcdep * ERROR on row 1: ORA-02292: integrity constraint (DEMO.SYS_C00801) violates – child record located
242
Views—Chapter 12
Following are two other situations: SQL> update funcdep 2 set name=’SALES FORCE’ 3 where name=’SALES’; where name=’SALES’ * ERROR on row 3: ORA-01779: cannot change a column that list a non key-preserved table. SQL> update funcdep 2 set last_name=’CLARKY’ 3 where last_name=’CLARK’; 1 row updated.
When WITH CHECK OPTION is included in a view’s definition, all the linked columns and all the repeated columns of the table are changed.
The INSERT Command An INSERT command will work only when all the constraints of the base table are satisfied. We cannot insert a new row in the EMP table through Funcdep, since there is no department_id field in the EMPLOYEE table used as the FOREIGN KEY.
Replacing a View The replacement of a view simply changes its definition in the data dictionary. A view can be replaced in one of two ways. One method is to delete the view with the DROP command and then use the CREATE VIEW command to rebuild it. The second option does not delete the view, but uses the OR REPLACE option of the CREATE 243
Chapter 12—Views
VIEW command. This second option replaces the definition of the view and preserves the existing security authorizations.
Viewing the Definitions of the View The definitions of a view are stored in a view called USER_VIEWS in the data dictionary. The following shows the structure of such a view: SQL> describe user_views; Name Null? ----------------------VIEW_NAME NOT NULL TEXT_LENGTH TEXT TYPE_TEXT_LENGTH TYPE_TEXT OID_TEXT_LENGTH OID_TEXT VIEW_TYPE_OWNER VIEW_TYPE
Type -------------VARCHAR2(30) NUMBER LONG NUMBER VARCHAR2(4000) NUMBER VARCHAR2(4000) VARCHAR2(30) VARCHAR2(30)
To see the name and text of the command that builds this view, use the view_name column and text: SQL> select view_name, text from user_views; VIEW_NAME ----------------------------TEXT ----------------------------------------------------EMPBASIC select employee_id, last_name,first_name, salary from employee
244
Views—Chapter 12 GENDEP select department.name, department.location_id, location.regional_group from dep NEWDEP SELECT “DEPARTMENT_ID”,"NAME","LOCATION_ID" FROM DEPARTMENT SALES SELECT SALESPERSON_ID, SALES_ORDER.CUSTOMER_ID, CUSTOMER.NAME CUSTOMER, P
Materialized Views A materialized view is a physical copy of the base table with the results moved to another schema object. Materialized views are also called snapshots, because they are a kind of photograph of the base table.
Designing Multiple Tables and Views Simultaneously You can create tables and views at the same time with the CREATE SCHEMA command. In this command, you specify the definitions of all the tables and views, along with the access privileges of each of them. If, for some reason, one of the tables or views is not created, all the creation commands are cancelled. A schema is created by the CREATE USER command, which creates some of the schema objects at the same time.
245
Chapter 12—Views
Syntax: CREATE SCHEMA AUTHORIZATION name_of_schema create_table_statement create_view_statement grant_statement
Arguments: name_of_schema This must be identical to the user name created by the CREATE USER command. create_table_statement A CREATE TABLE command that is part of the schema. Several commands can be specified. You cannot use the final semicolon. create_view_statement A CREATE VIEW command that is part of the schema. Several commands can be specified. You cannot use the final semicolon. grant_statement An optional GRANT command used to attribute privileges. Cannot be returned with semicolon. This next example creates two tables and a view: CREATE TABLE Dept_tab ( Deptno NUMBER(3) PRIMARY KEY, Dname VARCHAR2(15), Loc VARCHAR2(25)) CREATE TABLE Emp_tab ( Empno NUMBER(5) PRIMARY KEY, Ename VARCHAR2(15) NOT NULL, Job VARCHAR2(10), Mgr NUMBER(5), Hiredate DATE DEFAULT (sysdate),
246
Views—Chapter 12 Sal NUMBER(7,2), Comm NUMBER(7,2), Deptno NUMBER(3) NOT NULL CONSTRAINT Dept_fkey REFERENCES Dept_tab(Deptno)) GRANT SELECT ON Sales_staff TO human_resources; CREATE SCHEMA AUTHORIZATION Scott CREATE VIEW Sales_staff AS SELECT Empno, Ename, Sal, Comm FROM Emp_tab WHERE Deptno = 30 WITH CHECK OPTION CONSTRAINT Sales_staff_cnst
In this chapter you’ve learned that views are an important mechanism to help display tables and restrict database access through the limitation of columns. You’ve also seen how to mask the origin table or column by replacing the column schema with an alias. Mastering views is important for those who develop database applications. The next chapter discusses database management through the use of privileges and roles.
247
Chapter 13
Users, Privileges, and Roles The concept of users is important for database administrators to understand. Anyone who wants to access Oracle must be registered as a user of the database, and must have privileges assigned to him or her outlining the tasks he or she will be able to execute. Roles are groups of privileges that can be assigned to users. These concepts are thoroughly explained in this chapter.
Users One of the most important tasks of an administrator is controlling access to the database. Oracle relies on a mechanism that allows you to register a person, called user. Each registered user has an access password, which must be provided in various situations. Each user is then assigned individual privileges or roles.
The CREATE USER Command The CREATE USER command is responsible for the creation of new users. It creates a user or an account through which you can connect to the database, and establish the means by which Oracle will allow the user access. You can assign the following optional properties to the user: 249
Chapter 13—Users, Privileges, and Roles
: : : :
Standard tablespace Temporary tablespace Quotas to allocate space in the tablespaces Profile containing resource limits
Syntax: CREATE USER user IDENTIFIED {BY password | EXTERNALLY | GLOBALLY AS ‘CN=user’} [ DEFAULT TABLESPACE tablespace | TEMPORARY TABLESPACE tablespace | QUOTA { integer [K | M] | UNLIMITED} ON tablespace [QUOTA { integer [K | M] | UNLIMITED} ON tablespace] ... | PROFILE profile | PASSWORD EXPIRE | ACCOUNT { LOCK | UNLOCK} ...
Arguments: user The name of the user to be created. IDENTIFIED Indicates how Oracle validates the user. BY password Requires the user to specify this password for the connection. EXTERNALLY Indicates that a user must be validated by an external service (such as an operating system service or even third parties).
250
Users, Privileges, and Roles—Chapter 13
GLOBALLY AS external name Indicates that a user must be authenticated by Oracle Security Service. External name is the name X.509 in Oracle Security Service, which identifies this user. DEFAULT TABLESPACE Identifies the standard tablespace for the objects created by the user. If this clause is omitted, the objects are sent to the System tablespace as default. TEMPORARY TABLESPACE Identifies the tablespace for the user’s temporary segments. If this clause is omitted, they are sent to the System tablespace as default. QUOTA Allows the user to allocate space in the tablespace, optionally establishing a quota of bytes integer. This quota is the maximum space that can be allocated in the tablespace by the user. You can also use K or M to specify the quota in Kbytes or Mbytes. Note that a CREATE USER command can have several QUOTA clauses for different tablespaces. UNLIMITED Allows the user to allocate unlimited space in the tablespace. PROFILE Reassigns the named profile to the user, and limits the database resources that can be utilized by the user. If this clause is omitted, Oracle assigns the default profile to the user. PASSWORD EXPIRE Makes the user password expire. It must be changed before a new connection to the database can be completed. ACCOUNT LOCK Blocks the user account, disabling its access.
251
Chapter 13—Users, Privileges, and Roles
ACCOUNT UNLOCK Unblocks the user account, enabling its access. Here is an example (do not execute this command): CREATE USER james IDENTIFIED BY welcome DEFAULT TABLESPACE sports QUOTA 10M ON sports QUOTA 5M ON temp_ts QUOTA 5M ON system PROFILE boxer
User James has the password welcome and uses the Sports tablespace with 10 Mbytes of space (specified by QUOTA). There are 5 Mbytes each in the temp_ts and System tablespaces. The limits for the resources of the user database are defined in the profile file called Boxer.
Creating a New User To assign privileges, you must connect to the administrator using the System name and the manager keyword. To connect to the database as a new user, you must use the CONNECT command with the following format: CONNECT user/password CONNECT system/manager
Now let’s use the CREATE USER command. Both the name and password can be up to 30 characters long, without spaces or commas. If you enter a user name that has already been registered, the system will issue an error message and will not allow you to register the new user.
252
Users, Privileges, and Roles—Chapter 13
When the user is created, you have to assign him or her privileges. First, let’s create a user called Cindy, with the password ramalho: SQL> CREATE USER cindy IDENTIFIED BY ramalho; User created.
Before assigning the privilege, we will try to connect as Cindy: SQL> connect cindy/ramalho; ERROR: ORA-01045: the user Cindy needs the CREATE SESSION privilege; logon denied
There is an error in the above example because the user doesn’t have any privileges assigned yet. Let’s go back and connect to the system using the GRANT command.
The GRANT Command The GRANT command has two distinct forms: one to distribute system privileges and the other to distribute object privileges (these are discussed later in this chapter). Only the DBA can use the GRANT command to distribute system privileges. Syntax: GRANT SystemPrivilege/role TO user/role/ public WITH ADMIN OPTION
Arguments: privilege The name of the privilege to be assigned. user/role The name of the user or role that is receiving the privilege.
253
Chapter 13—Users, Privileges, and Roles
WITH ADMIN OPTION Allows a user or role that receives the privilege to assign it to other users, change it, or even delete it. Let’s connect as System and assign the RESOURCE privilege, which allows access to the database and the creation of tables, sequences, procedures, triggers, indexes, and clusters: SQL> connect system/manager; Connected. SQL> grant RESOURCE to cindy; Grant operation successful.
From now on the user can perform any operation pertaining to the role received, such as, in the following example, the creation of a table: SQL> connect cindy/ramalho; Connected. SQL> create table x 2 (a number); Table created.
The next example shows, through SQL*Plus, the importance of understanding the concept of user, role, and privilege. After configuring SQL*Plus, we use the CONNECT command to make a new connection as user Cindy. Note that the name was entered incorrectly, and even with the correct password Oracle denied access: SQL> connect cindy/ramalho; ERROR: ORA-01017: invalid name of user/password; logon denied
254
Users, Privileges, and Roles—Chapter 13
Now we will connect correctly and access Scott’s table: SQL> connect Enter the user name: Cindy Enter the password: ******* Connected. SQL> select * from emp; select * from emp * ERROR on row 1: ORA-00942: the table or view does not exist.
This occurs because the EMP table, which was created by Scott, did not assign any access privileges to other users. Therefore, each user is restricted to his or her own activities inside the database.
Deleting a User You can remove a database user with the DROP USER command. This command removes both the user and all the objects contained in this user’s schema. You will need to specify the CASCADE clause of the command. Oracle also removes all the referential integrity associated to the objects of the removed user. Syntax: DROP USER name
In the next example user Arnold is removed: SQL> connect system/manager Connected.
255
Chapter 13—Users, Privileges, and Roles SQL> drop user arnold; Users eliminated. SQL> select * from all_users; USERNAME USER_ID --------------------------- ------SYS 0 SYSTEM 5 OUTLN 11 DBSNMP 20 MTSSYS 28 AURORA$ORB$UNAUTHENTICATED 25 SCOTT 26 DEMO 27 ORDSYS 30 ORDPLUGINS 31 MDSYS 32 CTXSYS 35 CINDY 37
CREATED -------03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 05/17/99
13 rows selected.
Privileges A privilege is an authorization given to the user to access and manipulate a database object in a certain way. For example, one user can be assigned the privilege to select tables but not change them, while another user can read, update, and even change the structure of tables and other objects. As all database manipulation is done through SQL commands, a privilege grants to a user the right to use these commands.
256
Users, Privileges, and Roles—Chapter 13
There are two types of privileges: system privileges and object privileges.
System Privileges A system privilege is the right or permission to execute certain database actions in a specific type of database object. There are more than 70 types of privileges associated to the actions of a database. The name of the privilege is similar to the name of the action it executes. For example, a privilege called ALTER TABLE grants a user the right to modify a table. The following is a list of the system privileges: Action Analyze Audit Cluster
Database Database link Index
Privilege Procedure
Profile
Privilege ANALYZE ANY AUDIT ANY AUDIT SYSTEM CREATE CLUSTER CREATE ANY CLUSTER ALTER ANY CLUSTER DROP ANY CLUSTER ALTER DATABASE CREATE DATABASE LINK CREATE ANY INDEX ALTER ANY INDEX DROP ANY INDEX GRANT ANY PRIVILEGE CREATE PROCEDURE CREATE ANY PROCEDURE ALTER ANY PROCEDURE DROP ANY PROCEDURE EXECUTE ANY PROCEDURE CREATE PROFILE ALTER PROFILE DROP PROFILE ALTER RESOURCE COST
257
Chapter 13—Users, Privileges, and Roles
Action Public database link Public synonym Role
Rollback segment
Sequence
Session
Snapshot
Materialized views
Synonym
System
258
Privilege CREATE PUBLIC DATABASE LINK DROP PUBLIC DATABASE LINK CREATE PUBLIC SYNONYM DROP PUBLIC SYNONYM CREATE ROLE ALTER ANY ROLE DROP ANY ROLE GRANT ANY ROLE CREATE ROLLBACK SEGMENT ALTER ROLLBACK SEGMENT DROP ROLLBACK SEGMENT CREATE SEQUENCE CREATE ANY SEQUENCE ALTER ANY SEQUENCE DROP ANY SEQUENCE SELECT ANY SEQUENCE CREATE SESSION ALTER SESSION RESTRICT SESSION CREATE SNAPSHOT CREATE ANY SNAPSHOT ALTER ANY SNAPSHOT DROP ANY SNAPSHOT ALTER MATERIALIZED VIEW CREATE MATERIALIZED VIEW DROP MATERIALIZED VIEW CREATE SYNONYM CREATE ANY SYNONYM DROP ANY SYNONYM ALTER SYSTEM
Users, Privileges, and Roles—Chapter 13
Action Table
Tablespace
Transaction Trigger
User
View
Privilege CREATE TABLE CREATE ANY TABLE ALTER ANY TABLE BACK UP ANY TABLE DROP ANY TABLE LOCK ANY TABLE COMMENT ANY TABLE SELECT ANY TABLE INSERT ANY TABLE UPDATE ANY TABLE DELETE ANY TABLE CREATE TABLESPACE ALTER TABLESPACE MANAGE TABLESPACE DROP TABLESPACE UNLIMITED TABLESPACE FORCE TRANSACTION FORCE ANY TRANSACTION CREATE TRIGGER CREATE ANY TRIGGER ALTER ANY TRIGGER DROP ANY TRIGGER CREATE USER BECOME USER ALTER USER DROP USER CREATE VIEW CREATE ANY VIEW DROP ANY VIEW
Object Privileges An object privilege is the right to perform certain actions in a specific object, such as the right to include a row in a table. These privileges do not apply to all the objects of a database. Triggers, procedures, indexes, database links, and clusters do not have any object privileges. The following is a list of the object privileges: 259
Chapter 13—Users, Privileges, and Roles
Privilege ALTER DELETE EXECUTE INDEX INSERT REFERENCE SELECT UPDATE
Object Tables and sequences Tables and views Procedures Tables Tables and views Tables Tables, views, and sequences Tables and views
When a user creates an object, such as a table, only the user can view it. The user/owner must grant a privilege or a role to access the table. A privilege can be granted with the GRANT command as shown previously in this chapter.
Assigning Object Privileges to a User/Role A variation of the GRANT command allows you to assign object privileges to a user or role. The privileges assigned can be: SELECT, ALTER, DELETE, EXECUTE, INSERT, INDEX, REFERENCE, and UPDATE. The following objects can be assigned privileges: tables, views, sequences, snapshots, and synonyms. Any user who has authority can grant privileges on tables. Syntax: GRANT ALL SELECT INSERT DELETE INDEX ALTER UPDATE [( column_name )]ON table_name/view_Name TO user /PUBLIC WITH ADMIN OPTION
260
Users, Privileges, and Roles—Chapter 13
Options: SELECT To select data in a table or view. INSERT To insert rows in a table or view. DELETE To eliminate rows in a table or view. UPDATE To update a table and, optionally, update only the specified columns. INDEX To create or eliminate the indexes of a table. ALTER To modify a table. ALL To perform all the above privileges. table_name Names of existing tables (including the qualifier) in the database. view_name Names of existing views (including the qualifier) in the database. column_name This is optional and determines the columns of tables or views specified in the ON clause. The names of the columns must not be qualified. USER Name of the user to whom the privilege is assigned. PUBLIC Means that all the current and new users have the privileges specified for the table or view.
261
Chapter 13—Users, Privileges, and Roles
WITH ADMIN OPTION Allows the user or role that receives the privilege to grant it to other users, modify it, or even delete it. The next example shows user Scott granting the SELECT privilege so user Cindy can access the EMP table: SQL> connect scott/tiger; Connected. SQL> grant select on emp to cindy; GRANT operation successful.
Now we connect to Cindy and access the table: SQL> select ename from emp; select ename from emp * ERROR on row 1: ORA-00942: table or view does not exist
An error occurs. What is the problem, since the privilege was already assigned? When a user makes a SELECT in another user’s table, he or she must provide the schema of the table or object. In other words, he or she must identify the table, owner, and even the database link, if needed. In the following example, you need to provide the SCOTT.EMP schema to access the EMP table: SQL> select ename from scott.emp; ENAME ----SMITH ALLEN WARD JONES
262
Users, Privileges, and Roles—Chapter 13
If you try to access another one of Scott’s tables using this schema, but without assigning an object privilege for the user, you will have the same problem again. Connected as Scott, we will assign to Cindy the UPDATE privilege only for the Dname column of the DEPT table: SQL> grant update (DNAME) on dept to cindy;
Then, connected as Cindy, we will update two columns of the DEPT table: SQL> update scott.dept 2 set dname=’SALES FORCE’ 3 where deptno=30; 1 row updated. SQL> update scott.dept 2 set loc=’MIAMI’ 3 where deptno=30; update scott.dept * ERROR on row 1: ORA-01031: insufficient privileges
Note that it was not possible to update the column without the proper privileges. In the previous example, user Cindy was not assigned the UPDATE privilege for all of the columns. Now we will try to insert a new row in the SCOTT.DEPT table: SQL> insert into scott.dept values (50,’MEDIA’,’MIAMI’); insert into scott.dept values (50,’MEDIA’,’MIAMI’) * ERROR on row 1: ORA-01031: insufficient privileges
263
Chapter 13—Users, Privileges, and Roles
Note that Cindy is prevented from updating the table because she has not been assigned the proper privileges.
Viewing Users and Privileges Connected as Scott, we will try to create a new user: SQL> create user arnold identified by terminator; create user arnold identified by terminator * ERROR on row 1: ORA-01031: insufficient privileges
Remember that high-level privileges are necessary to create a user. Connected as System/manager, we will create this user and view a list of all other users. You can use one of the tables of the data dictionary to check the database users. The dictionary view that maintains this list is ALL_USERS. SQL> connect system/manager; Connected. SQL> create user arnold identified by terminator; User created. SQL> select * from all_users; USERNAME USER_ID --------------------------- ------SYS 0 SYSTEM 5 OUTLN 11 DBSNMP 20 MTSSYS 28
264
CREATED -------01/03/99 03/01/99 03/01/99 03/01/99 03/01/99
Users, Privileges, and Roles—Chapter 13 AURORA$ORB$UNAUTHENTICATED SCOTT DEMO ORDSYS ORDPLUGINS MDSYS ARNOLD CTXSYS CINDY
25 26 27 30 31 32 38 35 37
03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 03/01/99 05/17/99 03/01/99 05/17/99
Revoking a System Privilege In addition to granting a privilege, you can also revoke it, by using the REVOKE command. To be revoked, a system privilege must have been granted with the ADMIN OPTION option. SQL> revoke create session from arnold; Revoke successful.
To check the functionality of the command, connect as Arnold: SQL> connect arnold/terminator ERROR: ORA-01045: the user Arnold needs the privilege CREATE SESSION; logon denied Notice: You are not connected to Oracle anymore. SQL>
Oracle checked Arnold’s privileges and noted he did not have the CREATE SESSION privilege any more, thus preventing the connection to the database.
265
Chapter 13—Users, Privileges, and Roles
Revoking an Object Privilege Now we show you how to revoke an object privilege that was granted to a user. In an example we have seen before, user Scott granted to Cindy the SELECT privilege for the DEPT table. Now we will revoke this privilege using a SQL command. To do that, you must connect as a user who has the authority to grant privileges. A user cannot grant or revoke privileges to himself or herself. In the following example, we have to connect as user Scott. Then, we use the REVOKE command, specifying the privilege, the object, and the user that will be revoked: SQL> connect scott/tiger Connected. SQL> revoke select on dept from cindy; Revoke successful.
To verify that the revoke operation worked, we connect as Cindy and try to access the SCOTT.DEPT table: SQL> connect cindy/ramalho Connected. SQL> select * from scott.dept; select * from scott.dept * ERROR on row 1: ORA-01031: insufficient privileges
Because the privilege has been revoked, Cindy cannot access the table anymore. While Cindy cannot view the DEPT table anymore, she still can change the contents of the Dname column: SQL> update scott.dept 2 set dname=’SALES’ 3 where deptno=30;
266
Users, Privileges, and Roles—Chapter 13
Roles A role is a group of privileges assigned to a name. Instead of granting eight privileges to a user, you can create a role that is assigned those eight privileges, and then assign that role to the user. The use of roles simplifies the administration of users. Oracle8i has several predefined roles, such as CONNECT, RESOURCE, DBA, EXP_FULL_DATABASE, and IMP_FULL_DATABASE. In addition to these roles, users can create other ones that meet the needs of their applications. Next, we will review Oracle’s users, passwords, and roles: User
Password
Role
SCOTT
TIGER
CONNECT and RESOURCE
SYSTEM
MANAGER
DBA
SYS
SYS1
CONNECT, RESOURCE, and DBA, EXP_FULL_DATABASE, and IMP_FULL_DATABASE
DEMO
DEMO
CONNECT and RESOURCE
If you are using Windows 95, the password of user SYS is the serial number without the hyphens. This number can be obtained by clicking on the System icon on the Control Panel. It appears after the identification of the user, in a format similar to this: “28877-411-1357921-04810”. User SYS is the most advanced of all. Therefore, use it only when you really need it, since it can execute some actions that may compromise the entire database and its contents.
267
Chapter 13—Users, Privileges, and Roles
Below are Oracle8i’s predefined roles: Role CONNECT
Purpose Allows access to the database.
RESOURCE
Allows access to the database, and the creation of tables, sequences, procedures, triggers, indexes, and clusters. All the system privileges. It allows granting the privilege to other users.
DBA DELETE_CATALOG_ROLE EXECUTE_CATALOG_ROLE SELECT_CATALOG_ROLE
Roles used to export views and packages of the data dictionary.
EXP_FULL_DATABASE IMP_FULL_DATABASE
Roles used to export and import the database.
AQ_USER_ROLE AQ_ADMINISTRATOR_ROLE
Roles used for Oracle’s Advanced Querying.
SNMPAGENT
Role used by the Enterprise Manager or by the Intelligent Agent. Creates a user that has a recovery catalog.
RECOVERY_CATALOG_OWNER HS_ADMIN_ROLE
This role is used by a DBA, who uses the heterogeneous services of Oracle to access specific tables of the data dictionary.
To create a role, the user must have the CREATE ROLE privilege. When created, a role can be assigned the option ADMIN OPTION, which allows the user to grant it to other roles or users, revoke the granted role, change the access to it, and remove it.
Creating a Role The creation of a new role follows the same rules that apply to the creation of other objects we have seen so far. When you create a new role, you can assign it some privileges or other roles that
268
Users, Privileges, and Roles—Chapter 13
were previously created. The SQL command used to create a role is CREATE ROLE: Syntax: CREATE ROLE role [NOT IDENTIFIED | IDENTIFIED {BY password | EXTERNALLY | GLOBALLY} ]
Arguments: role Name of the role to be created. Oracle recommends the role contain at least one single-byte character, independent of the database’s set of characters, which may or may not contain multiple-byte characters. NOT IDENTIFIED Indicates that this role is authorized by the database and that no password is required to enable it. IDENTIFIED Indicates that the user must be authorized by the specified method before the role can be enabled with the SET ROLE command: BY password The user must specify the password for Oracle to enable the role. It can contain only single-byte characters from the database’s set of characters, regardless of whether this set of characters contains multiple-byte characters. EXTERNALLY Indicates that the user must be authorized by an external service (such as an operating system or a third-party service) before the role can be enabled. Depending on the operating system, the user must specify a password before the role can be enabled.
269
Chapter 13—Users, Privileges, and Roles
GLOBALLY Indicates that the user must have authorization from Oracle Security Service to use the role before it can be enabled with the SET ROLE command, or at the login. If both the NOT IDENTIFIED and the IDENTIFIED options are omitted, the standard role will be NOT IDENTIFIED. In the following example, we connect as system/manager to create a role called Basic1: SQL> CREATE ROLE basic1; Role created.
Granting Privileges and Roles to a Role After creating a role, you can grant it privileges using the GRANT command. The privileges can be specific to that role or from other roles. If a role is granted a role, the newly created role assumes the privileges of those roles it may receive. Syntax: GRANT
role/name_of_privilege TO user/role/ PUBLIC WITH ADMIN OPTION
The next example grants the RESOURCE role to Basic1: SQL> grant resource to basic1; Grant operation successful.
270
Users, Privileges, and Roles—Chapter 13
Granting a Role to a User Now we assign the Basic1 role to user Arnold: SQL> grant basic1 to arnold; Grant operation successful.
Next we will connect as the new user: SQL> connect arnold/terminator ERROR: ORA-01045: the user Arnold needs the privilege CREATE SESSION; logon denied Notice: You are not connected to Oracle anymore.
TIP: While the RESOURCE role allows many operations in the schema objects, you need the CREATE SESSION privilege (part of the CONNECT role) to connect to the database. To solve this problem, we will connect as system/manager and assign CONNECT to Basic1: SQL> connect system/manager Connected. SQL> grant connect to basic1; Grant operation successful.
Now let’s try to connect: SQL> connect arnold/terminator; Connected
Viewing the Roles of a User Oracle has some special views that control the privileges and roles. One of these views is called USER_ROLE_PRIVS. It displays the roles assigned to the current user:
271
Chapter 13—Users, Privileges, and Roles SQL> select * from user_role_privs; USERNAME GRANTED_ROLE -------- -----------ARNOLD BASIC1
ADM --NO
DEF --YES
OS_ --NO
SQL> 1 row updated.
Deleting a Role The command responsible for the deletion of a role is DROP ROLE. The user must have the system privilege DROP ANY ROLE to remove a role or the role must have been created with the ADMIN OPTION option. Syntax: DROP ROLE role.
The next example removes the Basic1 role. Oracle automatically updates all the grants, along with updating roles and users that depend on the role that is being removed. After removing the Basic1 role that was granted by user Arnold, we try to connect to this user; Oracle does not allow the access, since the user does not have the access privilege anymore: SQL> connect system/manager Connected. SQL> drop role basic1; Role eliminated.
When we try to connect as user Arnold, an error will occur, because he has no associated privilege or role:
272
Users, Privileges, and Roles—Chapter 13 SQL> connect arnold/terminator ERROR: ORA-01045: the user Arnold needs the privilege CREATE SESSION; logon denied Notice: You are not connected to Oracle anymore.
In this chapter, you learned the concepts of users, roles, and privileges. These are the main tools to control access to the database, and to restrict the operations that can be performed by a user or a group of users. As a developer, you don’t have to worry about roles and privileges, but if you are a database manager, roles and privileges are vital to the security of the database. The next chapter discusses synonyms, which are a simple way to access tables and other database objects.
273
Chapter 14
Synonyms This chapter covers synonyms, which are a simple way to access tables and other database objects using an alternate name or a shortcut. A synonym is an alias given to a database object. A reference is made to the original object when the synonym is created. For example, if a synonym is created for a table, Oracle associates the address of the table to the synonym, and does not create a duplicate of the table. There are many advantages to using synonyms. Perhaps the most important of all is that they hide the identity of the object that is being specified. If the object is changed or moved, all you have to do is to update the synonym, rather than change the numerous references to the object. Sometimes security is not the most important aspect. For instance, a table with a long name that belongs to a schema different from the user can be abbreviated with a synonym, thus simplifying execution of the commands. A synonym can be created for a table, view, snapshot, sequence, procedure, package function, or even another synonym. A synonym can be public and visible to all users, or private and available only to the user who created it. Synonyms can be used to replace objects in the following SQL commands: SELECT INSERT DELETE 275
Chapter 14—Synonyms
GRANT COMMENT UPDATE EXPLAIN PLAN LOCK TABLE REVOKE AUDIT NOAUDIT
The CREATE SYNONYM Command Synonyms are created by using the CREATE SYNONYM command. Syntax: CREATE [PUBLIC] SYNONYM name_of_synonym FOR schema
Arguments: PUBLIC Creates a public synonym. If the PUBLIC clause is omitted, the synonym belongs to the schema or user who created it. Another user can use this synonym if he or she precedes its name with the schema of the user who created it. When a synonym is created as public, you don’t have to add the schema to it. name_of_synonym The name of the synonym. schema The name of the schema where the synonym will be created. If it is omitted, the synonym is created in the user’s schema. A synonym must have a unique name in the schema. If its name is not unique and the user tries to create a synonym with the form and name of an existing synonym or other database object, a warning message will be issued and the synonym will not be created. 276
Synonyms—Chapter 14
The user must have the CREATE SYNONYM privilege to create a synonym.
Creating Synonyms for Tables of Other Users The following example shows how user Cindy can create a private synonym that references another user’s table. To access Scott’s EMP table, this user must grant the SELECT object privilege to Cindy: SQL> connect Enter user-name: scott/tiger Connected. SQL> grant select on scott.emp to cindy;
Now, user Cindy creates a synonym called dt for Scott’s DEPT table. Once the synonym is created, you don’t need to specify the schema to access it: SQL> connect cindy/ramalho; Connected. SQL> create synonym dt for scott.dept; create synonym dt for scott.dept * ERROR on line 1: ORA-01031: insufficient privileges
277
Chapter 14—Synonyms
This error occurred because Cindy does not have the CREATE SYNONYM privilege, which must be assigned by the user administrator or system: SQL> connect system/manager Connected. SQL> grant create synonym to cindy; Grant operation successful. SQL> connect cindy/ramalho; Connected. SQL> create synonym dt for scott.dept; Synonym created. SQL> select * from dt; DEPTNO -----10 20 30 40 70
DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS PLANT
LOC -------NEW YORK DALLAS CHICAGO BOSTON DALLAS
Renaming Synonyms A synonym can be renamed with the RENAME SYNONYM command. All existing references to the synonym that is changed are automatically updated. Therefore, any user who has received the privilege to a synonym that has its name changed keeps his or her privileges for the new name.
278
Synonyms—Chapter 14
Syntax: RENAME old_name TO new_name
In the next example, the synonym is renamed Dep1. Note that the SELECT command works in the usual manner: SQL> rename dt to dep1; Table renamed. SQL> select * from dep1; DEPTNO DNAME LOC ---------------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 70 PLANT DALLAS
Removing Synonyms To remove a synonym, the user must issue the DROP SYNONYM command. Syntax: DROP [PUBLIC] SYNONYM name
Example: SQL> drop synonym dep1; Synonym eliminated.
All references made to a synonym that has been deleted generate an error. It’s important to remember this when the synonym is used inside a procedure. A synonym that is associated to a table is not automatically deleted with the table. 279
Chapter 14—Synonyms
Also note the order in which the synonym is created. In the next example, user Cindy creates a synonym for SCOTT.ACCOUNT and tries to access the table: SQL> create synonym ac for scott.account; Synonym created. SQL> select * from ac; select * from ac * ERROR on line 1: ORA-00942: the table or view does not exist.
Although it is possible to create a synonym for a table with no SELECT privilege assigned, access is denied. The synonym works only when user Scott grants the SELECT privilege. A synonym must have a unique name in the schema. User Scott cannot create a synonym called Dept for a table of user Demo, because it already has a table with that name. On the other hand, Cindy can create such a synonym, because in her schema no object has the name Dept. Different users can create synonyms with similar names as long as they are not public synonyms. SQL> connect scott/tiger Connected. SQL> create synonym dept for demo.department; create synonym dept for demo.department * ERROR on line 1: ORA-00955: the name is being used by an existing object SQL> connect cindy/ramalho SQL> create synonym dept for demo.department; Synonym created. 280
Synonyms—Chapter 14
User Scott can use the synonym created by Cindy by adding the synonym’s schema: SQL> connect scott/tiger Connected. SQL> select * from cindy.dept; DEPARTMENT_ID NAME LOCATION_ID ------------- -------------------10 ACCOUNTING 122 20 RESEARCH 124 30 SALES 123 40 OPERATIONS 167 12 RESEARCH 122 13 SALES 122 14 OPERATIONS 122 23 SALES 124 24 OPERATIONS 124 34 OPERATIONS 123 43 SALES 167 11 lines selected.
Obtaining Information on the Schema Objects For detailed information about the schema objects, you can use one of the many views of the database dictionary: View ALL_OBJECTS, USER_OBJECTS
Purpose Displays all the user objects.
ALL_CATALOG, USER_CATALOG Returns the name and type of the user objects. ALL_TABLES, USER_TABLES Returns the user tables.
281
Chapter 14—Synonyms
View ALL_TAB_COLUMNS, USER_TAB_COLUMNS
Purpose Returns information about the columns of user tables.
ALL_TAB_COMMENTS, USER_TAB_COMMENTS
Returns the comments of the tables.
ALL VIEWS, USER_VIEWS
Returns the user views.
ALL_INDEXES, USER_INDEXES
Returns the user indexes.
ALL_IND_COLUMNS, USER_IND_COLUMNS
Returns the columns used as index.
USER_CLUSTERS
Returns the user clusters.
ALL_SEQUENCES, USER_SEQUENCES
Returns the user sequences.
ALL_SYNONYMS, USER_SYNONYMS
Returns the user synonyms.
ALL_DEPENDENCIES, USER_DEPENDENCIES
Returns the dependency relations of the user.
For specific information on each view, i.e., which columns form the view, use the DESCRIBE command: SQL> describe user_views;
Name Null? ---------------- -------VIEW_NAME NOT NULL TEXT_LENGTH TEXT TYPE_TEXT_LENGTH TYPE_TEXT OID_TEXT_LENGTH OID_TEXT VIEW_TYPE_OWNER VIEW_TYPE 282
Type -------------VARCHAR2(30) NUMBER LONG NUMBER VARCHAR2(4000) NUMBER VARCHAR2(4000) VARCHAR2(30) VARCHAR2(30)
Synonyms—Chapter 14
Here are some examples related to user Scott: SQL> select * from user_catalog; TABLE_NAME TABLE_TYPE -------------------ACCOUNT TABLE BONUS TABLE DEMOCONSTR2 TABLE DEMOCONSTR3 TABLE DEPT TABLE DEPT1 TABLE EMP TABLE NEWAGAIN TABLE NEWEMP TABLE NEWEMP2 TABLE NEWONE TABLE NEWSEQ SEQUENCE NEWSEQ2 SEQUENCE NEWSEQ3 SEQUENCE PEMP SYNONYM RECEIPT TABLE SALGRADE TABLE TESTACONSTR TABLE SQL> select * from user_synonyms; SYNONYM_NAME TABLE_OWNER TABLE_NAME ------------------------------DB_LINK ------------------------------------------PEMP SCOTT EMP
283
Chapter 14—Synonyms
SQL> select * from user_sequences; SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY
C
O
CACHE_SIZE
LAST_NUMBER
------------- --------- --------- -----------NEWSEQ 1 1,000E+27 1 NEWSEQ2 30 1,000E+27 20
N N
N N
---------20 30
----------1 495
NEWSEQ3
N
N
20
1040
1000
4000
1
SQL> select index_name, index_type from user_indexes; INDEX_NAME INDEX_TYPE ------------------IND_ENAME NORMAL PK_DEPT NORMAL PK_EMP NORMAL PK_EMP2 NORMAL PK_EMP3 NORMAL PK_EMP4 NORMAL PK_NEWA NORMAL SYS_C001275 NORMAL
This chapter introduced the concept of synonyms, a simple and efficient way to mask or hide the schema of an object. Synonyms can also be used to simplify SQL commands. When you use synonyms, there’s no need to specify the owner, name, or location of the object to manipulate it. This chapter closes the part of this book that covers schema objects. The next part discusses the PL/SQL language, an extension of SQL, and its objects.
284
Part IV
PL/SQL Now that you have learned how to create and maintain the schema objects, we will go a little further into the use of PL/SQL, Oracle’s procedural language. In this part we show how to create triggers, stored procedures, and packages, and introduce the concept of cursors. Chapter 15: PL/SQL Chapter 16: Triggers Chapter 17: Stored Procedures and Functions Chapter 18: Packages Chapter 19: Cursors Chapter 20: Transactions
285
Chapter 15
PL/SQL PL/SQL is an extension of the SQL language. We can say that it is a dialect of the SQL language specialized for use in the Oracle database. Because it is a procedural language, it eliminates many restrictions of the SQL language PL/SQL combines the SQL language’s ease of data manipulation and the procedural language’s ease of programming. Routines written in PL/SQL can be called in the Oracle call interface, Java, Pro*C/C++, or COBOL. With the PL/SQL language, we can create schema objects, including the following:
:
: : :
Stored procedures and functions. A stored procedure is a PL/SQL program that can be enabled by an application, a trigger, or an Oracle tool. The basic difference between a procedure and a function is that a procedure executes its commands and a function executes commands and returns a result. Packages. A package is a file that groups functions, cursors, stored procedures, and variables in one place. Triggers. A trigger is a PL/SQL program that is stored in the database and executed immediately before or after the INSERT, UPDATE, and DELETE commands. Cursors. Oracle uses workspaces to execute the SQL commands. Through PL/SQL cursors, it is possible to name the workspace and access its information. 287
Chapter 15—PL/SQL
PL/SQL Blocks The PL/SQL language uses the concept of structured blocks. Procedures and functions form these blocks. A PL/SQL block has the basic structure shown below:
[DECLARE -- declarations] BEGIN -- statements [EXCEPTION -- handlers] END;
Figure 15.1:
The basic structure of a PL/SQL block.
There are three parts to the PL/SQL block:
: : :
288
Declaration section/Declare (optional), in which all the objects are declared. Execution section/Begin, in which the PL/SQL commands are placed. Exception section/Exception (optional), in which the errors are handled.
PL/SQL—Chapter 15
Declaration Section The first section of the block is called the declaration. It is optional, but if the block uses variables or constants, all of them must be declared before they are used in a command. This section begins with the keyword Declare. In this section, the developer can perform the following:
: : : :
Declare the name of an identifier. Declare the type of identifier (constant or variable). Declare the data type of the identifier. Assign (initialize) contents to the identifier.
Variables and Constants The PL/SQL language allows the declaration of variables and constants, which can be used in the SQL commands contained in the procedures and functions. All the variables and constants used must be declared.
Variables The variables can contain any data type that is valid for SQL and Oracle (such as char, number, long, varchar2, and date) in addition to these types:
: : : : :
Boolean
Can be assigned the values True, False, or NULL.
Binary_integer Accepts numbers between -2,147,483,647 and 2,147,483,647. Positive
Accepts numbers from 1 to 2,147,483,647.
Natural
Accepts numbers from 0 to 2,147,483,647.
%type Assigns to the variable that is being created the same data types used by the column that is being used. Note the following example, in which the variable codcli is created with the same data type as the Deptno column: 289
Chapter 15—PL/SQL
codcli := dept.deptno%type;
:
%rowtype Declares a composed variable that is equivalent to the row of the table. After the variable is created, the fields of the table can be accessed, using the name of this variable followed by a period and the name of the field: Empline := emp%rowtype
After the variable is created, you can use the following expression to assign a column to another variable: Newvar : = empline.ename; Code= NUMBER(5); Name=CHAR(30); OK= BOOLEAN;
Even arrays of variable size (varrays) can be created through the varray, record, and table data types. There are two ways to assign values to a variable. The first is to use the assignment operator “:=”: tot := price * margin; increase:= sal * 1.10; OK := FALSE;
The second way to assign values to variables is to use the SELECT command to assign the contents of the fields of a table to a variable: SELECT sal * 0.10 INTO increased FROM emp WHERE empno = emp_id;
290
PL/SQL—Chapter 15
Constants The declaration of a constant is similar to the declaration of a variable. All you have to do is to add the keyword Constant after the name of the constant: Vr_fixo CONSTANT REAL := 4000.00;
Each variable or constant must be specified with its name, type, and, optionally, initial value. All the rows must end with a semicolon: DECLARE Cust_name varchar2 (20); Credit number (5,2) : = 100;
Execution Section This section begins with the Begin declaration. The commands specified here must follow the same rules used for executing a command in SQL*Plus. They must always end with a semicolon. This section can contain SQL commands, logical control commands, and assignment commands, as well as other commands.
Exception Section In this section, the developer can use commands to handle an error that occurs during the execution of a PL/SQL program. When this type of error occurs inside a PL/SQL program, the following error message is displayed: PLS-00000 Error message.
You can create a routine that executes corrective procedures when detecting an error, thus preventing an interruption of the system.
291
Chapter 15—PL/SQL
How PL/SQL Works PL/SQL is an engine that makes up part of the Oracle server. It executes the procedural commands and passes the SQL commands for the Oracle server to process.
PL/SQL Engine
PL/SQL Block
Procedural Statement Executor
PL/SQL Block
SQL Statement Executor Oracle
Figure 15.2:
PL/SQL processing.
PL/SQL blocks can be created with any of the processing editors. Windows Notepad, for example, is perfect for the task. To execute a PL/SQL program or script, you can use SQL*Plus, which allows creating, storing, and executing PL/SQL blocks. However, don’t forget that the editing capabilities of SQL*PLUS are quite limited.
Control Structures Like most procedural languages, PL/SQL has some commands to control the execution flux of the program. They are responsible for performing deviations, analyzing conditions, and allowing decision making inside the application. Following are the main
292
PL/SQL—Chapter 15
control structures in PL/SQL, which can be divided into condition control structures (selection), sequence structures, and repetition or interaction structures.
Selection
T
Sequence
Iteration F
F T
Figure 15.3:
PL/SQL control structures.
The IF..THEN Command The IF..THEN command evaluates a condition and executes one or more rows of commands only if the analyzed condition is true. It has two variations as follows: Syntax 1: IF THEN ; ; END IF;
293
Chapter 15—PL/SQL
The commands that appear between the THEN and END IF clauses will be executed only if the condition is true. Example: IF SALl> = 5000 THEN UPDATE EMP SET SAL= SAL*1.2; END IF
Syntax 2: IF CONDITION THEN ; ELSIF THEN ; ELSIF THEN ; ELSE ; END IF;
In this structure, more than one condition can be analyzed and, therefore, several actions can be executed: Example: IF sal<2000 THEN UPDATE EMP SET SAL= SAL*1.2; ELSIF sal <3000 THEN UPDATE EMP SET SAL=SAL*1.3 ELSE UPDATE EMP SET SAL=SAL*1.4 END IF
294
PL/SQL—Chapter 15
PL/SQL uses the ELSIF clause rather than ELSEIF, as other languages do. A single command can have numerous ELSIF clauses; however, it can have only one ELSE clause. In this structure, if the main condition returns false, the first ELSIF clause will be analyzed. If the main condition is true, the following commands will be executed until another ELSIF or ELSE clause is found. If the first ELSIF condition is false, the program tests the second condition, and so on. When the first true condition is found, its commands are executed, and the program jumps to the row after the END IF command. An IF..THEN command can be nested inside other IF..THEN commands.
The LOOP Command The LOOP command initializes a group of commands indefinitely, or until a condition forces a “break” in the loop and detours the execution of the program to another place. This command is used with the EXIT command, which is responsible for interrupting the loop execution: Syntax 1: LOOP EXIT END LOOP;
Syntax 2: LOOP EXIT []] WHEN END LOOP;
295
Chapter 15—PL/SQL
Whenever the commands are executed inside a loop, the cycle restarts in the command following that loop. When EXIT is executed, the execution control passes to the row following the END LOOP command or to the name specified: I : = 1 Loop I : = I+1 IF I=> 30 EXIT END IF END LOOP
Another version would be: I : = 1 Loop I : = I + 1 EXIT WHEN i > = 30 END LOOP
The FOR..LOOP Command The FOR..LOOP command is a variation of the LOOP command. Here, the commands are automatically executed until an evaluated condition returns false. Syntax: FOR IN [REVERSE] . . LOOP
296
PL/SQL—Chapter 15 END LOOP;
Example: FOR j IN 1 . . 10 LOOP END LOOP;
In this case, the FOR command initializes a control variable called J, which has the initial value of 1. The commands will be executed until END LOOP is found. Then, the control returns to the FOR command, which increments the variable and analyzes the master condition, i.e., whether the value of J is less than the final value. When this happens the cycle is reinitialized. The REVERSE clause makes the counter start with the highest value and decrease until it reaches the lowest value.
The WHILE Command The WHILE command is another control structure. This structure only executes the commands if the analyzed condition is true. Syntax: WHILE LOOP END LOOP;
Example: X: =1 While x<20 LOOP x:+x+1 END LOOP 297
Chapter 15—PL/SQL
Integrating SQL in a PL/SQL Program SQL commands can be inserted in the execution section of a PL/SQL block. The developer can use (reference) a variable or constant declared in the declaration section. This way, in addition to using the name of the columns, the contents of the variables can also be manipulated by the SQL commands. Inside a PL/SQL program the SELECT command uses a new clause called INTO that allows transferring the contents of the fields in a row to the variables in memory. This clause must be placed between the list of fields and the FROM clause: Declare Var_name varchar2 (20) ; Begin SELECT ename INTO Var_name FROM emp for ename = ‘SMITH’ ; End;
Note that to attribute contents to a field in a variable, the SELECT command must return only one row; otherwise an error will occur, since several values are being assigned to only one variable. Although powerful in its ability to recover information, PL/SQL is a veritable dinosaur in terms of user interface. Even when executed in a graphical environment, it seems obsolete. It has no support for direct communication with the user. For example, when a PL/SQL block queries a database, it cannot immediately display or make available the obtained results. The results of PL/SQL processing are presented in two ways: the creation of a temporary table to be used by other applications, or a package called DBMS_OUTPUT, which, among other things, allows the display of a row with the contents of a variable or previously defined constants. We will see some examples later. Inside the DBMS_OUTPUT package there are two procedures used to display the contents of fields/variables. One is called enable, and
298
PL/SQL—Chapter 15
the other is put_line. For them to work correctly, it is necessary to adjust a SQL*Plus variable called SERVEROUTPUT to the value ON. Here are some examples using the control structures and the creation of variables. Initially, connected as Scott, we will create a SQL*PLUS table with the following structure:
Figure 15.4: Using the control structures.
If you have previously created a table with this name, and want to execute these examples, delete the records inserted in the table with the DELETE FROM TEMPTABLE command before executing the next example, or create a table with another name. Testing the PL/SQL blocks in SQL*PLUS requires at least two specific commands: GET and @. To configure a PL/SQL block that was previously written as a text file to the execution buffer of SQL*Plus, use the following command:
299
Chapter 15—PL/SQL
Syntax: GET name_of_block
Example: SQL>GET c:\prog1.sql
To execute a loaded block, use the slash key (/) or the RUN command. This lists and executes the block. To execute a block without displaying a list of the commands, use the following format of the command: Syntax: @name_of_block
Example: @c:\prog1.sql
Practical Examples The rest of this chapter gives you some examples of the functionality of the control structures. The first example shows the WHILE command. It displays the creation of a variable called I, to which the value zero is assigned. Then, the WHILE command uses it to execute a loop 11 times, inserting rows in the TEMPTABLE table: --test1.sql declare i int : = 0; begin while i <=10 loop insert into temptable (column1, column2) values (i, sysdate); i := i+1;
300
PL/SQL—Chapter 15 end loop; end;
Note the extra space between the “:” and “=” in the expression “i int : = 0;” . Also note we are using the temptable name with the columns of the TEMP1 table. To view the result of the program, use SQL*Plus. In our example, the files were created with Notepad and written to the C:\oracle directory with the .sql extension.
Figure 15.5: An error in the block’s execution.
An error message is issued when a logic or typing error occurs. In this case, you correct the program and execute it again. Notice that another error appears; this is because the name of the table used in INSERT INTO is incorrect. Change it to TEMP1 and execute the program:
301
Chapter 15—PL/SQL SQL> @c:\oracle\exemp1.sql 10 / PL/SQL procedure successfully completed. SQL> select * from temp1; COLUMN1 COLUMN2 --------------0 FEB-27-00 1 FEB-27-00 2 FEB-27-00 3 FEB-27-00 4 FEB-27-00 5 FEB-27-00 6 FEB-27-00 7 FEB-27-00 8 FEB-27-00 9 FEB-27-00 10 FEB-27-00 11 rows selected.
If the program is executed again, another 11 records will be written. The next example is the same as the previous one, except that it uses the FOR command to execute the loop. Its advantage is that you don’t have to control the incrementing of the counter variable through programming: --EXEMP2.sql declare i int := 0; begin FOR I IN 1..10 loop insert into temp1 (column1, column2) values (i, sysdate);
302
PL/SQL—Chapter 15 end loop; end;
The following example adds a conditional test to the previous example. It inserts only the records with a code that is a multiple of 3. To do that, you use the MOD function, which divides the value of I by 3 and, if the remainder is zero, inserts the row: --EXEMP3.sql declare i int := 0; begin FOR I IN 1..10 loop IF MOD(I,3)=0 THEN insert into temp1 (column1, column2) values (i, sysdate); END IF; end loop; end;
This is the result (shown only at the end of the listing for the SELECT command): COLUMN1 COLUMN2 --------------3 FEB-27-00 6 FEB-27-00 9 FEB-27-00 24 rows selected.
In the next example, an ELSE clause is added to the IF command. If the value of I is a multiple of 3, the record will be inserted, with the value of I and the system date. If not, a computation is made and the value of I*50 is written to the first field, and the system date is added to the value of I in the second field:
303
Chapter 15—PL/SQL --EXEMP4.sql declare i int := 0; begin FOR I IN 1..10 loop IF MOD(I,3)=0 THEN insert into temp1 (column1, column2) values (i, sysdate); ELSE insert into temp1 (column1, column2) values (i*50, sysdate+I); END IF; end loop; end;
Here is the listing (just the new records): COLUMN1 COLUMN2 --------------3 FEB-27-00 6 FEB-27-00 9 FEB-27-00 50 FEB-28-00 100 FEB-29-00 3 FEB-27-00 200 MAR-02-00 250 MAR-03-00 6 FEB-27-00 350 MAR-05-00 400 MAR-06-00 9 FEB-27-00 500 MAR-08-00 34 rows selected.
304
PL/SQL—Chapter 15
This chapter introduced the PL/SQL language and its components and command structures. The next chapter discusses triggers, which are used to execute routines.
305
Chapter 16
Triggers Using triggers is one of the most practical ways to implement routines, thus granting integrity of data or operations. Triggers are routines or procedures that are used when an INSERT, UPDATE, or DELETE command is executed in a table or a view. The name “trigger” is appropriate, as these are triggered whenever the above-mentioned commands are executed. In Oracle8i they can be written in PL/SQL, Java, or even in C. A trigger is automatically executed without any action required by the user. A stored procedure, on the other hand, needs to be explicitly invoked. This is the main difference between triggers and stored procedures. Database
Applications UPDATE t SET . . . ;
INSERT INTO t . . . ;
DELETE FROM t . . . ;
Table t
Update Trigger BEGIN
. . .
Insert Trigger BEGIN
. . .
Delete Trigger BEGIN
. . .
Figure 16.1: The anatomy of a trigger.
307
Chapter 16—Triggers
The major application of a trigger is to create consistencies and access restrictions to the database, as well as implement security routines. Instead of giving control of the application to the table itself, triggers execute these controls, providing much more security to the handling of the database. Triggers are also used to:
: : : :
Create the contents of a column derived from other columns. Create validation mechanisms involving searches in multiple tables. Create logs to register the use of a table. Update other tables as a result of inclusions or changes in the current table.
A trigger can execute the commands contained in its blocks, or enable the stored procedures to execute certain tasks. A trigger is associated to a table and, in some cases, to a view. When a view is used, the base table triggers are normally enabled. A trigger can perform the role of a constraint, forcing an integrity rule. If the task can be performed both by triggers and constraints, your first option should be a constraint. In this case, the triggers should be used only when a referential integrity rule cannot be executed using the NOT NULL, UNIQUE KEY, PRIMARY KEY, FOREIGN KEY, CHECK, DELETE CASCADE, DELETE SET, and NULL constraints.
Restrictions A trigger cannot execute the COMMIT, ROLLBACK, or SAVEPOINT commands. It also cannot call procedures or functions that execute those tasks. The SELECT command can be used only with the INTO clause. A row-level trigger cannot read or change the contents of a table that is being modified. This type of table is one in which the 308
Triggers—Chapter 16
contents are being changed by an INSERT, DELETE, and UPDATE command, and the command has not been completed. In other words, it is not yet written with COMMIT. The size of the trigger or the text of the commands cannot exceed 32 KB.
Components of a Trigger A trigger has three parts: 1. SQL command that activates the trigger (triggering event) The trigger can be activated by a SQL command or by a user event. In a table, it can be triggered by the INSERT, UPDATE, or DELETE commands. In a schema object, it can be triggered through the CREATE, ALTER, or DROP commands, when the database is loaded or shut down, or through an error message. The INSERT, DELETE, and UPDATE commands enable a trigger. The same trigger can be invoked in more than one situation, i.e., only when an INSERT command is executed, or when an INSERT or DELETE command is executed. 2. Trigger restriction Represented by the WHEN clause, it specifies what condition must be true for the trigger to be triggered. 3. Trigger action The PL/SQL block, or Java or C routine executed by the trigger.
309
Chapter 16—Triggers
REORDER Trigger AFTER UPDATE OF parts_on_hand ON inventory
Triggering Statement
WHEN (new.parts_on_hand
Trigger Restriction
FOR EACH ROW DECLARE NUMBER X; BEGIN SELECT COUNT(*) INTO X FROM pending_orders WHERE part_no=:new.part_no;
Triggered Action
/* a dummy variable for counting */ /* a query to find out if part has already been */ /* reordered-if yes, x=1, if no, x=0 */
IF x = 0 /* part has not been reordered yet, so reorder */ THEN INSET INTO pending_orders VALUES (new.part_no, new.reorder_quantity, sysdate); /* part has already been reordered */ END IF; END;
Figure 16.2:
Example of a trigger.
Types of Triggers Oracle8i has four types of triggers, depending on the application:
: : : :
Table triggers applied to DML commands. INSTEAD OF triggers applied to views. SYSTEM EVENT triggers applied to the database in the startup, shutdown, and error handling operations. USER EVENT triggers applied to a user or object schema.
Table Triggers There are two distinct types of triggers that can be used in a table. The first type, statement-level, is executed only once when a triggering event occurs. The other type, row-level, is used in every row of the table processed by the SQL command.
310
Triggers—Chapter 16
A trigger can be activated before or after the execution of an activation command (INSERT, DELETE, and UPDATE). A table can contain up to 12 triggers associated with the activation commands and the triggering event. There are six row-level triggers, and six statement-level triggers:
: : : : : :
BEFORE INSERT AFTER INSERT BEFORE UPDATE AFTER UPDATE BEFORE DELETE AFTER DELETE
When a trigger is defined, you can specify whether the trigger must occur before or after the triggering command. The BEFORE trigger is used in situations where the trigger action could determine if the trigger itself should be executed, or when you need some preprocessing before executing the command. The AFTER trigger is triggered only after the execution of the associated triggering command.
Statement-Level Trigger Statement-level triggers are triggered only once. For example, when an UPDATE command updates 15 rows, the commands contained in the trigger are executed only once, and not with every processed row.
Row-Level Trigger The commands of row-level triggers are executed on all the rows that are affected by the command that enabled the trigger.
311
Chapter 16—Triggers
INSTEAD OF Triggers The INSTEAD OF trigger is available only in the Enterprise version of Oracle. Triggers are a good way to change views that cannot be directly changed with the SQL DML commands (INSERT, UPDATE, and DELETE). These triggers are called INSTEAD OF triggers, because, unlike other triggers, Oracle calls the trigger itself rather than executing an instruction through it.
System Event and User Event Triggers Triggers can be associated with system or schema object events of a user. The types available are:
: : : : : : :
System events Database startup and shutdown Server error message events User events User logon and logoff DDL commands (CREATE, ALTER, and DROP) DML commands (INSERT, DELETE, and UPDATE)
The system event triggers can be defined at the database or schema level. For example, when you want to create a trigger that is activated when the database is loaded, you can create a trigger with this structure: CREATE TRIGGER startupDB ON DATABASE STARTUP BEGIN .. commands;
312
Triggers—Chapter 16 ... END;
System event triggers are triggered during the startup or shutdown of the database, and also by error messages. These are the types available: STARTUP
SHUTDOWN
SERVERERROR
These are triggered when the database opens an instance. These triggers include attributes such as the system event, instance number, and database name. These are triggered immediately before the database starts the shutdown process. These triggers include attributes such as system event, instance number, and database name. These are triggered whenever an error occurs. These triggers include attributes such as the system event and the error number.
The user event triggers occur when a user logs on, logs off, or executes DDL or DML commands. The attributes of the LOGON and LOGOFF triggers are the system event and the user name: LOGON
This is triggered after the user connection.
LOGOFF
This is triggered when the user starts his or her connection.
DDL command triggers, which are associated to a database or schema, have attributes such as the system event, the type of schema object, and the name: BEFORE CREATE and AFTER CREATE BEFORE ALTER and AFTER ALTER BEFORE DROP and AFTER DROP
These are triggered when a schema object is created. These are triggered when a schema object is modified. These are triggered when a schema object is eliminated from the schema or database.
313
Chapter 16—Triggers
Creating a Trigger A trigger is created with the CREATE TRIGGER command. It has the following syntax: Syntax: CREATE [OR REPLACE] TRIGGER [schema.] trigger {BEFORE | AFTER | INSTEAD OF} { DELETE | INSERT | UPDATE [OF column [, column] ...] } [OR { DELETE | INSERT | UPDATE [OF column [, column] ... ] } ] ... ON [schema.] {table | view} [ [REFERENCING { OLD [AS] old | NEW [AS] new} ...] FOR EACH {ROW | STATEMENT} [WHEN (condition)] ] pl/sql_block
Arguments: OR REPLACE Re-creates an existing trigger. You use this option to change the definition of an existing trigger without having to delete it first. schema This is the schema that will contain the trigger. If schema is omitted, Oracle will create the trigger in the user’s schema. trigger The name of the trigger to be created. BEFORE Makes Oracle activate the trigger before executing the triggering command. For row triggers, this is the individual triggering before each affected row is changed. You cannot specify a BEFORE trigger in a view or object view. 314
Triggers—Chapter 16
AFTER Makes Oracle activate the trigger after the execution of a triggering command. You cannot specify an AFTER trigger in a view or object view. INSTEAD OF Makes Oracle activate the trigger instead of executing the triggering command. As the default, the INSTEAD OF triggers are enabled in each row. INSTEAD OF is a valid option only for views; you cannot specify an INSTEAD OF trigger in a table. DELETE Makes Oracle activate the trigger whenever a DELETE command eliminates rows in a table. INSERT Makes Oracle activate the trigger whenever an INSERT command adds a row to the table. UPDATE Makes Oracle activate the trigger whenever an UPDATE command changes the value in one of the columns specified in the OF clause. If omitted, Oracle will activate the trigger whenever an UPDATE command changes a value in any column of the table. You cannot specify an OF clause with an INSTEAD OF trigger. Oracle activates the INSTEAD OF triggers whenever an UPDATE changes the value of any column in the view. You cannot specify nested tables or LOB columns in OF clauses. ON Specifies the schema and the name of the table (table) or the view (view) of one of the following parameters when the trigger is created: table, object table, view, or object view. If schema is omitted, Oracle assumes the table is in its own schema. You are allowed to create triggers in indexed tables. You can also create a trigger in a table of the SYS schema. table The name of a table or an object table.
315
Chapter 16—Triggers
view The name of a view or an object view. REFERENCING Specifies the correlation names. You can use the correlation names in the PL/SQL block, and in the WHEN clause in a row trigger, specifically referencing the new and old values of the current row. The default correlation names are OLD and NEW. If your row trigger is associated to a table called OLD or NEW, use this clause to specify different names for the correlation (don’t confuse the table name with the correlation name). If a trigger is defined as an object or view table, OLD and NEW refer to the object instances. FOR EACH ROW Designates a trigger such as a row trigger. Oracle triggers a row trigger for each row that is affected by a triggering command, which meets the optional constraints conditions defined in the WHEN clause. Except for the INSTEAD OF triggers, if this clause is omitted, the trigger is a triggering command. Oracle triggers a triggering command only once, when the triggering command is submitted, as long as the optional conditions of the trigger constraint are met. The INSTEAD OF triggers are implicitly enabled for each row. WHEN (condition) Specifies the trigger restriction, which is a SQL condition that must be met before Oracle can activate the trigger. You can specify a trigger restriction only for a row trigger. Oracle evaluates this condition for every row affected by the triggering command. You cannot specify trigger restrictions for the INSTEAD OF trigger. You can reference object columns and their attributes, VARRAY, nested tables, or LOB columns. It is not possible to call PL/SQL functions or methods in trigger restrictions.
316
Triggers—Chapter 16
pl/sql_block The PL/SQL block executed by Oracle to activate the trigger. NOTE: The PL/SQL block of a trigger cannot contain SQL transaction control commands (COMMIT, ROLLBACK, SAVEPOINT, and SET CONSTRAINT).
Modifying a Trigger A trigger cannot be directly modified. To change it you must re-create it with the CREATE command. If a trigger had its privileges granted to other users, they remain valid as long as the trigger exists.
Enabling/Disabling a Trigger When a trigger is created, it is automatically enabled and is triggered whenever the triggering command and the execution command is true. To disable the execution of the trigger, use the ALTER TRIGGER command with the DISABLE clause. To enable it again, use the ENABLE clause: Syntax: ALTER TRIGGER name DISABLE/ENABLE;
Example: ALTER TRIGGER change_sal DISABLE;
317
Chapter 16—Triggers
Deleting a Trigger To delete a trigger, use the DROP TRIGGER command: Syntax: DROP TRIGGER name_of_trigger;
This removes the trigger structure from the database and withdraws the privileges that were granted to other users.
References to Columns Inside a Trigger You can access the value of a column inside a row-level trigger. Depending on the operation that is being performed, you may need to precede the column name with :new or :old. This is necessary because you may be able to obtain both the old and new values.
: : :
For an INSERT command, the values of the fields that will be written must be preceded by :new. For a DELETE command, the values of the row fields that are being processed must be preceded by :old. For an UPDATE command, the original value that is being written is accessed with :old. The new values that will be written must be preceded by :new.
Take a look at this example, which determines whether the value inserted is greater than 10000: IF :new.Sal > 10000 (commands)
The following determines whether the new value attributed to the field is greater than the old value: IF :new.Sal < :old.Sal (commands)
318
Triggers—Chapter 16
The old and new values are available in BEFORE and AFTER triggers.
Validating the Data Entry If you are using SQL*Plus to create triggers, you will certainly notice its limitations as a program editor. Use a processing editor instead, such as Notepad, and cut and paste to insert data in a command row of SQL*Plus. In the following example we will determine a maximum value for the Salary field. No employee can earn more than $8,000. In addition to activating the trigger on the insert operation, thus preventing a new employee from earning more than the limit, the update routines must be checked to make sure the salary of the existing employees is not changed to values that are not allowed. When the UPDATE command is selected, the table columns are displayed, and the ones that changed can be marked and triggered when there are updates. In this example, the Sal column must be marked. Since the trigger is a row-level trigger, For Each Row must be marked, and the OLD AS and NEW AS fields must be filled out. After entering this information, click on the Body tab, and enter the following command block between BEGIN and END: if :new.sal > 8000 then raise_application_error(-20000,’Error checking sal/Incorrect Salary’); end if;
The IF command tests Sal. If the column’s content is greater than $8,000, an internal procedure called raise_application_error is enabled. This procedure returns an error message for the application or subprogram that invoked it. Specify the code –20000, a comma, and the appropriate error message.
319
Chapter 16—Triggers
A new row will not be written until the restriction imposed by the trigger is met.
Compilation Errors Many errors can occur during the creation of a trigger. Two common situations are typing errors or the use of improper commands. The following trigger, created directly in SQL*PLUS, will return an error message: SQL> CREATE TRIGGER TESTASAL 2 BEFORE INSERT OR UPDATE OF SAL 3 ON SCOTT.EMP 4 FOR EACH ROW 5 BEGIN 6 IF :NEW.SAL > 8000 7 RAISE_APPLICATION_ERROR(-20000,’INCORRECT VALUE’) 8 END IF; 9 END; 10/
After executing the command, a message is displayed: Note: Trigger created with compilation errors.
To view the error that occurred in the last command executed, use the SHOW ERRORS view. Take a look at the following: SQL> SHOW ERRORS; Errors for TRIGGER TESTASAL:
320
Triggers—Chapter 16 ROW/COL ------3/4
ERROR -----------------------------------------------------------PLS-00103: Encountered the symbol “RAISE_APPLICATION_ERROR” when expecting one of the following: * & - + / mod rem then an exponent (**) and or The symbol “*” was substituted for “RAISE_APPLICATION_ERROR” to continue.
4/4
PLS-00103: Encountered the symbol “END” when expecting one of the following: . ( * % & - + / mod rem then an exponent (**) and or
Taking another look at the code, you will note the failure to include the THEN clause in the IF command. To correct this error, eliminate the trigger and create it again: SQL> DROP TRIGGER TESTASAL; Trigger dropped. SQL> CREATE TRIGGER TESTASAL 2 BEFORE INSERT OR UPDATE OF SAL 3 ON SCOTT.EMP 4 FOR EACH ROW 5 BEGIN 6 IF :NEW.SAL > 8000 THEN 7 RAISE_APPLICATION_ERROR(-20000,’INCORRECT VALUE’); 8 END IF 9 END; 10 / Trigger created.
321
Chapter 16—Triggers
Now it’s time to test our trigger to see if it is working properly. Let’s try to give Smith a pay raise to $30,000: SQL> update emp 2 set sal=30000 3 where ename=’SMITH’; update emp * ERROR on row 1: ORA-20000: INCORRECT VALUE ORA-06512: in “SCOTT.TESTASAL”, row 3 ORA-04088: error during the execution of trigger ‘SCOTT.TESTASAL’
Note the text of error 20000 gives the reason for the error. If you were using a graphical interface to include or update the record, you would see a Windows message box. Now let’s try a smaller pay raise: SQL> UPDATE EMP 2 SET SAL = 2000 3 WHERE ENAME=’SMITH’; 1 row updated.
The record was successfully updated, because the trigger condition was met.
Replicating with Triggers Triggers are an efficient mechanism to replicate data among tables. We can easily create triggers that insert, delete, or modify another table based on the operations performed in the current table.
322
Triggers—Chapter 16
To create the replication trigger, we will use the AFTER INSERT mode. This mode enables the trigger after including the new record in the current table. Using data obtained through new.NameOfField, we insert the new record in the NEWEMP2 table, which was created in a previous chapter of this book. If this table does not exist, you should create a table with the same structure as the EMP table, but without the Comm column. CREATE TRIGGER REP_INS AFTER INSERT ON scott.EMP FOR EACH ROW BEGIN INSERT INTO scott.NEWEMP2 VALUES (:NEW.EMPNO, :NEW.ENAME, :NEW.JOB, :NEW.MGR, :NEW.HIREDATE, :NEW.SAL, :NEW.DEPTNO); END;
Now, we insert a record in the EMP table and check the results in the NEWEMP2 table: SQL> INSERT INTO EMP 2 VALUES 3* (8000,’PALHARES’,’CLERK’,7782,’05/10/1999’,2000,0,30) 1 row created. SQL> SELECT * FROM NEWEMP2 WHERE EMPNO=8000; EMPNO ----8000
ENAME JOB MGR -------- ----- ---PALHARES CLERK 7782
HIREDATE SAL -------- ---05/10/99 2000
DEPTNO -----30
Now let’s create another row, but omit the value for the Hiredate column:
323
Chapter 16—Triggers SQL> INSERT INTO EMP 2 (EMPNO,ENAME,JOB,MGR,SAL,DEPTNO) 3 VALUES (8001,’TREVOR’,’ANALYST’,7782, 3000,30); 1 row created. SQL> SELECT * FROM NEWEMP2; EMPNO ----7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 8000 8001
ENAME -----SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER PALHARES TREVOR
JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK CLERK ANALYST
MGR ---7902 7698 7698 7839 7698 7839 7839 7566 7698 7788 7698 7566 7782 7782 7782
16 rows selected.
Take a look at the following example: SQL> CREATE TRIGGER REP_DEL 2 BEFORE DELETE ON EMP 3 FOR EACH ROW 4 BEGIN 5 DELETE FROM NEWEMP2
324
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81 05/01/81 06/09/81 04/19/87 11/17/81 09/08/81 05/23/87 12/03/81 12/03/81 01/23/82 05/10/99
SAL ---800 1600 1250 2975 1250 2850 2450 3000 5000 1500 1100 950 3000 1300 2000 3000
DEPTNO -----20 30 30 20 30 30 10 20 10 30 20 30 20 10 30 30
Triggers—Chapter 16 6 WHERE EMPNO= :OLD.EMPNO; 7 END; 8/ Trigger created.
Now we delete the record of employee Palhares from the EMP table: SQL> DELETE FROM EMP WHERE EMPNO=8000; 1 row deleted.
Now let’s check if the employee record remains in the NEWEMP2 table: SQL> SELECT * EMPNO ENAME ----- -----7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7876 ADAMS 7900 JAMES 7902 FORD 7934 MILLER 8001 TREVOR
FROM NEWEMP2; JOB MGR --------- ---CLERK 7902 SALESMAN 7698 SALESMAN 7698 MANAGER 7839 SALESMAN 7698 MANAGER 7839 MANAGER 7839 ANALYST 7566 PRESIDENT SALESMAN 7698 CLERK 7788 CLERK 7698 ANALYST 7566 CLERK 7782 ANALYST 7782
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81 05/01/81 06/09/81 04/19/87 11/17/81 09/08/81 05/23/87 12/03/81 12/03/81 01/23/82
SAL ---800 1600 1250 2975 1250 2850 2450 3000 5000 1500 1100 950 3000 1300 3000
DEPTNO -----20 30 30 20 30 30 10 20 10 30 20 30 20 10 30
15 rows selected.
Everything worked fine.
325
Chapter 16—Triggers
Obtaining Information about a Trigger Oracle has a view in the data dictionary, accessible only by those with the DBA privilege, that contains data from all the triggers created for the database in use. This table is called DBA_TRIGGERS. Following is a description of its contents (using System/manager to access this table): SQL> desc dba_triggers; Name ----------------OWNER TRIGGER_NAME TRIGGER_TYPE TRIGGERING_EVENT TABLE_OWNER TABLE_NAME REFERENCING_NAMES WHEN_CLAUSE STATUS DESCRIPTION TRIGGER_BODY
Null? -------NOT NULL NOT NULL
NOT NULL NOT NULL
Type -------------VARCHAR2(30) VARCHAR2(30) VARCHAR2(16) VARCHAR2(26) VARCHAR2(30) VARCHAR2(30) VARCHAR2(87) VARCHAR2(2000) VARCHAR2(8) VARCHAR2(2000) LONG
To view the user’s triggers, you use the view USER_TRIGGERS: SQL> describe user_triggers; Name Null? ----------------- ----TRIGGER_NAME TRIGGER_TYPE TRIGGERING_EVENT TABLE_OWNER BASE_OBJECT_TYPE TABLE_NAME COLUMN_NAME REFERENCING_NAMES 326
Type -------------VARCHAR2(30) VARCHAR2(16) VARCHAR2(75) VARCHAR2(30) VARCHAR2(16) VARCHAR2(30) VARCHAR2(4000) VARCHAR2(128)
Triggers—Chapter 16 WHEN_CLAUSE STATUS DESCRIPTION ACTION_TYPE TRIGGER_BODY
VARCHAR2(4000) VARCHAR2(8) VARCHAR2(4000) VARCHAR2(11) LONG
SQL> select trigger_name,trigger_body from user_triggers where trigger_name=’REP_INS’; TRIGGER_NAME --------------------TRIGGER_BODY --------------------REP_INS BEGIN UPDATE NEWEMP2 SET EMPNO = :NEW.EMPNO, ENAME = :NEW.ENAME, JOB
In this chapter you learned about triggers and the events that trigger them. You also learned about their importance to those who develop database applications, and how they assist with data security and minimize network traffic. The next chapter presents stored procedures, which are groups of commands that must be called.
327
Chapter 17
Stored Procedures and Functions A stored procedure is a group of SQL and PL/SQL commands that execute certain tasks. In contrast to a trigger, which is automatically executed when a trigger event occurs, the user must call a procedure either from a program or manually. While a trigger is associated to only one table or user, several users or applications can use a procedure. A procedure is completely portable among platforms in which Oracle is executed. A function is similar to a stored procedure. The main difference between them is that a function returns a value, and a stored procedure doesn’t.
329
Chapter 17—Stored Procedures and Functions
Database Applications Program code Program code
Stored Procedure
HIRE_EMP (...); Program code ode
HIRE_EMP (...); Program code
BEGIN
HIRE_EMP (...); END;
Progr
Program code
Program code HIRE_EMP (...); Program code
Figure 17.1: A procedure receives values through parameters.
Database
Procedure HIRE_EMP (name VARCHAR2, job VARCHAR2, mgr NUMBER, hiredate DATE, sal NUMBER, comm NUMBER, deptno NUMBER)
BEGIN INSERT INTO emp VALUES (emp sequence .NEXTVAL, name, job, mgr hiredate, sal, comm, deptno);
Figure 17.2: The anatomy of a procedure.
330
END;
Stored Procedures and Functions—Chapter 17
Creating a Stored Procedure A stored procedure has two parts: a specification section and the procedure body. The CREATE PROCEDURE command, described below, is responsible for the creation of procedures: Syntax: CREATE [OR REPLACE] PROCEDURE [schema.] procedure [ (argument [IN | OUT | IN OUT] datatype [, argument [IN | OUT | IN OUT] datatype] ...)] {IS|AS} {pl/sql_subprogram_body | external_body} external_body ::= EXTERNAL LIBRARY [schema.]library_name [NAME external_proc_name] [LANGUAGE language_name] [CALLING STANDARD [C | PASCAL] PARAMETERS (external_parameter_list) [WITH CONTEXT] external_parameter_list ::= { { parameter_name [property] | RETURN property } [BY REF] [external_datatype] | CONTEXT } [, { parameter_name [property] | RETURN property } [BY REF] [external_datatype]] ... property ::= INDICATOR | LENGTH | MAXLEN | CHARSETID | CHARSETFORM
Arguments: OR REPLACE Re-creates the procedure if it already exists. Use this option to change the definition of an existing procedure without canceling, re-creating, or revalidating privileges of the database objects that were previously granted to the procedure. If a procedure is redefined, Oracle will recompile it. Users with previously granted privileges can still access the redefined procedure without revalidating the privileges.
331
Chapter 17—Stored Procedures and Functions
schema The schema that will contain the procedure. If schema is omitted, Oracle creates the procedure in the current schema. procedure The name of the procedure to be created. argument The name of a procedure argument. If the procedure does not accept arguments, you can omit the parentheses after its name. IN Specifies that a value is determined for the argument when the procedure is called. OUT Specifies that the procedure returns a value for this argument in its calling environment after the execution. IN OUT Specifies that a value must be determined for the argument when the procedure is called and that the procedure returns a value in its calling environment after the execution. datatype The argument’s data type. As long as no specifier is given, an argument can be any data type supported by PL/SQL. The data types are specified without any length, precision, or scale. For example, varchar2(10) is not valid, but varchar2 is. Oracle derives the length, precision, or scale of an argument from the environment from which the procedure is called. IS pl/sql_subprogram_body The procedure definition. Procedure definitions are written in PL/SQL. AS external_body Identifies an external procedure in 3GL, stored in a library that can be shared. The AS external_body clause is the interface between the PL/SQL and the external procedure.
332
Stored Procedures and Functions—Chapter 17
LIBRARY Specifies the shared library in which the external procedure is stored. The library must have EXECUTE privileges. library_name A PL/SQL identifier. Putting library_name in double quotes makes it case sensitive but is not required. NAME external_procedure_name Specifies the external procedure to be called. Putting external_procedure_name inside double quotes makes it case sensitive but is not required. If the name is omitted, the default is the PL/SQL subprogram. LANGUAGE Specifies the 3GL in which the external procedure was written. Currently, the only language supported is C. When the name is omitted, the default is C. CALLING STANDARD Specifies the calling default language (C or Pascal) in which the external procedure was compiled. When the calling default is omitted, the default is C. WITH CONTEXT Specifies that a context pointer will be the first parameter transferred to the external procedure. The context is seamless to the external procedure, but it is available for access functions called by the external procedure. PARAMETERS Specifies the positions and data types of the parameters transferred to the external procedure. It can also specify the parameter properties, such as current and maximum length, and preferred method of parameter transference (by value or by reference). To build the CREATE PROCEDURE command inside an Oracle precompiler program, you must end the command with the keyword END-EXEC, followed by the terminator specified in the command of the specific SQL language.
333
Chapter 17—Stored Procedures and Functions
In the following example, we create a stored procedure that gives all the employees a 10% pay increase. This stored procedure does not require any parameters. Using SQL*Plus, enter the following: SQL> CREATE OR REPLACE PROCEDURE RAISE_SAL2 2 BEGIN 3 UPDATE NEWEMP 4 SET SAL=SAL*1.1; 5 END; 6 / Error: procedure created with compilation errors.
We purposely introduced some errors when creating the stored procedure. When it was compiled, a failure was detected, and an error message was displayed. In SQL*Plus, use the SHOW ERRORS command to see what happened: SQL> SHOW ERRORS; Errors for LINE/COL -------2/1
PROCEDURE RAISE_SAL2: ERROR ----------------------------------------------PLS-00103: Encountered the symbol “BEGIN” when expecting one of the following: ( ; is with as compress compiled wrapped The symbol “is” was substituted for “BEGIN” to continue.
In this case, the problem was that the keyword IS was missing. Re-create the procedure, typing the following: SQL> CREATE OR REPLACE PROCEDURE increase1 2 IS 3 BEGIN
334
Stored Procedures and Functions—Chapter 17 4 5 6 7 Procedure
UPDATE NEWEMP2 SET SAL=SAL*1.1; END; / created.
Executing a Stored Procedure A stored procedure is executed by making a call to it. Inside a trigger or another stored procedure, specify the name of the procedure and its respective parameters. For example: RAISE_SAL(20,12)
From SQL*PLUS a procedure can be called with the EXECUTE command. Let’s test this option: SQL> EXEC increase1; Procedure PL/SQL successfully completed.
Note that all the salaries were increased by 10%: SQL> SELECT * EMPNO ENAME ----- -----7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7876 ADAMS
FROM NEWEMP2; JOB MGR --------- ---CLERK 7902 SALESMAN 7698 SALESMAN 7698 MANAGER 7839 SALESMAN 7698 MANAGER 7839 MANAGER 7839 ANALYST 7566 PRESIDENT SALESMAN 7698 CLERK 7788
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81 05/01/81 06/09/81 04/19/87 11/17/81 09/08/81 05/23/87
SAL ------880 1760 1375 3272.50 1375 3135 2695 3300 5500 1650 1210
DEPTNO -----20 30 30 20 30 30 10 20 10 30 20
335
Chapter 17—Stored Procedures and Functions 7900 7902 7934 8001
JAMES FORD MILLER TREVOR
CLERK ANALYST CLERK ANALYST
7698 7566 7782 7782
12/03/81 12/03/81 01/23/82
1045 3300 1430 3300
30 20 10 30
15 lines selected.
Now we will create a procedure with parameters. This procedure also increases employees’ salaries, but this time the pay raise is only for those in a particular department and the increase is a different percentage. A stored procedure can execute certain tasks without any information given to it. In other words, parameters are not necessary. For example, you can create a stored procedure that updates the table of employees, increasing the salary of all by 10%, or you can create a procedure using two parameters, such as the department code and the increase percentage. In this case, only the employees of the specified department will receive the indicated increase: SQL> CREATE PROCEDURE increase2 (vdept IN newemp2.deptno%type, 2 percentage number) 3 IS 4 BEGIN 5 update newemp2 6 set sal=sal*(1+percent/100) 7 where deptno=vdept; 8 END; 9 / Procedure created.
Note that the vdept parameter is based on the Deptno column of the NEWEMP2 table. According to the computation used, the value of the salary increase has to be entered as a whole number. For example, 21% must be specified as 21.
336
Stored Procedures and Functions—Chapter 17 SQL> exec increase2(30,21); Procedure PL/SQL successfully completed. SQL> select * EMPNO ENAME ----- -----7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7876 ADAMS 7900 JAMES 7902 FORD 7934 MILLER 8001 TREVOR
from newemp2; JOB MGR --------- ---CLERK 7902 SALESMAN 7698 SALESMAN 7698 MANAGER 7839 SALESMAN 7698 MANAGER 7839 MANAGER 7839 ANALYST 7566 PRESIDENT SALESMAN 7698 CLERK 7788 CLERK 7698 ANALYST 7566 CLERK 7782 ANALYST 7782
HIREDATE -------12/17/80 02/20/81 02/22/81 04/02/81 09/28/81 05/01/81 06/09/81 04/19/87 11/17/81 09/08/81 05/23/87 12/03/81 12/03/81 01/23/82
SAL ------880 2129.60 1663.75 3272.50 1663.75 3793.35 2695 3300 5500 1996.50 1210 1264.45 3300 1430 3993
DEPTNO -----20 30 30 20 30 30 10 20 10 30 20 30 20 10 30
15 lines selected.
Deleting a Stored Procedure To delete a stored procedure, use the DROP PROCEDURE command: Syntax : DROP PROCEDURE name
337
Chapter 17—Stored Procedures and Functions
Example: SQL> drop procedure raise_sal2; Procedure dropped.
Functions A function is similar to a stored procedure. The main difference between these two structures is that a function returns a value and a stored procedure doesn’t. Another difference is how a function can be called. It can return a value, be invoked through a SELECT command, and also be used in computations with another function of Oracle.
Creating a Function The CREATE FUNCTION command creates a function as an isolated schema object. You can also create a function as part of a package. Syntax: CREATE [OR REPLACE] FUNCTION [schema.]function [(argument [IN | OUT | IN OUT] datatype [, argument [IN | OUT | IN OUT] datatype] ...)] RETURN datatype {IS | AS} pl/sql_subprogram_body | external_body external_body ::= EXTERNAL LIBRARY [schema.]library_name [NAME external_proc_name] [LANGUAGE language_name] [CALLING STANDARD [C | PASCAL] PARAMETERS (external_parameter_list) [WITH CONTEXT] external_parameter_list ::= { { parameter_name [property] | RETURN property } [BY REF] [external_datatype] 338
Stored Procedures and Functions—Chapter 17 | CONTEXT } [, { parameter_name [property] | RETURN property } [BY REF] [external_datatype]] ... property ::= INDICATOR | LENGTH | MAXLEN | CHARSETID | CHARSETFORM
Arguments: OR REPLACE Re-creates the function if it already exists. Use this option to change the definition of an existing function, without canceling, re-creating, or revalidating the privileges of database objects previously granted in the function. If a function is redefined, Oracle will recompile it. Users to whom privileges were previously granted can still access the function in a redefined function without revalidating the privileges. schema This is the schema that will contain the function. If schema is omitted, Oracle creates the function in the current schema. function The name of the function to be created. argument The name of an argument of the function. If the function does not accept any arguments, you can omit the parentheses after its name. IN Specifies that a value must be determined for the argument when the function is called. This is the default. OUT Specifies that the function will determine the value for the argument. IN OUT Specifies that a value for the argument can either be provided by the user or be determined by the function. 339
Chapter 17—Stored Procedures and Functions
datatype The data type of an argument. An argument can be any data type supported by PL/SQL. The data type cannot specify the length, precision, or scale. Oracle derives the length, precision, or scale of an argument from the environment in which the function is called. RETURN datatype Specifies the return value for the data type of the function. Since every function must return a value, this is a required clause. The value returned can be any data type supported by PL/SQL. pl/sql_subprogram_body The function definition. Function definitions are written in PL/SQL. external_body_clause Identifies the external function to be registered. AS EXTERNAL Identifies an external function in 3GL, which is stored in a shared library. The AS EXTERNAL clause is the interface between PL/SQL and the external function. LIBRARY Specifies the shared library in which the external function is stored. You must have EXECUTE privileges in the library. library_name An identifier in PL/SQL. Putting library_name inside double quotes makes it case sensitive but is not required. NAME external_function_name Specifies the external function to be called. Putting external_function_name inside double quotes makes it case sensitive but is not required. If the name is omitted, the default will be the PL/SQL subprogram.
340
Stored Procedures and Functions—Chapter 17
LANGUAGE Specifies the 3GL in which the external function was written. Currently, the only language supported is C. If the name is omitted, the default is C. CALLING STANDARD Specifies the calling default language (C or Pascal) in which the external function was compiled. If the calling default is omitted, the default will be C. WITH CONTEXT Specifies that a context pointer will be the first parameter transferred to the external function. The context is seamless to the external function, but is available to the access functions called by the external function. PARAMETERS Specifies the positions and data types of the parameters transferred to the external function. It can also specify the parameter properties, such as current and maximum length, and preferred method for parameter transfer (by value or by reference). Here we will create a function that returns the number of employees in a certain department. To do that, the CREATE FUNCTION will use an argument containing the code of the specified department: CREATE OR REPLACE FUNCTION countemp (vdept in newemp2.deptno%type) RETURN number IS emptot number; BEGIN select count(*) into emptot from newemp2 where deptno=vdept; return emptot; END;
341
Chapter 17—Stored Procedures and Functions
Only the department code is inserted as an argument in this function. Then it specifies that the function returns a value of the data type number. A variable called emptot is created; it will receive the total number of employees in the department.
Executing a Function To display the result of a function in SQL*Plus, you use the SELECT command and specify the function name that will be queried in the DUAL table. Consider the following examples: SQL> select countemp(30) from dual; COUNTEMP(30) ---------------7 SQL> select countemp(10) from dual; COUNTEMP(10) ---------------3
If incorrect parameters or a different number of parameters are passed, execution errors will result. The following example shows an error caused by a missing parameter: SQL> select empnum from dual; select empnum from dual * ERROR at line 1: ORA-06553: PLS-306: wrong number or types of arguments in call to
342
Stored Procedures and Functions—Chapter 17
Here, the value is passed inside quotation marks: SQL> select countemp(“30") from dual; select countemp(“30") from dual * ERROR on line 1: ORA-00904: column name invalid
In this chapter, you’ve seen how a stored procedure can improve Oracle’s performance and how to use functions. As applications become more sophisticated, the use of stored procedures and functions will become more important. In the next chapter, we discuss packages, which allow the creation of several procedures and functions in a single file.
343
Chapter 18
Packages A package is a collection of database objects, such as stored procedures, functions, variables, constants, and cursors. A package may contain subprograms that can be called from a trigger, procedure, or function. A package is an important resource for the developer, because it allows him or her to better organize in modules the components of a system. For example, a package called Genemp can contain functions and stored procedures related to an employee table. Moreover, packages simplify the administration of privileges. A package also improves machine performance, because it simultaneously transfers several objects to the memory.
Package Structure A package has two sections: the specification section and the body section. They need to be created separately.
Specification Section The specification section is a type of summary for the contents of the package body. Physically, the specification section and package body are distinct objects. In this section, the names of functions and stored procedures are declared together with the variable and constant names, which are included in the initialization. The 345
Chapter 18—Packages
specification section is created with the CREATE PACKAGE command, as shown below: Syntax: CREATE [OR REPLACE] PACKAGE [schema.] package {IS | AS} pl/sql_package_spec
Arguments: OR REPLACE Re-creates the package specification if it already exists. Use this option to change the specification of an existing package without canceling, re-creating, or revalidating previously granted object privileges. If a package specification changes, Oracle recompiles it. Users with previously granted privileges can still access a redefined package without revalidating the privileges. schema The schema that will contain the package. If schema is omitted, Oracle creates the package in its own schema. package The name of the package to be created. pl/sql_package_spec The package specification. It can declare program objects. Package specifications are written in PL/SQL.
Package Body The package body contains the formal definition of all the objects referenced in the declaration section. The package body is created with the CREATE PACKAGE BODY command, as shown below: Syntax: CREATE [OR REPLACE] PACKAGE BODY [schema.] package {IS | AS} pl/sql_package_body
346
Packages—Chapter 18
Arguments: OR REPLACE Re-creates the body of the package if it already exists. Use this option to change the body of an existing package without canceling, re-creating, and revalidating previously granted object privileges. If a package body changes, Oracle recompiles it. Users with previously granted privileges can still access the package without revalidating the privileges. schema The schema that will contain the package. If schema is omitted, Oracle creates it in its own schema. package The name of the package to be created. pl/sql_package_body The body of the package. It can declare and define program objects. Package bodies are written in PL/SQL. The initialization section is optional, and is executed only when you specify the package for the first time. The procedure and function definition sections are where the PL/SQL code of these objects must be specified.
Using Navigator Rather than using the SQL commands, you can use the Navigator to create packages.
Creating a Package in Navigator To create a package in Navigator, first you need to enter Genemp as the name of the table and Scott as user: PACKAGE GENEMP IS PROCEDURE RAISE_SAL
347
Chapter 18—Packages (vdept IN newemp.deptno%type, vpercsal number); FUNCTION EMPNUM (vdept in newemp.deptno%type) RETURN number; END;
Creating the Body in Navigator To create a package body with the Navigator, select the Stored Program Unit folder, right-click on it, and select New. Then select Package Body. A dialog box asks for the name of this section and the owner. Enter Genemp as the name of the table and Scott as the user. The name entered for a package body must be the same as the name given in the specification section. A dialog box displays the section structure. Here, you specify the variables, constants, and the complete code of functions and stored procedures. Replace the structure with the following code: PACKAGE BODY GENEMP IS PROCEDURE RAISE_SAL (vdept IN newemp.deptno%type, vpercsal number) IS BEGIN update newemp set sal=sal*(1+vpercsal/100) where deptno=vdept; END; FUNCTION EMPNUM (vdept in newemp.deptno%type) RETURN number IS emptot number; 348
Packages—Chapter 18 BEGIN select count(*) into emptot from newemp where deptno=vdept; return emptot; END; END;
Referencing a Package Subprogram To access objects specified inside a package, precede the object with the package name: SQL> execute genemp.raise_sal(20,10); PL/SQL procedure successfully completed.
If a constant called refval was created in this package, the procedure used to access it would be the following: IF genemp.refval > x then ... END IF
The entire package is configured to memory when a procedure inside it is called for the first time.
Recompiling a Package You may want to consider recompiling a package manually, as this eliminates package recompilation during run time. This improves the performance and prevents problems during the execution of a task. To recompile one part of the package, use the ALTER
349
Chapter 18—Packages
PACKAGE command. To recompile only the body, use the BODY option: SQL> alter package genemp compile body; Package body altered.
Or you can recompile the entire package by omitting the BODY option: SQL> alter package genemp compile; Package altered.
You can also recompile using the Navigator. Right-click on the package, and select the Compile option.
Deleting a Package When a package is deleted, all the references made to it and its objects become invalid. Therefore, be very careful when doing this task. If it is specified inside a trigger, Oracle tries to recompile the package. If it does not find the package, an error warning is issued. To delete a package, you can either right-click on the package name and select the Delete option in the quick menu, or use the DROP PACKAGE command. Syntax: DROP PACKAGE [BODY] name
The BODY option deletes the body of the specified package, leaving the specification section unchanged. If this option is omitted, both sections of the package are deleted. The package body can be replaced and recompiled without affecting its own specification. The schema objects that reference the package elements don’t have to be recompiled, except when the specification is also replaced.
350
Packages—Chapter 18
Oracle Packages Oracle has dozens of packages containing procedures that extend its functionality. Most of them start with the prefix DBMS_, UTL_ DEBUG_ , or OUTLN_. For example, the DBMS_OUT package has several procedures to send messages from other procedures, packages, or triggers. During the designing and testing phase of a trigger, we can use the DBMS_OUTPUT package to check the contents of columns. Normally, packages have several procedures that are responsible for specific tasks. The procedures contained in DBMS_OUTPUT are: Routine ENABLE DISABLE PUT and PUT_LINE NEW_LINE GET_LINE and GET LINES
Description Enables the message display. Disables the message display. Puts a line in the buffer. Ends the line created with PUT. Recovers information from the buffer.
Following is an example of the use of the DBMS_OUTPUT package, which is called by a trigger that is enabled when any DML operation is performed in the NEWEMP2 table: CREATE OR REPLACE TRIGGER saldif BEFORE DELETE OR INSERT OR UPDATE ON newemp2 FOR EACH ROW WHEN (new.Empno > 0) DECLARE sal_diff number; BEGIN sal_diff := :new.sal - :old.sal; dbms_output.put(‘ Old: ‘ || :old.sal); dbms_output.put(‘ New: ‘ || :new.sal);
351
Chapter 18—Packages dbms_output.put_line(‘ Difference ‘ || sal_diff); END; /
To view the output, you must execute the SET SERVEROUTPUT ON command before performing any triggering operation: SQL> update newemp2 set sal=sal*1.3 where empno=7876; Old: 1100 New: 1430 Difference 330 1 line updated.
See the online manual for a complete list of Oracle8i packages. In this chapter we explained what a package is and its advantages to the developer. You also learned how to create and edit both parts of a package, as well as how to specify the objects it contains. The next chapter discusses the concept of cursors.
352
Chapter 19
Cursors When Oracle processes a SQL command, it opens an area in the memory called Private SQL Area. This area stores information responsible for executing the command. An identifier for this area—called a cursor—is created. When you use SQL*Plus to select database records, the SELECT command is sufficient to display the rows of tables or views that meet the specified criteria. Unfortunately, this is not true when you use PL/SQL. When a PL/SQL block, trigger, or stored procedure uses a SELECT command that returns more than one row, Oracle displays an error message and invokes the TOO_MANY_ ROWS exception. To resolve this problem, Oracle uses a mechanism called a cursor. (Do not confuse these cursors with the mouse pointer that you see on the screen.) For static SQL commands, there are two types of cursors: implicit and explicit. Oracle implicitly declares a cursor to all the DDL and DML commands that return only one row. For queries that return multiple rows, you have to explicitly create a cursor. The set of rows returned by a cursor is called a result set. The row that is being processed is called the current row. The current row inside the result set is identified by a cursor, which allows the individual processing of each of them. Oracle uses four commands to handle cursors. They are: DECLARE, OPEN, FETCH, and CLOSE. 353
Chapter 19—Cursors
Think of a cursor as a temporary file that stores and controls the rows returned by a SELECT command. SQL*Plus automatically generates cursors for the queries that are executed. In PL/SQL, however, the user needs to create explicit cursors. An implicit cursor that returns all the rows is created. In the following example, the SELECT command returns only the rows containing department 20 in the EMP table. In SQL*Plus a cursor that displays only those rows is automatically created. In this case, the cursor was implicitly created. select ename, deptno, sal from emp where deptno=20
Creating a Cursor Creating a cursor involves four steps: 1. Declaring the cursor—the cursor receives a name and is assigned a SELECT command. 2. Opening the cursor—the query is executed and the number of rows to be returned is determined. 3. Fetching—the row that is found is sent to the program in PL/SQL. 4. Closing the cursor—the Oracle resources allocated to the cursor are freed.
Declaring the Cursor The DECLARE command is used to declare a cursor. Syntax: DECLARE CURSOR cursor_name [(parameter[, parameter]...)] [RETURN return_type] IS SELECT COMMAND;
354
Cursors—Chapter 19
Arguments: cursor_name Name of the cursor to be created. return_type Represents a row or record in a table. A parameter must follow this syntax: name_of_parameter [IN] datatype [{:= | DEFAULT} expression]
Example: DECLARE CURSOR prim01 IS SELECT empno, ename, job, sal FROM emp WHERE deptno =30; CURSOR seg02 RETURN dept%ROWTYPE IS SELECT * FROM dept WHERE deptno = 20;
A cursor name cannot receive values or be used in an expression. The parameter of a cursor can be initialized with the default value: DECLARE CURSOR prim021 (quantity INTEGER DEFAULT 0, sale INTEGER ) IS SELECT ...
When declaring a cursor, you can specify the name and query that will be executed. This task is performed in the declaration section of a block. In the following example, a cursor called Display20 is created with a query that selects the employees of department 20: DECLARE CURSOR display20 IS SELECT ENAME ,DEPTNO,SAL FROM EMP WHERE DEPTNO=20 ORDER BY ENAME;
355
Chapter 19—Cursors
There is no limit to the number of cursors you can create, except for the memory that is allocated to each of them. In addition, as is the case with procedures and functions, cursors can receive parameters. In the next example, the department code is inserted by parameter: CURSOR displaydep (T_deptno number) IS SELECT ENAME ,DEPTNO,SAL FROM EMP WHERE DEPTNO=T_deptno ORDER BY ENAME;
Opening a Cursor The OPEN command must be used to provide parameters for the cursor. Unless default values are created for the parameters, each parameter must have a value assigned to it with the OPEN command. The opening of the cursor is the operation that performs the query and creates the result set, which is the group of rows that meets the query condition. A cursor is opened with the OPEN command: OPEN display30;
The cursor leaves the first row selected as the current row. Here are some other examples: DECLARE emp_name emp.ename%TYPE; salary emp.sal%TYPE; CURSOR test1 (name VARCHAR2, salary NUMBER) IS SELECT ... OPEN test1(emp_name, 3000); OPEN test1(‘Facciolla’, 1500); OPEN test1(emp_name, salary);
356
Cursors—Chapter 19
Attributes of an Explicit Cursor To manipulate the rows you need to use some attributes of the explicit cursor. These attributes return a value referring to the execution of a multiline query. When a cursor or variable is opened, the rows that satisfy the query are identified and form the result set. The rows of the result set are downloaded one at a time.
%FOUND After the opening and before the first fetch, the value of %FOUND is NULL. From then on, it returns TRUE when a DML command affects one or more rows, or SELECT INTO when it does not return any row: LOOP FETCH c1 INTO emp, my_sal, my_hiredate; IF c1%FOUND THEN — fetch successful ... ELSE — fetch successful EXIT; END IF; END LOOP;
%ISOPEN %ISOPEN returns TRUE when the cursor or variable is opened. Otherwise, it returns FALSE: IF c1%ISOPEN THEN — cursor is opened ... ELSE — cursor is closed OPEN c1; END IF;
357
Chapter 19—Cursors
%NOTFOUND %NOTFOUND returns TRUE when the last row of the cursor is processed and no other row is available. This is the same as finding the end of file. Before the first FETCH command, %NOTFOUND returns NULL. LOOP FETCH c1 INTO emp, my_sal, my_hiredate; EXIT WHEN c1%NOTFOUND; END LOOP;
%ROWCOUNT %ROWCOUNT returns the total number of rows returned by the FETCH command. Each time a FETCH command is executed, %ROWCOUNT is increased by 1. When the cursor is opened, %ROWCOUNT is zeroed. LOOP FETCH c1 INTO my_ename, my_deptno; IF c1%ROWCOUNT > 10 THEN ... END IF; ... END LOOP;
Attributes of an Implicit Cursor The attributes of an implicit cursor return information about the execution of the INSERT, UPDATE, DELETE, or SELECT INTO commands. The values of the cursor attributes always refer to the SQL command that was executed most recently. Before Oracle opens the SQL cursor, the attributes of the implicit cursors will have NULL in their fields.
358
Cursors—Chapter 19
%FOUND The attribute %FOUND contains the value NULL until a DML command is executed. From then on, it returns TRUE when a DML command affects one or more rows, or SELECT INTO does not return any row. DELETE FROM emp WHERE empno = emp; IF SQL%FOUND THEN — successful INSERT INTO new_emp VALUES (func, my_ename, ...);
%ISOPEN Oracle always closes a cursor after the SQL command is executed; therefore, %ISOPEN always generates FALSE.
%NOTFOUND %NOTFOUND is the opposite of %FOUND, and returns TRUE when an INSERT, UPDATE, or DELETE command does not affect any row, or when SELECT INTO does not return any row.
%ROWCOUNT %ROWCOUNT returns the number of rows affected by the INSERT, UPDATE, DELETE, or SELECT INTO commands. It returns 0 when the commands do not affect or return any row. DELETE FROM emp WHERE ... IF SQL%ROWCOUNT > 5 THEN ...commands... END IF;
Accessing the Cursor Rows After the cursor is opened with the OPEN command, the selected rows are available. PL/SQL uses the FETCH command to read the contents of a row. FETCH reads the value of each column of the
359
Chapter 19—Cursors
row that is specified by the SELECT command, and assigns a variable. This can be seen as an equivalent to the SELECT INTO command. The FETCH command recovers one row at a time from the result set. After each FETCH, the cursor goes to the next row of the result set: FETCH test1 INTO my_empno, my_ename, my_deptno;
In the next example we use Oracle’s DBMS_OUTPUT package to demonstrate the results: LOOP FETCH display30 INTO t_ename, t_deptno, t_sal; EXIT WHEN display30%notfound; DBMS_OUTPUT.PUT_LINE(t_ENAME // ´ ´ //TO_CHAR(T_DEPTNO) // ´ ´ / / TO_CHAR (T_SAL)) ; END LOOP;
If executing this only once, only the contents of one row will be accessed. To sequentially read the rows of the cursor, use the FOR..LOOP command. The next example reads the Display30 cursor, attributing the contents of selected columns to three variables that were previously declared. The EXIT clause tests the %NOTFOUND attribute. When it returns TRUE, the loop will be closed. When this does not happen, the variables are displayed: LOOP FETCH display30 INTO t_ename, t_deptno, T_sal; EXIT WHEN display30%notfound; DBMS_OUTPUT.PUT_LINE(t_ENAME // ´ ´ //TO_CHAR(T_DEPTNO) // ´ ´ // TO_CHAR (T_SAL)) ; END LOOP;
360
Cursors—Chapter 19
Closing a Cursor When a cursor is not in use, it must be closed so Oracle can free the resources that were allocated to it. The command responsible for this task is CLOSE: CLOSE display30
If you forget to close a cursor, Oracle will close it automatically when the user closes the program or disconnects from the database.
A Practical Example To show how a cursor works, we’ve created a procedure called Cur01, which displays the contents of the Ename, Deptno, and Sal fields of the EMP table. Initially, three variables are created. They will contain the contents of the fields. To do that, use the %type attribute that creates it with the same data type as the field. Then, the cursor is defined with the name Display30 and the specified SELECT command. We activate the output of data from the DBMS_OUTPUT package, and then open the cursor. A loop is executed until there are no more rows to be processed. The FETCH command downloads the contents of the fields to the variables. Finally, the package displays the data: CREATE OR REPLACE PROCEDURE CUR01 IS e_ename emp.ename%type; e_deptno emp.deptno%type; e_sal emp.sal%type; CURSOR display30 IS SELECT ENAME,DEPTNO,SAL FROM EMP WHERE DEPTNO=30 ORDER BY ENAME; BEGIN DBMS_OUTPUT.ENABLE; /*open cursor*/ 361
Chapter 19—Cursors OPEN display30; LOOP FETCH display30 INTO e_ename, e_deptno, e_sal; EXIT WHEN display30%notfound; DBMS_OUTPUT.PUT_LINE(e_ename || ‘—’ ||TO_CHAR(e_deptno) || ‘—’ || TO_CHAR (e_sal)) ; END LOOP; close display30; end;
To execute this cursor, you have to invoke the Cur01 procedure: SQL> EXECUTE cur01;
This is the result: SQL> exec cur01; ALLEN—30—1600 BLAKE—30—2850 JAMES—30—950 MARTIN—30—1250 TREVOR—30—3000 TURNER—30—1500 WARD—30—1250 PL/SQL procedure successfully completed.
Using the FOR..LOOP Instead of displaying the returned rows, and to avoid the manual work of opening, attributing, and closing a cursor, you can use the FOR..LOOP command. When you use it, Oracle automatically declares a variable with the same name as that used as a counter in the FOR command. Just precede the name of the selected field
362
Cursors—Chapter 19
with the name of this variable to access its contents. Below is an example of how this command is used: SQL> CREATE OR REPLACE PROCEDURE CUR02 IS 2 CURSOR display30 IS 3 SELECT ENAME, DEPTNO, SAL FROM EMP WHERE DEPTNO=30 4 ORDER BY ENAME; 5 6 BEGIN 7 DBMS_OUTPUT.ENABLE; 8 FOR X IN display30 LOOP 9 DBMS_OUTPUT.PUT_LINE(X.ENAME || ‘ ‘ | TO_CHAR(X.DEPTNO)|| 10 ‘ ‘ || TO_CHAR (X.SAL)); 11 END LOOP; 12 END; 13 / Procedure created. SQL> execute cur02; ALLEN 30 1600 BLAKE 30 2850 JAMES 30 950 MARTIN 30 1250 TREVOR 30 3000 TURNER 30 1500 WARD 30 1250 PL/SQL procedure successfully completed.
This chapter presented the concept of cursors, which help with memory. The next chapter discusses transactions and how to use them to minimize database errors.
363
Chapter 20
Transactions A transaction is a logical work unit containing one or more SQL declarations. It is an atomic unit, meaning that the effects of the SQL declarations in a transaction are either all committed (applied to the database) or all rolled back (undone in the database). A transaction starts with the first executable SQL transaction and ends when it is committed or rolled back, be that explicitly (with a COMMIT or ROLLBACK declaration) or implicitly (when a DLL declaration is issued). To illustrate the concept of transactions, think about a banking operation database. When a client transfers money from a savings account to a checking account, the transaction can consist of three separate operations: debiting the savings account, crediting the checking account, and recording the transaction in the transaction log. Oracle should allow two situations. When all three SQL declarations can be executed to maintain the appropriate balance in the accounts, the effects of the transaction can be applied to the database. However, when something (such as insufficient funds, invalid account number, or hardware failure) prevents one or more transaction declarations from completing, then the entire transaction must be rolled back so the balance of all accounts will be correct.
365
Chapter 20—Transactions
Transaction Management An Oracle transaction begins when the first executable SQL declaration is found. An executable SQL declaration is a SQL declaration that generates calls for an instance, including the DML and DDL declarations. When a transaction begins, Oracle attributes it to a rollback segment in the new transaction. A transaction ends when one of the following happens:
: :
: :
You issue a COMMIT or ROLLBACK declaration (without a savepoint). You execute a DDL declaration (such as CREATE, DROP, RENAME, or ALTER). When the current transaction contains a DML declaration, Oracle first makes the transaction commit, and then executes the DDL commit declaration as a new declaration transaction. A user disconnects from Oracle. (The current transaction is committed.) A user process is not ended normally. (There is a rollback of the current transaction.)
After a transaction ends, the next executable SQL declaration automatically starts the next transaction.
Discretionary Transaction Management Application developers are able to improve the performance of short and non-distributed transactions by using the BEGIN_DISCRETE_TRANSACTION procedure. It optimizes transaction processing, so short transactions can be executed faster. During a discretionary transaction all the changes made to any piece of data are deferred until it is committed. Obviously, other simultaneous transactions cannot see the uncommitted changes of a transaction, whether it is discretionary or not.
366
Transactions—Chapter 20
Oracle generates redo information, but stores it in a separate location in the memory. When a transaction issues a commit request, Oracle writes the redo information in the redo record file (together with other group commits), and applies the changes made directly to the database block. Oracle returns the control to the application after a commit is complete. This eliminates the need to generate undo information, since the block is not changed until the transaction is committed, and redo information is stored in the redo log buffers. There is no iteration among discretionary transactions, which always generate the redo, and the NOLOGGING mode, which applies only to the direct path operations.
Transaction Declaration and Control A “successfully executed” SQL declaration is different from a “committed” transaction. A successfully executed declaration is simply one in which only one declaration was analyzed and considered a valid SQL construction, and that all the declarations were error free as an atomic unit (for example, all the rows of a multiline update were changed). However, before the transaction containing the declaration is committed, a transaction can be rolled back, and all the changes of the declaration can be undone. A declaration, and not a transaction, is successfully executed. Committing means that a user explicitly or implicitly said “make the changes in this transaction permanent.” The changes made by the SQL declaration(s) in your transaction become permanent and visible to other users only after it is committed. Only the transactions of other users that were initiated after yours will see the committed changes.
367
Chapter 20—Transactions
Committing Transactions Committing a transaction means to make permanent the changes made by the SQL declarations inside the transaction itself. Before a transaction that changes data can be committed, the following has to occur:
: :
Oracle generates the rollback segment records in the rollback segment buffers in the system global area (SGA). The rollback information contains the old data values that were changed by the SQL declarations of the transaction. Oracle generates entries in the redo record of the redo record buffer of the SGA. These changes can be written to disk before a transaction is committed. The changes are made to the database buffers of the SGA. These changes can be written to disk before a transaction is really committed.
The following happens when a transaction is committed:
: :
:
The internal table containing the transaction of associated rollback segment records that a transaction was committed, and the unique System Change Number (SCN) corresponding to the transaction is attributed and recorded in the table. The Log Writer (LGWR) writes the entries of the redo record of redo record buffers of the SGA to the online redo record file; it also writes the SCN of the transaction to the on redo record file. This atomic event constitutes the commit of the transaction. Oracle frees the row and table locking, and marks the transaction as complete.
Two-Phase Commit In a distributed database, Oracle must coordinate the control of the transaction in a network, as well as maintain the data consistency, even when a network or system failure occurs.
368
Transactions—Chapter 20
A two-step commit mechanism guarantees that all the database servers that participate in a distributed transaction have a commit or rollback of the transaction declarations. A two-phase commit mechanism also protects the explicit DML operations executed by integrity constraints, remote procedure calls, and triggers. Oracle’s two-phase commit mechanism is completely seamless to the users who issue distributed transactions. Actually, the users don’t even have to know if the transaction is distributed. A COMMIT declaration that denotes the end of a transaction automatically starts the two-phase commit; no complex code or declaration syntax is required to include the distributed transactions in the body of a database application. The background recovery process (RECO) automatically resolves the result of the in-doubt distributed transactions—those transactions in which some type of system or network failure interrupted the commit. After the failure is fixed and communication is reestablished, the RECO in each local Oracle server makes the automatic commit or rollback of all the in-doubt distributed transactions, consistently and in all the involved nodes. In the case of a long-term failure, Oracle allows each local administrator to manually commit or roll back all the distributed transactions that are in-doubt as a result of the failure. This option permits the local database administrator to free all the locked resources, which otherwise could be indefinitely locked as a result of the long-term failure. When a database must be recovered up to a particular point, the recovery resources of Oracle allow the database administrators at other sites to also return their databases to that point. This guarantees the consistency of the global database.
369
Chapter 20—Transactions
Rolling Back Transactions Rolling back means to undo all the changes made to data that were executed by the SQL declarations inside an uncommitted transaction. Oracle allows the rollback of an entire uncommitted transaction. Alternatively, you can roll back the final part of an uncommitted transaction to a marker called a savepoint. There are several types of rollbacks, all of which use the same procedures:
: : : : : :
A rollback at the declaration level due to a declaration execution error or deadlock. A rollback to a savepoint. A rollback of a transaction due to a user request. A rollback of a transaction due to the abnormal ending of the process. A rollback of all the pending transactions, when an instance ends abnormally. A rollback of incomplete transactions during the recovery.
When rolling back a transaction that does not have a savepoint, the following occurs:
: : :
Oracle undoes all the changes made by all the SQL declarations of the transaction, using the corresponding rollback segments. Oracle frees all the data transaction locking. The transaction ends.
When a transaction is rolled back to a savepoint, the following occurs:
:
370
Oracle makes the rollback only of declarations that were executed after the savepoint.
Transactions—Chapter 20
: : :
The specified savepoint is preserved, but all of those that were established after the specific savepoint are lost. Oracle frees all the table and row locking required from that savepoint on, but maintains all the data locks that were acquired before it. The transaction remains active and can proceed.
Rollback at Declaration Level If there is an error at any time during the execution of a SQL declaration, all of its effects will be rolled back. The rollback effect makes the declaration seem as if it had never been executed. This is a rollback at declaration level. The errors found during the execution of the SQL declaration cause rollbacks at the declaration level. (An example of such an error would be trying to insert a duplicate value in a primary key.) The errors found during the analysis of the SQL declaration (such as a syntax error) were not executed yet and, therefore, they do not cause a rollback at declaration level. The simple SQL declarations involved in a deadlock (concurrency among data) can also cause a rollback at declaration level. A SQL declaration with failure causes the loss of only the work that it executed; it does not cause the loss of any work that preceded it in the current transaction. When the declaration is a DDL, the implicit commit that immediately preceded it is not undone.
Savepoints You can declare intermediate markers called savepoints inside the context of a transaction. They divide a long transaction into smaller parts.
371
Chapter 20—Transactions
You use savepoints to arbitrarily mark your work at any point inside a long transaction. Then you have the option of rolling back the work executed before the current point of the transaction (its end) but after the declared savepoint. For example, you can use savepoints in a long and complex series of updates, so if you introduce an error, you will not need to submit each declaration again. Savepoints are equally useful in application programs. When a procedure contains several functions, you can create a savepoint before a function begins. Then, if any of them fail, it is easy to return data to their state when the function started, and execute it again with revised parameters, or even to perform a recovery action. After rolling back to a savepoint, Oracle frees the data locks obtained by the rolled back declarations. Other transactions that were waiting for the locked resources can continue and, if desired, they can update the rows that were previously locked.
Autonomous Transactions Autonomous transactions are independent transactions that can be called from inside another transaction. These allow going outside out of the context of the calling transaction to execute some SQL operations, to make the commit or rollback of those operations, and then returning to the context of the calling transaction, and proceeding with those transactions. After it is invoked, an autonomous transaction is totally independent from the calling transaction (the main transaction). It does not see any of the uncommitted changes made by the main transaction, and does not share any lock or resource with this same transaction. The changes made by an autonomous transaction are visible to other transactions in the commit of the autonomous transactions.
372
Transactions—Chapter 20
An autonomous transaction can call another transaction. There are no limitations, except those of the resources, to the number of calling layers in the autonomous transactions. Deadlocks are possible between an autonomous transaction and its calling transaction. Oracle detects these deadlocks and returns an error. The application developer is responsible for avoiding deadlock situations. Autonomous transactions are useful for implementing actions that must be executed independently, regardless of whether the calling transactions are committed or rolled back, such as a logging transaction, or the retry counters.
Autonomous PL/SQL Blocks You can call autonomous transactions from a PL/SQL block. The PRAGMA AUTONOMOUS_TRANSACTION procedure can declare as autonomous the following types of PL/SQL blocks:
: : : : :
Stored procedure or function Local procedure or function Package Type method Anonymous block of first level
The transactional operations executed in the BEGIN..END section of an autonomous block are created as part of an autonomous transaction, i.e., independently of the calling block transaction context. When an autonomous PL/SQL block is inserted, the caller transaction context is suspended. This guarantees that the SQL operations executed in this block (or in other blocks that were called from it) do not have any dependency or effect on the state of the caller transaction context. An autonomous PL/SQL block is considered as having purity of RNDS (Reads No Database State) and WNDS (Writes No Database 373
Chapter 20—Transactions
State), even when the SQL operations are executed in the autonomous block, or in other blocks called from it. For this reason, such blocks can be called as SQL contexts. When an autonomous block invokes another block of this type, or even itself, the called block does not share its transaction context with the calling block. However, when an autonomous block invokes a non-autonomous block (i.e., a block that is not declared as being autonomous), the called block inherits the transaction context from the calling autonomous block.
Transaction Control Declarations in Autonomous PL/SQL Blocks The transaction control declarations in an autonomous PL/SQL block apply only to the autonomous transaction that is currently active. Examples of these declarations include:
: : : : :
Set transaction Commit Rollback Savepoint Rollback to savepoint
Also, the transaction control declaration of the main transaction applies not only to that transaction, but also to all the autonomous transactions that it calls. For example, rolling back the main transaction to a savepoint before the beginning of an autonomous transaction does not roll back this transaction. With this chapter we finish the part of this book related to the use of the SQL and PL/SQL languages. As a developer you will be working with these elements most of the time. The next part covers two important concepts: distributed processing and replication.
374
Part V
DISTRIBUTED PROCESSING This part is somewhat more conceptual and shows how Oracle8i works in a distributed environment, as well as the replication of tables and databases. Chapter 21: Distributed Processing Chapter 22: Replication
375
Chapter 21
Distributed Processing This chapter defines distributed processing, and describes how the Oracle server and database applications work in a distributed processing environment. This material applies to almost all types of environments of the Oracle database system.
Oracle’s Client/Server Architecture In the Oracle database system, the application and the database are divided into two parts: a front end, or client, and a back end, or server. The client executes the application that accesses information in the database, and interacts with a user through the keyboard, screen, or mouse. The server executes the Oracle software and handles the necessary functions for the simultaneous and shared data access in an Oracle database. Although the client application and Oracle can be executed in the same computer, most often it is more efficient when the client and server are executed in different computers that are connected through a network.
377
Chapter 21—Distributed Processing
Distributed Processing Using more than one processor to execute individual tasks is called distributed processing. Examples of distributed processing in Oracle database systems are shown in the following figure: Database server
A
Network
Client
Client
Database server
B
Client Client
Figure 21.1:
378
Distributed processing in the database environment.
Distributed Processing—Chapter 21
: :
In Part A of the figure, the client and the server are located in different computers, which are connected through a network. In Part B of the figure, there is only one computer, which has more than one processor. Different processors separate the execution of the client application.
In the network example (Part A), the server and clients communicate through Net8, Oracle’s network interface. Net8 is discussed later in this chapter. Oracle’s client/server architecture in a distributed processing environment provides the following benefits:
:
: : :
: :
The client applications are not responsible for the execution of any data processing. Instead, they ask for user entry and server data, and then analyze and present those data using the display capabilities of the client workstation or terminal (for example, using graphics or spreadsheets). The client applications are not dependent on the physical location of data. When data is moved or distributed to other database servers, the application continues functioning with few or no modifications at all. Oracle explores the multitasked and shared memory resources of its basic operating system. As a result, it delivers the highest concurrency, data integrity, and performance to the client applications. The client workstations or terminals can be optimized for data presentation (for example, supporting graphics and mouse input), and the server can be optimized for data processing and storage (for example, having a large memory and plenty of disk space). In network environments, you can use inexpensive client workstations to efficiently access remote data in the server. Oracle can be dimensioned as your system grows. You can add several servers to distribute the processing workload of the database through the network (horizontal dimensioning), or 379
Chapter 21—Distributed Processing
: :
even move Oracle to a minicomputer or mainframe, and take advantage of the performance of a larger system (vertical dimensioning). In any case, all data and applications are maintained with few or no changes, since Oracle is supported among the systems. In network environments, shared data is stored in servers rather than being stored in all the system’s computers. This helps to make the management of simultaneous access easier and more efficient. In network environments, the client applications submit database requests to the database using SQL declarations. After it is received, the server processes the SQL declaration and the results are returned to the client application. Network traffic is maintained because only the requests and results are sent through the network.
Net8 Net8 is Oracle’s network interface. It permits Oracle tools to be executed in the network and server workstations in order to access, modify, share, and store data in other servers. Net8 is considered part of the program interface in network communications. It uses the communication protocols, or application programming interfaces (APIs), supported by a wide variety of networks, that provide Oracle with a distributed database and distributed processing.
: :
380
A communication protocol is a set of standards, implemented in the application, that governs the data transmission through a network. An API is a set of subroutines that provides, in the case of networks, a way to establish the remote communication to the process through a communication protocol.
Distributed Processing—Chapter 21
The communication protocols define how to transmit and receive data in a network. In a network environment, an Oracle server communicates with the client workstations and other Oracle servers using Net8. Net8 supports communications in all major network protocols, from those supported by PC LANs to those used by major mainframe computer systems. Without Net8, an application developer must manually code all the communications of an application that operates in an environment of network distributed processing. When the network hardware, topology, or protocol change, the application has to be changed accordingly. However, by using Net8 the application developer doesn’t have to worry about the network communications to support a database application. When the basic protocol changes, the database administrator makes some minor changes; the application does not require any change, and continues working normally.
How Net8 Works The Net8 drivers provide an interface among the Oracle processes, which are executed in the database server, and the user processes of Oracle tools, which are executed in other computers of the network. The Net8 drivers acquire the SQL declarations from Oracle’s tool interface and package them for transmission to the database by means of one of the supported protocols or the programming interfaces. The drivers also acquire the answers from Oracle and package them for transmission to the tools by means of the same mechanism. All of this is done without any link to the network operating system.
381
Chapter 21—Distributed Processing
Network Listener When an instance is initialized, a network listener process establishes a communication path with Oracle. When a user process makes a connection request, the listener determines whether it should use a shared server process or a dedicated server process, and determines the appropriate connection. The listener process also establishes a communication path among databases. When several databases or instances are executed in a machine, such as the Oracle Parallel Server, the service names allow instances to register themselves automatically in other listeners of the same machine. A service name can identify several instances, and one instance can belong to several services. The clients connected to a service do not need to specify the required instance. The automatic instance register reduces the administrative load of several databases, or even of those instances. The system identifiers (SIDs) of other instances in the network must be registered in a file called listener.ora. The initialization parameter, service_names, identifies to which services an instance belongs. In the initialization, each instance registers itself with the listeners of other instances belonging to the same services. During the database operation, the instances of each service pass information about the CPU usage and the countdowns of current connections to all listeners of the same services. This allows the dynamic balance of workload and the connection failover.
382
Distributed Processing—Chapter 21
Multitiered Architecture In a multitiered architecture environment, the application server provides data to clients and servers, acting as an interface among clients and database servers. Such architecture allows the use of an application server to:
: : :
Validate the credentials of a client, such as a Web navigator. Connect to a database server. Execute the required operation. Database Server
Database Server
Database Server
Application server1
Application server2
Application serverN
Database Server
Database Server
Database Server
Request Thin Client Query Data
Thin Client
Thin Client
Figure 21.2:
An example of multitiered architecture.
383
Chapter 21—Distributed Processing
Clients A client initiates a request for an operation to be executed in the database server. It can be a Web navigator or another final user process. In multitiered architecture, the client connects to the database server through one or more application servers.
Application Servers An application server provides the data access for the client. It serves as an interface among the client and one or more database servers, providing an additional level of security. It also can execute part of the query processing for the client, thus removing part of the database server’s workload. The application server assumes the identity of the client when executing operations to that client in the database server. Application server privileges are limited to preventing it from executing unnecessary and undesirable operations during a client operation.
Database Servers A database server provides data required by an application server on behalf of the client. It performs all the remaining query processing. Oracle’s database server can audit the operations executed by the application server, on behalf of the individual clients, as well as its own operations. For example, a client operation can be a request to display information in the client, while an application server operation can be a request to connect with the database server. This chapter discussed distributed processing and how Oracle works in a distributed processing environment. The next chapter introduces replication, which is the process of updating database objects in a distributed database system.
384
Chapter 22
Replication Replication is the process of copying and updating database objects in the many databases that form a distributed database system. The changes applied to a site are captured and locally stored before they are forwarded and applied to each of the remote locations. Replication provides the user with fast and local access to shared data, and protects the availability of applications by switching among the existing access options.
Replication Objects A replication object is a database object that exists in several servers of a distributed database system. Oracle’s replication resource allows the replication of tables and support objects, such as views, database triggers, packages, indexes, and synonyms. SCOTT.EMP and SCOTT.BONUS, illustrated in the following figure, are examples of replication objects.
385
Chapter 22—Replication
ORC1.WORLD
ORC2.WORLD
SCOTT MG SCOTT . EMP SCOTT . DEPT SCOTT . BONUS SCOTT . SALGRADE
SCOTT MG SCOTT . EMP SCOTT . DEPT SCOTT . BONUS SCOTT . SALGRADE
ORC3.WORLD
SCOTT MG SCOTT . EMP SCOTT . DEPT SCOTT . BONUS SCOTT . SALGRADE
Figure 22.1: The master group SCOTT_MG contains the same replication objects in every site.
Replication Groups In a replication environment, Oracle manages the replication objects using replication groups. The replication group objects can originate from several database schemas, and a schema can contain objects that are members of different replication groups. In a multimaster replication environment, the groups are called master groups. The corresponding master groups in different places must contain the same set of replication objects. Figure 22.1 illustrates the master group SCOTT_MG, and contains an identical copy of the objects replicated in each master site. In a snapshot site, the organization is maintained using a snapshot group. This snapshot group maintains a partial or complete
386
Replication—Chapter 22
copy of the target master group. The following figure illustrates that the Group A snapshot of the snapshot site maintains only a partial copy of the Group A master group in the master site, while the Group B snapshot maintains a complete copy of the Group B master group.
Group A
Group A
SCOTT . EMP SCOTT . DEPT
SCOTT . EMP SCOTT . DEPT
SCOTT . SALGRADE SCOTT . BONUS
Group B
Group B
MIKE . CUSTOMER
MIKE . CUSTOMER
MIKE . DEPARTMENT MIKE . EMPLOYEE
MIKE . DEPARTMENT MIKE . EMPLOYEE
MIKE . ITEM
MIKE . ITEM
Master Site
Figure 22.2:
Snapshot Site
The snapshot groups correspond to the master groups.
Replication Sites A replication group can exist in several replication sites. The replication environments support two basic types of sites: master sites and snapshot sites. A master site contains a complete copy of all the objects of a replication group. All the master sites in a multimaster replication environment communicate directly with each other to propagate data and schema changes made to the replication group. A replication group in a master site is called more specifically master group. Every master group has one and only one site of master 387
Chapter 22—Replication
definition (for example, ORC1.WORLD in Figure 22.3 could be the site of master definition). A site of master group definition of replication is a master site that works as a point of control from which the replication group and group objects are managed. A snapshot site supports read-only and updatable snapshots of table data in an associated master site. The table snapshots of a snapshot site may contain all the data of a table, or a subset of them inside a replication group. However, these snapshots must be simple and have a correspondence with each other in the tables of the master site. For example, a snapshot site may contain snapshots only from the selected tables of a replication group. And a snapshot in particular can be only a selected part of a certain replicated table. A replication group of a snapshot site is called specifically a snapshot group. A snapshot group can also contain other replication objects. ORC2.WORLD
Master Site
Master Site
Snapshot Site
Master Site
SNAP1.WORLD
ORC3.WORLD
Figure 22.3:
388
ORC1.WORLD
Three master sites and one snapshot site.
Replication—Chapter 22
Multimaster Replication Multimaster replication of Oracle allows several sites, acting as equal peers, to manage the replicated object groups of a database. In a multimaster configuration, the applications may update all the replicated tables in any site. Figure 22.4 illustrates a multimaster replication system. Oracle’s database servers, which operate as master sites in a multimaster environment, work automatically to convert data of all table copies, and to guarantee the global consistency of transactions, as well as data integrity. Multimaster replication is useful for many types of application systems, with special requirements. The following scenarios describe some uses for the multimaster replication. The multimaster replication can be useful to protect the availability of a mission critical database. For example, a multimaster replication environment can replicate all data in your database, establishing a failover site, in case the primary site is unavailable due to system or network failures. In contrast to Oracle’s Standby resource, the failover site also works as a totally functional database to support the application access when the primary site is simultaneously operational. Multimaster replication is useful for transaction processing applications that require several access points to the information of the database, with the purpose of distributing a high application load, guaranteeing continuous availability or providing more localized data access. Applications with application load distribution requirements normally include those applications oriented to the client service.
389
Chapter 22—Replication
Figure 22.4: Multimaster replication with support for several update access points.
Snapshot Replication A snapshot contains a complete or partial copy of a master target table at a unique moment. A snapshot can be read-only or updatable. In a basic configuration, snapshots provide read-only access to the table’s data originated from a primary or master site. The applications query data from the local data copies, avoiding network access and independent of network availability. However, the applications of the entire system must access data from the primary site when the updates are needed. Read-only snapshots provide the following benefits:
: : : :
390
The master tables don’t have to belong to a master group. They support complex snapshots (the snapshot may be based in one or more tables, and may contain aggregates, associations, operation sets, or a CONNECT BY clause). Provide local access to improve response times and availability. Off-load queries to the master site.
Replication—Chapter 22
Updatable Snapshots In a more advanced configuration, you can create an updatable snapshot that allows the users to insert, update, and delete rows of the target master table. An updatable snapshot also contains only a subset of the data set of the target master table. Figure 22.5 illustrates a replication environment using updatable snapshots. Updatable snapshots are based in tables from a master site, and are configured to support the multimaster replication. Actually, the updatable snapshots must be part of a snapshot group based on a master group on the master site.
Table
Master Site
Master Site
Figure 22.5:
Table
Master Site
Table
Table
Table
Table
Replication Group
Replication Group
Replication of updatable snapshot.
Updatable snapshots are always based in only one table, and can be incrementally updated. Oracle propagates the changes made through an updatable snapshot of the remote master table of the snapshot. If needed, there can be cascading updates to all other 391
Chapter 22—Replication
master sites. Oracle updates an updatable snapshot as part of a group of updates identical to the read-only snapshots. (An update group is an organizational mechanism, which maintains the transactional consistency.) Updatable snapshots provide the following benefits:
: : :
Allow users to query and update a local replicated data set, even when it is disconnected from the master site. Greater data security, which is attained by the replication of only a selected subset of the dataset in the target master table. Smaller footprint than the multimaster replication.
Using Snapshot Replication The read-only snapshot replication is useful as a way to replicate entire databases or off-load information. For example, when the performance of a system with high-volume transaction processes is critical, sometimes it is advantageous to keep a duplicate database to isolate the queries in great demand. The read-only snapshot replication is useful for information distribution. Take as an example the operations of a large department store chain. In this case, it is critical to guarantee that information about prices is always available, relatively up to date, and consistent at the point of retail. To achieve these objectives, each retail store can have its own copy of product price data, which is updated every night from a primary price table. The read-only and updatable snapshot replication can be very useful as a mechanism of information transportation. For example, the replication of read-only snapshots can move data periodically from a transaction processing database to a data warehouse.
392
Replication—Chapter 22
Disconnected Environments The updatable snapshot replication is useful for the distribution of transaction processing applications, which operate using disconnected components. Let’s look at a typical system to automate the sales force of a life insurance company. Each salesperson visits the clients regularly, carrying a laptop computer to register orders in a personal database while disconnected from the corporate network of computers and the centralized database system. When the salesperson returns to the office, he or she must forward all the orders to a centralized and corporate database. To help with the distribution of a snapshot environment, such as a sales force, the distribution models allow the database administrator to create a snapshot environment in the master site, providing ease of distribution and installation of a customized and safe snapshot environment. The distribution models allow a DBA to create a distribution environment once, and distribute with the necessary frequency for the target snapshot sites.
Hybrid Snapshots The replication and master snapshots can be combined in hybrid, or “mixed” configurations, to meet different application requirements. The mixed configurations can have any number of master sites and several snapshot sites for each master. As Figure 22.6 shows, the n-way replication (or multimaster replication) between two masters supports the replication of a complete table among databases that support two geographic regions. The snapshots can be defined in the masters to replicate complete tables or subsets of tables for the sites inside each region.
393
Chapter 22—Replication
N-Way
Master Site
Replication Group
Snapshot Site
Snapshot Site
Replication Group
Replication Group
Replication Group
Figure 22.6:
Master Site
Snapshot Site Replication Group
Hybrid configuration.
The main differences between snapshots and replicated masters include:
: : :
394
Replicated masters must contain data for the complete table that is being replicated, while snapshots can replicate subsets of data in the master table. Multimaster replication allows replicating changes for every transaction as changes occur. The snapshot updates are oriented to a set, propagating the changes of several transactions in a more efficient operation, but with less frequent intervals. If conflicts occur due to the changes made to several copies of the same data, the master sites detect and resolve the conflicts.
Replication—Chapter 22
Administering a Replicated Environment Every master and snapshot site in a replication environment has a replication catalog. The replication catalog of a site is a distinct set of data dictionary tables and views, which maintain administrative information about the replication objects and replication groups of the site. Every server that participates in a replication environment can automate the object replication in the replication groups using the information contained in the replication catalog. To help with the management of these replication environments, Oracle provides the Oracle Replication Manager. To configure and manage a replication environment, each participating server uses Oracle’s replication API. A server replication management API is a set of PL/SQL packages, which encapsulates the procedures and functions that the administrators use to configure Oracle’s replication resources. The Oracle Replication Manager also uses the procedures and functions of the replication management API in each site to do the work. An administration request is a call to a procedure or function of the replication management API. For example, when you use the Replication Manager to create a new master group, the Replication Manager completes the task by calling the DBMS_REPCAT.CREATE_MASTER_REPGROUP procedure. Some administration requests generate additional calls to the replication management API to complete the request.
Replication Conflicts The updatable snapshot and asynchronous multimaster replication environments must foresee the possibility of replication conflicts that may occur when, for example, two transactions originated in different updatable sites update the same row almost at the same time.
395
Chapter 22—Replication
When there are data conflicts, you need a mechanism to guarantee that the conflict will be resolved according to the business rules, and that data is correctly distributed to all the sites. In addition to the records of all the conflicts that may occur in a replicated environment, Oracle replication provides a variety of methods for resolving conflicts, which allow you to define a conflict resolution system for your database that will solve the conflicts according to your business rules.
Procedure Replication The batch processing applications can change great quantities of data in a single transaction. In these cases, the typical row-level replication can overload a network. To avoid these problems, some batch processing applications that operate in a replication environment can use Oracle’s procedure replication to replicate simple calls to stored procedures, distributing data copies. The procedure replication replicates just the call to a stored procedure that an application uses to update a table. The procedure replication does not replicate the changes made to data. To use procedure replication, you must replicate the packages that change your system data in every site. After replicating a package, you must generate a wrapper for this package in each site. When an application calls a packaged procedure in the local site to change data, the wrapper guarantees that the call is made to the same packaged procedure in other sites of the replicated environment. The procedure replication can be asynchronous or synchronous.
396
Replication—Chapter 22
Conflict Detection When a replication system replicates data using the replication procedure, the procedures that replicate data are responsible for guaranteeing the integrity of replicated data. In other words, you must create such procedures to avoid and detect replication conflicts, and to handle them properly. Consequently, procedure replication is often used when the databases are available only for the processing of great batch operations. In these situations, the replication conflicts are less likely, since numerous transactions are not disputing the same data.
Synchronous Data Propagation Synchronous data propagation is the normal configuration for replication environments. However, Oracle also supports synchronous data propagation for applications with special requirements. Synchronous data propagation occurs when an application updates a local copy of a table, and in the same transaction also updates all other copies of the same table. Consequently, synchronous data replication is also called real-time data replication. Use synchronous replication only when the applications require that the replicated sites be continually synchronized. You can create a replicated environment with some sites propagating changes synchronously, while others use asynchronous propagation (deferred transactions).
Synchronous Data Replication When a system of shared ownership replicates all the changes synchronously (real-time replication), replication conflicts may not occur. In real-time replication, applications use distributed transactions to update all the copies of a table simultaneously. As is the case of non-distributed database environments, Oracle automatically locks the rows on behalf of every distributed 397
Chapter 22—Replication
transaction, to prevent destructive interference among transactions. Real-time replication systems can avoid replication conflicts. In this chapter you learned about the different types of replication and why it is important in a database environment. This ends the part on distributed processing and replication. In the next part of this book, several Oracle utilities are explored.
398
Part VI
UTILITIES Here we show how some of Oracle’s utilities work. These utilities, which include Export, Import, DBVERIFY, and SQL*Loader, are extremely useful for the developer. Chapter 23: Export Chapter 24: Import Chapter 25: DBVERIFY Chapter 26: SQL*Loader
399
Chapter 23
Export The Export utility allows the transference of objects among Oracle databases. It even allows the transference of files among different hardware and software platforms. Export extracts an object definition and its contents, turning them into a binary file. This file can be transferred through network or disk to other locations, With the Import utility, discussed in the following chapter, it is possible to convert and insert this data in another Oracle database. Export file
Database Table 1
Table 3
Table 5
Table 1 Index 1
Index 1
Table 4
Index 5
Table 2
Index 4
Table 6
Table 2 Table 3 Table 4 Index 4 Table 5 Index 5 Table 6
Figure 23.1:
Transferring objects using the Export utility.
401
Chapter 23—Export
The Export utility extracts all the database objects together with the related or dependent objects. For example, a table is extracted along with its indexes, comments, and permissions.
Export Methods Export provides three export methods:
: : :
Table mode User mode Full mode
Table Mode Table mode allows exporting specific tables of the user schema, instead of all the tables. It also allows the export of rows, permissions, definitions, restrictions, and triggers of tables. A table and all of its dependent objects are exported, whether it is partitioned or not.
User Mode User mode allows exporting tables and other schema objects, such as views, materialized views, clusters, database links, sequences, synonyms, and stored procedures.
Full Mode Full mode exports all the database objects. A user can only export tables if he or she has the CREATE SESSION privilege. To export tables to other users, he or she must have the EXP_FULL_DATABASE role, which normally is assigned to the DBA.
402
Export—Chapter 23
To use Export, the user must execute the catexp.sql or catalog.sql script once after the creation of the database. These scripts create the export views, assign all the needed privileges to the EXP_FULL_DATABASE role, and attribute them to the DBA role.
Execution Modes The Export program is executed in the command line of the operating system, through the file exp.exe. It can be specified with a parameter file. . . or by individually specifying the parameters.
:
Form 1
parameter file:
exp user/passwordPARFILE=NameOfParameterFile
PARFILE Specifies the name of the text file containing the parameters.
:
Form 2
individual parameters:
exp username/password
After specifying the user and password, the program asks for each parameter. The two forms can be combined. In this case, parameters specified in both the command line and the parameter file have the priority.
The EXP Command The syntax for the EXP program is shown below: Syntax: EXP <parameter1, parameter2, parameterN..>
403
Chapter 23—Export
Arguments: Note that some commands have a value of Y or N indicating their state. The default value for these commands is indicated in parentheses. USERID Name of user/password. BUFFER Size of data buffer. If 0 is specified, only one row will be copied one at a time. Tables with the data types long, lob, bfile, ref, rowid, and logical rowid have their rows copied one at a time. FILE Output file. The default is expdat.dmp. The default extension is .dmp. COMPRESS Import to the extension (Y). The default consolidates all the tables in an initial extension after import. GRANTS Determines that EXP must export the permissions (Y). INDEXES Specifies that the indexes must be exported (Y). ROWS Indicates that EXP must export rows of data (Y). CONSTRAINTS Specifies when Export must export restrictions (constraints) (Y). CONSISTENT =y/n Specifies whether Export must use the SET TRANSACTION READ ONLY commands to guarantee that data is consistent and does not change during the program execution. LOG Screen output file.
404
Export—Chapter 23
DIRECT Direct path (N). Specifies when a conventional or direct path is used. Y indicates that the extraction directly overwrites the SQL command processing level. FEEDBACK=n Specifies that Export displays a progress indicator for every n rows processed. The default is 0. FILESIZE=value Maximum size of each file. HELP=y/n Displays the help text (N). QUERY Specifies the SELECT clause used to export a subset of the table, such as: query="where deptno=20" FULL Exports the entire file (N). OWNER Indicates that the export is of type user, and lists the users whose objects are being exported. TABLES Specifies that the export is of type table, and lists the table and partition names that are being exported. RECORDLENGTH Size of I/O record. INCTYPE=complete/cumulative/incremental Specifies the types of export, such as incremental, complete, or cumulative. The default is none. RECORD Tracks incremental export (Y). Indicates whether an incremental or cumulative export should export the SYS.INCEXP, SYS.INCFIL, and SYS.INCVID system tables.
405
Chapter 23—Export
PARFILE=file Specifies the name of a parameter file, which is a text file with a list of parameters and values. STATISTICS = none/estimate/compute Specifies the types of statistics that must be generated when data is imported. TRIGGERS Exports triggers (Y).
Obtaining Help By specifying the argument Y to the Help parameter, the user can obtain a list of the parameters used by the program. Take a look at the following: > exp help=y Export: Release 8.1.5.0.0 - Production on Tue May 18 10:24:43 1999 (c) Copyright 1999 Oracle Corporation. All rights reserved. You can let Export prompt you for parameters by entering the EXP command followed by your username/password: Example: EXP SCOTT/TIGER EXP SCOTT/TIGER Or you can control how Export runs by entering the EXP command followed by various arguments. To specify parameters, you use keywords:
406
Export—Chapter 23 Format: EXP KEYWORD=value or KEYWORD=(value1,value2,...,valueN) Example: EXP SCOTT/TIGER GRANTS=Y TABLES=(EMP,DEPT,MGR) or TABLES=(T1:P1,T1:P2), if T1 is partitioned table USERID must be the first parameter on the command line. Keyword Description (Default) ---------------------------------------------------------USERID username/password BUFFER size of data buffer FILE output files (EXPDAT.DMP) COMPRESS import into one extent (Y) GRANTS export grants (Y) INDEXES export indexes (Y) ROWS export data rows (Y) CONSTRAINTS export constraints (Y) LOG log file of screen output DIRECT direct path (N) FEEDBACK display progress every x rows (0) FILESIZE maximum size of each dump file QUERY select clause used to export a subset of a table VOLSIZE number of bytes to write to each tape volume FULL export entire file (N) OWNER list of owner usernames TABLES list of table names RECORDLENGTH length of I/O record INCTYPE incremental export type RECORD track incr. Export (Y)
407
Chapter 23—Export PARFILE CONSISTENT STATISTICS TRIGGERS
parameter filename cross-table consistency analyze objects (ESTIMATE) export triggers (Y)
Export terminated successfully without warnings.
Executing the Export Program The Export program can be executed in one of three different ways: with the command line, in interactive mode, or by using a parameter file.
Command Line Mode EXP allows you to specify all the parameters in the command line, using the following syntax: exp parameter=value parameter=value
When more than one parameter is needed, simply separate them with a space: >exp scott/tiger tables=emp rows=Y
Figure 23.2: Using comand line mode.
408
Export—Chapter 23
Interactive Mode In this mode, you specify just the user name and password: exp username/password
The program asks the necessary questions to perform the export, as shown in the following figure.
Figure 23.3: Using interactive mode.
409
Chapter 23—Export
The Parameter File The parameter file is a text file that stores a series of parameters used in the export. It can be created with Windows Notepad or any other word processor. It is useful when you execute the same commands over and over. For example, let’s say every week a user schema is exported. The format of this execution mode is: exp username/password PARFILE=filename
The parameter file requires a row for each parameter, where the name of the parameter and the associated value are specified: parameter=value parameter=(value) parameter=(value, value, ...)
Example: FULL=Y FILE=DBA.DMP GRANTS=Y INDEXES=Y CONSISTENT=Y
Exporting in User Mode User mode is a convenient mode in which to export user objects. The following example shows Scott exporting his tables: exp scott/tiger file=scott.dmp owner=scott grants=Y rows=Y compress=y
410
Export—Chapter 23
Figure 23.4: Exporting tables in user mode.
Warning Messages When Export is not able to complete the execution of a table export, an error message is displayed and the program continues the operation with the next table. The program displays error messages or writes them to the specified log file. The next example shows the export of two tables of user Demo. One was exported normally, and one was not found. This error causes the following error message to appear:
411
Chapter 23—Export
Figure 23.5: An error message displays when a table cannot be exported.
Another example is the specification of nonexistent parameters. In this case, the export is not executed: D:\>exp scott/tiger table=y LRM-00101: name of parameter ‘table unknown’ EXP-00019: failure when processing parameters; type ‘EXP HELP=Y’ to get help EXP-00000: Export unsuccessfully terminated
Exporting in Full Mode Only users with the DBA or EXP_FULL_DATABASE roles are authorized to perform an export in full mode. (The following example is for demonstration only. If you execute the command, it will back up the entire database.) exp system/manager full=Y file=dba.dmp grants=Y rows=Y
412
Export—Chapter 23
Incremental, Cumulative, and Complete Exports An export in full mode can be done in one of three different ways:
: : :
Incremental—This type of export copies only the tables that changed since the last incremental, cumulative, or complete export. It exports the table with their definitions and all of its data. Cumulative—This type copies only the tables that changed since the last cumulative or complete export. Complete—This type of export is done the first time to establish the basis for future cumulative or incremental exports.
This chapter discussed how to use Oracle’s Export utility. The Import utility is covered in the next chapter.
413
Chapter 24
Import The Import program is similar to Export, which was discussed in the previous chapter. Import restores the schema objects that were exported by the EXP program. The table objects are imported in the following order: table definitions, indexes, constraints, views, procedures, and triggers. Bitmap indexes, if they exist, are the last to be imported. The Import program first creates the tables and then populates them with data, and builds the indexes. After the indexes, the program creates the triggers and applies them to the referential integrity restrictions or constraints. The configuration order of the tables is important. If Scott’s EMP table is configured before the DEPT table, the DEPT table’s rows are not created, since the referential integrity constraint DEPT is not met because this table does not yet exist. The Import program can read files created by version 5.1.22 of the Export program.
415
Chapter 24—Import
Import Methods Import provides three import methods:
: : :
Table mode User mode Full mode
Table Mode Table mode allows the import of specific tables in the user schema rather than importing all of them. It also allows the import of rows, permissions, definitions, restrictions, and triggers of tables. A table and all its dependent objects are imported whether the table is partitioned or not.
User Mode User mode allows the import of tables and other schema objects, such as views, materialized views, clusters, database links, sequences, synonyms, and user stored procedures.
Full Mode Full mode imports all the database objects. To import tables of other users, the user must have the IMP_FULL_DATABASE role, which normally is attributed to the DBA. To use Import, the user must execute the catexp.sql or catalog.sql script only once after the database creation. These create export views, assign all the necessary privileges to the IMP_FULL_DATABASE role, and then grant the DBA role.
416
Import—Chapter 24
Execution Modes The Import program is executed from the command line of the operating system, through the file imp.exe. This can be specified as a parameter file or the parameters can be individually specified.
:
Form 1
parameter file:
imp user/passwordPARFILE=NameOfParameterFile
PARFILE Specifies the name of the text file containing the parameters. This is a text file that stores a series of parameters that will be used in the import operation. It can be created with the Windows Notepad, or with any other word processor. It is useful when you execute the same commands over and over, such as importing a user schema every week. The format of this execution mode is: imp username/password PARFILE=filename
The parameter file must have a line for each parameter, where the name of the parameter and the associated value are specified. parameter=value parameter=(value) parameter=(value, value, ...)
Example: FULL=Y FILE=DBA.DMP GRANTS=Y INDEXES=Y
417
Chapter 24—Import
:
Form 2
individual parameters:
imp username/password
After specifying the user and password, the program asks for each parameter. The two forms can be combined. In this case, parameters contained in both the command line and the parameter file have the priority.
The IMP Command Below is the syntax of the IMP program. Syntax: IMP <parameter1, parameter2, parameterN..>
Arguments: Note that some commands have a value of Y or N indicating their state. The default value for these commands is indicated in parentheses. USERID User name/password. BUFFER Size of data buffer. If 0 is specified, only one row will be copied at a time. Tables with the data types long, lob, bfile, ref, rowid, and logical rowid have their rows copied one at a time. FILE=fil Input file. The default is expdat.dmp. The default extension is DMP. SHOW=y/n Lists the contents of the file (N).
418
Import—Chapter 24
GRANTS Determines that IMP must import the Grants permissions (Y). INDEXES Specifies if the index must be imported (Y). ROWS Indicates whether IMP imports lines of data (Y). CONSTRAINTS Specifies when Import must import restrictions (constraints) (Y). DESTROY=y/n Rewrites the data file of the tablespace (N). LOG=file File of screen output. INDEXFILE=file Writes the index/table in the file specified. CHARSET= Specifies the set of NLS characters that is used. SKIP_UNUSABLE_INDEX=y/n Indicates that indexes that are not being used are not updated (N). HELP=y/n Displays the text of help (N). ANALYZE=y/n Executes the ANALYZE command in the file dump (Y). FEEDBACK=n Specifies that Import must display a progress meter for each n row processed. The default is 0. FILESIZE=value Maximum size of every file. VOID_NOVALIDATE Does not execute the validation of type of IDs specified.
419
Chapter 24—Import
RECALCULATE_STATISTICS Recomputes the statistics (N). VOLSIZE=value Number of bytes of the file in each volume of a file on tape. FULL Imports entire file (N). FROMUSER Lists the names of users who are owners of the objects. TABLES Specifies that the import is of type table, and lists the names of tables and partitions that are being imported. RECORDLENGTH Size of I/O record. INCTYPE=system/restore Specifies that the import type system restores the most recent version of the objects, or all of them, except for those of system. The default is none. TOUSER Displays the list of user names. PARFILE=file Specifies the name of a parameter file, which is a text file with a list and value file. COMMIT=y/n Writes the lines after each insertion (Y).
Obtaining Help By specifying Y in the Help parameter, the user can obtain a list of the program parameters. Take a look at the following:
420
Import—Chapter 24 Import: Release 8.1.3.0.0 - Development on Wed Jun 24 10:29:13 1998 (c) Copyright 1998 Oracle Corporation. All rights reserved. You can let Import prompt you for parameters by entering the IMP command followed by your username/password: Example: IMP SCOTT/TIGER Or, you can control how Import runs by entering the IMP command followed by various arguments. To specify parameters, you use keywords: Format: IMP KEYWORD=value or KEYWORD=(value1,value2, ...,valueN) Example: IMP SCOTT/TIGER IGNORE=Y TABLES=(EMP,DEPT) FULL=N or TABLES=(T1:P1,T1:P2), if T1 is partitioned table USERID must be the first parameter on the command line. Keyword Description (Default) ------------------------------------------------------USERID username/password BUFFER size of data buffer FILE input files (EXPDAT.DMP) SHOW just list file contents (N) IGNORE ignore create errors (N) GRANTS import grants (Y) INDEXES import indexes (Y) ROWS import data rows (Y) LOG log file of screen output DESTROY overwrite tablespace data file (N)
421
Chapter 24—Import INDEXFILE
write table/index info to specified file CHARSET character set of export file (NLS_LANG) SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N) ANALYZE execute ANALYZE statements in dump file (Y) FEEDBACK display progress every x rows(0) TOID_NOVALIDATE skip validation of specified type ids FILESIZE maximum size of each dump file RECALCULATE_STATISTICS recalculate statistics (N) VOLSIZE number of bytes in file on each volume of a file on tape FULL import entire file (N) FROMUSER list of owner usernames TOUSER list of usernames TABLES list of table names RECORDLENGTH length of I/O record INCTYPE incremental import type COMMIT commit array insert (N) PARFILE parameter filename CONSTRAINTS import constraints (Y) Import terminated successfully without warnings.
Importing Data from the Schema Itself To import, you need at least the CREATE SESSION privilege or the CONNECT role. The import can be made even when another user created the export file, as long as you have the IMP_FULL_DATABASE role.
422
Import—Chapter 24
These are the privileges required for the import operation: Object Clusters Database links Triggers on tables Triggers in schemas Indexes Constraints Libraries Packages Synonyms Sequences Snapshots Stored functions Stored procedures Table data Table definitions Views Object types Foreign function libraries Dimensions Operators Indextypes
Privileges CREATE CLUSTER and tablespace quota, or UNLIMITED TABLESPACE CREATE DATABASE LINK and CREATE SESSION in the remote database CREATE TRIGGER CREATE ANY TRIGGER CREATE INDEX and tablespace quota, or UNLIMITED TABLESPACE ALTER TABLE CREATE ANY LIBRARY CREATE PROCEDURE CREATE SYNONYM CREATE SEQUENCE CREATE SNAPSHOT CREATE PROCEDURE CREATE PROCEDURE INSERT TABLE CREATE TABLE CREATE VIEW SELECT in the base table SELECT CREATE TYPE CREATE LIBRARY CREATE DIMENSION CREATE OPERATOR CREATE INDEXTYPE
Type of Privilege system system system system system object system system system system system system system object system system system system system system system
To import privileges that were granted to other users, the user who initiates the import operation must have the objects, or must have received them with the WITH GRANT OPTION option. To import objects to other users’ schemas, you must have the IMP_FULL_DATABASE role. When user definitions are imported, they are created with the CREATE USER command, and the users do not automatically receive the CREATE SESSION privilege. 423
Chapter 24—Import
Importing Data to Existing Tables The next example shows the attempt to import just the DEPT table of user Scott. Note that an error will occur, and a warning message will be displayed. In this case, the table was not created because it already existed.
Figure 24.1: An error message displays when a table cannot be imported.
Importing Objects from Other Users The import and export programs allow tables and objects to be copied among the users of a database. The following example shows how user Cindy can obtain a copy of all the objects of user Scott. To do that, we connect to the IMP program as user Cindy/Ramalho:
Figure 24.2: Connecting to the IMP program.
424
Import—Chapter 24
After confirming the expdat.dmp file used by Scott as the source, answer all the questions by pressing the Enter key. After entering the name of user Scott as the object owner, we confirm that we want all of them. This is the final result:
Figure 24.3: The result of the import process.
After the data is imported, we check Cindy’s objects. Using SQL*Plus, we connect as Cindy/Ramalho and query the USER_CATALOG view in the data dictionary:
Figure 24.4: Checking the USER_ CATALOG view.
425
Chapter 24—Import
Note that the tables and Scott’s other objects now have an identical copy assigned to another user. Also note that an error occurred relating to the EMP and DEPT tables, since Cindy already had a synonym called Dept that makes reference to the DEPARTMENT table of the user Demo. Therefore, the referential integrity constraints of EMP to DEPT will not be successful, generating the error. This chapter described Oracle’s Import utility. Another important utility in Oracle is DBVERIFY, which performs integrity checking on a database’s data structure. It is discussed in the next chapter.
426
Chapter 25
DBVERIFY DBVERIFY is a program specified in the command line. Its purpose is to perform a physical integrity check of a database’s data structure. It can also be used to check a database online, a backup file, or specific files of the database. Its execution in an offline database greatly increases the performance of this database.
DBVERIFY Syntax The syntax of this program is shown below: Syntax: DBV FILE=name START/END = Block address BLOCKSIZE = value LOGFILE= name FEEDBACK= y/n HELP=y/n PARFILE= name
Arguments: FILE Name of the database to be checked.
427
Chapter 25—DBVERIFY
START Address of initial block for checking. If omitted, the program begins checking from the first block. END Final block for checking. If omitted, checks from the last block. BLOCKSIZE This parameter is required only when the file to be checked does not have the default block size (2 KB). LOGFILE Specifies the file for log storage. If omitted, the output is sent to the monitor. FEEDBACK Displays a period for each n number of checked pages. HELP Enables the online help. PARFILE Specifies the name of the parameter file to be used.
Obtaining Help To obtain online help while using DBVERIFY, use the command shown in the following figure:
Figure 25.1: Obtaining help for DBVERIFY.
428
DBVERIFY—Chapter 25
The next example shows the checking of the system01.dbf file:
Figure 25.2: Checking the system file.
This program is used to check a backup file that will be restored, to prevent it from failing due to a corrupted file. This chapter examined the role of DBVERIFY in database verification operations. SQL*Loader, another Oracle import utility, is the topic of the next chapter.
429
Chapter 26
SQL*Loader SQL*Loader is a utility that imports data from external files to the Oracle database table. This program is quite similar to the IBM DB2 Load utility. The program accepts several formats of titles, and allows the filtering of records that will be loaded. The program can load several external files in the same session.
Working Schema SQL*Loader uses a control file called Loader Control File, which contains instructions for the execution, manipulation, and filtering of the records contained in the input datafiles.
Figure 26.1:
The anatomy of SQL*Loader.
431
Chapter 26—SQL*Loader
During execution, SQL*Loader produces a log file with the operation log. If there are records with problems in the input files, a file with the rejected records is produced.
Discarded or Rejected Records The records read from input files that cannot be inserted in the database are written in separate files for further checking or correction.
Bad File A bad file contains the records that were rejected by SQL*Loader or by Oracle. Normally, this occurs when the record format is invalid. A common situation is quotation marks missing in a field, or a field without the separation comma. After it is approved by SQL*Loader, the record is inserted in the database. However, Oracle can reject it when it violates some constraint.
Discard File SQL*Loader can also create a file called a discard file. The discard file is created when it was specified as activated. It contains the records that did not pass through the selection filter of the control files.
Log File When executed, SQL*Loader creates a log file containing detailed information about the data processing, including information about possible errors.
432
SQL*Loader—Chapter 26
The SQL*Loader Control File The control file specifies how data in the input file is treated, which tables will receive it, which conversions are made, and so on. This is a text document file, and the commands to be interpreted by SQL*Loader are written to it. They include the specification of the input file location, characteristics of rows and columns, specification of data types, and so on. The contents of the file depend on the type of data configuration. However, we can say that it is divided into three parts:
: : :
The first section contains general information, such as the INFILE option to specify the input file, the specification of the set of characters, or global options such as rows, records to skip, and so on. The second section may contain the INTO TABLE commands. Each of these commands contains information relating to the table that will receive data. The third section is optional and can store input data, turning the control file into a datafile.
The basic format of a control file is: LOAD DATA INFILE ‘NameOfFile.dat’ INTO TABLE NameOfTable (field1 POSITION(beginning:end) TypeOfData, field2 POSITION(beginning:end) TypeOfData, fieldN POSITION(beginning:end) TypeOfData)
433
Chapter 26—SQL*Loader
Following is an example of how this file can be created, where the EMP table is configured with data from the eggplant.dat file: LOAD DATA INFILE ‘eggplant.dat’ INTO TABLE emp (empno POSITION(01:04) INTEGER ename POSITION(06:15) job POSITION(17:25) mgr POSITION(27:30) sal POSITION(32:39) comm POSITION(41:48)
EXTERNAL, CHAR, CHAR, INTEGER EXTERNAL, DECIMAL EXTERNAL, DECIMAL EXTERNAL,
Input Datafiles The input datafiles contain information that will be configured for the tables. SQL*Loader can read input files in several formats:
: : :
Stream record format (default format) Fixed record format Variable record format
Stream Record Format This is the default format, where each physical record has its end indicated by a certain character. Normally, the newline character (“\n”) or a carriage return followed by a new line (“\r\n”) is used. This character depends on the platform used by Oracle. The datafile specification follows this format: INFILE [“str ‘terminator_string’”]
terminator_string is text specified with alphanumeric or hexadecimal characters. The hexadecimal format must be used only when the string contains newline or carriage return characters, or when it is in a character set different from that of the control file. 434
SQL*Loader—Chapter 26
If terminator_string is not specified, the newline character is assumed. Following is the example of a control file and the datafile for this format: load data infile ‘example.dat’ into table example fields terminated by ‘,’ optionally enclosed by ‘"’ (col1 char(6), col2 char(10))
The file example.dat: hello,world james,bond Mel,Gibson
Fixed Record Format With this format all the records and their fields have a fixed size, no matter what the contents. The specification of the datafile must follow this format: INFILE “fix n”
fix indicates that SQL*Loader should consider the datafile records as having the fixed size of n bytes. The next example shows a datafile with record size of 11 characters, where ten characters are for the record and one character for newline (the Enter key). The control file: load data infile ‘example.dat’ “fix 11" badfile ‘example.bad’ discardfile ‘example.dsc’
435
Chapter 26—SQL*Loader discardmax 999 truncate into table example (rown position(1-5), cmnt position(6-10))
The file example.dat: 00001abcde 00002fghij 00003klmno 00004pqrst 00005uvwxy
Variable Record Format This type of format allows records of variable size. It contains text and numeric fields. In every record, the first field must be specified to have the string separated by a space from the next field. The datafile is specified in the following format: INFILE “VAR n”
This example uses the variable format, where the first five characters of the record specify the record size: load data infile ‘example.dat’ “var 5" badfile ‘example.bad’ discardfile ‘example.dsc’ discardmax 999 truncate into table example fields terminated by ”," optionally enclosed by ‘"’ (rown, cmnt, len)
436
SQL*Loader—Chapter 26
The file example.dat: 0001500001,a,00015, 0005000002,abcdefghijklmnopqrstuvwxyzABCDEFGHIJ,00050, 0005900003,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRS, 00059, 0005200004,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL,00052, 0004800005,abcdefghijklmnopqrstuvwxyzABCDEFGH,00048,
The SQLLDR.EXE Program The SQL*Loader program, as with the Export and Import programs, is executed from the command line. It can use a parameter file or receive the parameters directly in the command line. This is the syntax of the SQLLDR.EXE program: SQLLDR keyword=value [,keyword=value,...] Valid Keywords userid control log bad data discard discardmax skip load errors rows
Description ORACLE username/password. Name of control file. Name of log file. Name of bad file. Name of input datafile. Name of discard file. Number of discards allowed (use all as the default). Number of logic records for skipping (use 0 as the default). Number of logic records for loading (use all as the default). Number of errors allowed (use 50 as the default). Number of lines in the conventional path, or direct data saves (default: conventional path 64, direct path to all). 437
Chapter 26—SQL*Loader
Valid Keywords bindsize silent
direct parfile parallel file skip_unusable_indexes skip_index_maintenance commit_discontinued readsize
Description Size of conventional path bind array in bytes (use 65536 as the default). Suppress messages during the execution (header, feedback, errors, discards, and partitions). Use direct path (use FALSE as the default). Name of parameter file. Enables parallel loading (use FALSE as the default). File for allocating extensions (extents). Disables/enables index partitions (use FALSE as the default). Do not keep indexes (use FALSE as the default). Commit loading lines when its loading is discontinued (use FALSE as the default). Size of read buffer (use 65535 as the default).
Control File Commands Here are some of the main commands of the control file. See the documentation of your original Oracle software for details.
Comments To insert comments in the control file, you begin with two hyphens. Example: --File test.ctl
438
SQL*Loader—Chapter 26
Load Data This is a mandatory command that tells SQL*Loader to configure data.
Infile This specifies the input datafile. If the filename extension is omitted, .dat is assumed. If an asterisk is specified, the program assumes that data is inside its own control file, after the word BEGINDATA. Examples: INFILE * INFILE test.dat INFILE ‘c:/topdir/subdir/datafile.dat’
Append/Replace/Truncate If the tables to be configured are empty, you can use the INSERT option. If the tables have contents, the options APPEND, REPLACE, or TRUNCATE can be used. APPEND adds the rows to the end of the table, REPLACE deletes all the rows of the table before inserting new ones, and TRUNCATE adds the rows in an attempt to obtain the best performance. Warning: REPLACE and TRUNCATE replace all data in the table, not just the data of the rows that are inserted.
439
Chapter 26—SQL*Loader
Delimiters Special characters can delimit fields of type char, date, or numeric external. The delimited fields can be enclosed in a character or terminated by another character.
Terminated Fields Fields with the TERMINATED option are read from the initial position until an occurrence of the specified character is found. TERMINATED BY WHITESPACE indicates that the field ends when a blank space, a tab, or a new line is found.
Enclosed Fields These are fields enclosed inside specific characters. Type TERMINATED BY WHITESPACE OPTIONALLY ENCLOSED char AND
Description Data are read until the first occurrence of the character. Delimits the field with a blank space. Optionally, fields can be enclosed inside the specified character. Specifies an opening character and a closing character for the field.
Here are some examples: TERMINATED BY ‘,’ a data string, ENCLOSED BY ‘"’ a data string" TERMINATED BY ‘,’ ENCLOSED BY ‘" , ENCLOSED BY “(” AND ‘)’(a data string)
440
SQL*Loader—Chapter 26
WHEN This is an option used to filter input records. Example: WHEN (DEPTNO = ‘10’) AND (JOB = ‘SALES’)
INTO TABLE This specifies the table that will receive data. Examples: INTO TABLE SCOTT.dept INTO TABLE emp INTO TABLE SCOTT."-COMMENT"
Columns and Fields A column must have its configuration established through the specification of its name, size, data type, and whether the columns of the datafile are in the same sequence or the same number of columns that the table will receive.
TRAILING NULLCOLS The TRAILING NULLCOLS option declares that columns must be configured relative to the positioning. In the case of files with fixed size, you need to specify the position of the fields using the POSITION option, with the following syntax:
441
Chapter 26—SQL*Loader
Syntax Start End * +N
Description Initial position. Final position. Specifies that the field follows the field immediately before. Indicates that the field is moved +n characters from its current position.
Example: ENAME POSITION (1:20) CHAR EMPNO POSITION (22-26) INTEGER EXTERNAL ALLOW POSITION (*+2) INTEGER EXTERNAL TERMINATED BY “/”
Practical Example In the following example, we use the DEPT1 table of user Cindy, which was copied with the IMPORT command in Chapter 24. This is the structure of the table: SQL> describe dept1; Name -----DEPTNO DNAME LOC STATE
Null? -------NOT NULL
Type -----------NUMBER(2) VARCHAR2(10) VARCHAR2(9) VARCHAR2(4)
Current contents of DEPT1: SQL> SELECT * FROM DEPT1; DEPTNO DNAME ------ ----10 bbbb
442
LOC ----bbbbb
STAT ----
SQL*Loader—Chapter 26
The Control File The following text belongs to the filldep.ctl file. This text file is created with the Windows Notepad. -- PROGRAM: FILLDEP.CTL load data infile * append into table dept1 fields terminated by “,” optionally enclosed by ‘ “ ‘ trailing nullcols (deptno,dname,loc,stat) BEGINDATA 20,”MARKETING","SPAIN", 30,"ACCOUNTING","DALLAS","TX" 40,"SALES","MIAMI","FL"
The LOAD DATA command is required at the beginning of the file, after the comment lines. Arguments: INFILE * Indicates that data is in its own control file. APPEND Indicates that data is added to the end of the table. INTO TABLE Indicates that data is loaded to the table. FIELDS TERMINATED BY Indicates that fields end with commas, but they can be enclosed in quotation marks. As default, all the fields are treated as char. BEGINDATA Specifies the beginning of the data area.
443
Chapter 26—SQL*Loader
Note that the record with the code 20 does not have data in the last field. The following screen shows the Sqlldr program being enabled for user Cindy/Ramalho. The program asked for the name of control file, and filldep was specified:
Figure 26.2: Specifying the name of the control file.
The contents of the DEPT1 table after the program is executed: SQL> select * from dept1; DEPTNO DNAME LOC ------ ---------------10 bbbb bbbbb 30 “ACCOUNT” “DALLAS” 40 “SALES” “MIAMI”
STAT ---“TX” “FL”
The record with code 20 was not copied, since it was incomplete. Checking the directory where the filldep file is located, we notice the existence of two other files, one with the extension .log, and the other with the extension .bad.
Figure 26.3: Generating the .log and .bad files.
444
SQL*Loader—Chapter 26
The LOG File This is the content of the file generated: SQL*Loader: Release 8.1.5.0.0 - Production on Sun Feb 27 21:31:08 2000 (c) Copyright 1999 Oracle Corporation. All rights reserved. Control File: FILLDEP.ctl Data File: FILLDEP.ctl Bad File: FILLDEP.bad Discard File: none specified (Allow all discards) Number to load: ALL Number to skip: 0 Errors allowed: 50 Bind array: 64 rows, maximum of 65536 bytes Continuation: none specified Path used: Conventional Table DEPT1, loaded from every logical record. Insert option in effect for this table: APPEND TRAILING NULLCOLS option in effect
445
Chapter 26—SQL*Loader Column Name Position -------------------------- -------DEPTNO FIRST Enclosure string : ‘ “ ‘ DNAME NEXT Enclosure string : ‘ ” ‘ LOC NEXT Enclosure string : ‘ “ ‘ STAT NEXT Enclosure string : ‘ ” ‘
Len Term --- ---* ,
Encl ----
Data Type --------CHARACTER
*
,
CHARACTER
*
,
CHARACTER
*
,
CHARACTER
Record 1: Rejected - Error on table DEPT1. ORA-01401: inserted value too large for column Table DEPT1: 2 Rows successfully loaded. 1 Row not loaded due to data errors. 0 Rows not loaded because all WHEN clauses were failed. 0 Rows not loaded because all fields were null. Space allocated for bind array: 65016 bytes(63 rows) Space allocated for memory besides bind array: 0 bytes Total Total Total Total
logical logical logical logical
records records records records
skipped: 0 read: 3 rejected: 1 discarded: 0
Run began on Sun Feb 27 21:31:08 2000 Run ended on Sun Feb 27 21:31:11 2000 Elapsed time was: 00:00:02.83 CPU time was: 00:00:00.06
446
SQL*Loader—Chapter 26
The Bad File The bad file shows the rejected record: 20,"MARKETING","SPAIN",
With this chapter, we close the part about Oracle’s utilities. See the product manual for more details about each program. The next section covers using Oracle on the Internet.
447
Part VII
INTERNET RESOURCES This last part explains how to use Oracle’s publishing wizard to create HTML pages containing queries made to the database. Chapter 27: Oracle Web Publishing Assistant
449
Chapter 27
Oracle Web Publishing Assistant The Oracle Web Publishing Assistant allows the creation of Web page queries. Browsers such as Internet Explorer or Netscape Navigator can view these queries. To use this product, you must access an Oracle database. The Oracle Web Publishing Assistant allows the creation of a page with automatic or manual data update. The creation is done in four steps, where the user must connect to the database, select the table and columns that will be displayed, and indicate the name and place for the page to be created, as well as the type of update. The page can be created with a default or customized template. The Assistant maintains pages created with the option to update at regular intervals; those that do not need this option are directly created, and thus the Assistant has no control over them. The Assistant uses a Java applet to update the page.
Creating a Page To create a page, first open the Publishing Assistant. The first screen guides the reader to click the Create Web Page button to execute the Assistant:
451
Chapter 27—Oracle Web Publishing Assistant
Figure 27.1: The initial screen of the Assistant.
This initial screen hides the Assistant. It is suggested that you uncheck the Show this screen box, so the next time Web Publisher is invoked, the main screen of the program appears immediately, rather than the Assistant screen. To proceed, click on Create Web Page. In the following screen enter the user name and password:
Figure 27.2: Entering the user name and password.
452
Oracle Web Publishing Assistant—Chapter 27
If you access the local database, click on Next. In this step, you choose to create a page based on the database hierarchy, or a SQL command to filter the desired rows.
Figure 27.3: Selecting data for the Web page.
Let’s use the Build a Query option, in which the Assistant itself creates the appropriate SQL commands. In this step, you must choose the table or group of tables and columns that will be displayed in the page. To perform this task, click on the plus sign next to the local database to expand the object tree. Then, you need to choose the user and table to be displayed. Let’s choose the EMP table of user Scott.
453
Chapter 27—Oracle Web Publishing Assistant
Figure 27.4: Choosing a file to display.
As the default, all the columns are displayed. However, in this example we eliminate two of them. Clicking on the plus sign next to the table name displays the columns. To delete it, click on its name to uncheck it. The next figure shows that the Comm and Mgr columns are unchecked:
Figure 27.5: Getting ready to delete columns.
454
Oracle Web Publishing Assistant—Chapter 27
The Specify Additional Query Criteria Button This button allows including additional clauses to the SELECT command used to create the query. You can use the WHERE or ORDER BY clauses, for example, to customize your query. If you select the EMP table of user Scott, the current query will be displayed as: SELECT comm, deptno, empno, ename, hiredate, job, mgr, sal FROM scott.emp
You could enter the customizing clause in the provided field as: WHERE sal > 1000
In this example, we do not add anything to the basic query. After clicking on Next, the third step is displayed. You enter the frequency of page update. The options are:
:
: : : : :
At Regular Intervals—In this case, you must select the interval, days, minutes, hours, and the amount. Specify time intervals to which the Web Assistant must create your Web page. It will generate it immediately, and then will repeat the operation at the time interval specified. The time counting starts when you finish the query design, and is limited to an interval of 31 days (744 hours). Once—This option asks you to specify the month, day, year, and hour of page generation. On Day(s) of the Week—Allows selecting the day and hour for generation. On Day(s) of the Month—Allows selecting monthly date and hour for the page creation. Immediately—Generates the page only once. Manually—Generates the page only when the Assistant’s Generate button is clicked.
455
Chapter 27—Oracle Web Publishing Assistant
:
When data change—Select this programming option to automatically update your Web page whenever database data is changed. This programming option will only be available if you select a table or column(s) in a table through the database hierarchy.
In the example, we use the Immediately option, which works as an instant photograph. After it is generated, the Assistant has no update control over it. Other options allow the Assistant to update, change, or delete a page. In this case, it maintains a list of pages to be managed.
Figure 27.6: Specifying when to create the Web page.
After clicking on Next, the last step is displayed. You choose the directory—either local network or Internet—where the page will be located. As the default, Oracle creates a page called Web.htm in the following directory: D:\ORACLE\ORA81\ASSISTANTS\OWAST\WEB.HTM
456
Oracle Web Publishing Assistant—Chapter 27
Figure 27.7: Creating the default page.
Oracle allows creating a simple page, using the default template or a file customized by the user. Let’s use the default and click on Finish. The Assistant generates the page, and shows a success message:
Figure 27.8: A message indicating the page was successfully created.
When you click on the OK button, the default screen of the Assistant is shown. To view it, just specify your correct address in the address line of your browser. 457
Chapter 27—Oracle Web Publishing Assistant
It would not receive a design award, but it does serve the purpose of publishing in the Web. The type of generation used—immediate—closes the links of the Assistant with the page. Now we will create another page based on the DEPT table. This page will be created with the option to update it regularly.
Creating and Maintaining an Updatable Web Page Configure the Assistant. If you unchecked the display option in the first screen, the main screen of the program will be displayed. Click on the New button to start the Assistant:
Figure 27.9: The main screen.
After completing the first step, we will choose the DEPT table.
458
Oracle Web Publishing Assistant—Chapter 27
Figure 27.10: Selecting the data to be used in the Web page.
Then, we choose the At Regular Intervals update option, and set the frequency to one minute, i.e., each minute the page will be re-created.
Figure 27.11: Setting the update frequency.
459
Chapter 27—Oracle Web Publishing Assistant
After clicking on the Next button, we enter the name and directory of the page: D:\ORACLE\ORA81\ASSISTANTS\OWAST\WEBdept.HTM
Then we click on the Finish button. Now the page appears in the Assistant’s list of pages:
Figure 27.12: After the page is created, it appears on the list of pages.
Remember that the pages are updatable only if the Assistant is configured properly.
Using Publishing Assistant Now we will discuss some of the daily tasks with the Publishing Assistant. These include generating and deleting queries, and changing the properties of a query.
460
Oracle Web Publishing Assistant—Chapter 27
Generating a Query of a Stored Web Page To generate a query of a stored Web page, follow these steps: 1. Select the Web page query by clicking the name of the file displayed in the list. 2. Click on Generate, or choose Generate in the Web Page menu. (If you prefer, you may click with the right mouse button, and choose Generate in the pop-up menu.) To view the Web page, click on View. The Assistant starts your Web browser and loads the page.
Deleting a Query of a Stored Web Page To delete a query of a stored Web page, you do the following: 1. Select the file you want to delete by clicking on the name of the file. 2. Click on Delete, or choose Delete in the Web Page menu. (If you prefer, click with the right mouse button, and choose Delete in the pop-up menu.) Note that using the Delete button doesn’t delete the HTML file (.HTM) or the template (.HTX) associated to this query.
Checking and Changing the Properties of a Query To check and change the properties of a query to a stored Web page, follow these steps: 1. Select the file in the list by clicking on the name of the file. 2. Click on Properties, or select Properties in the Web Page menu.
461
Chapter 27—Oracle Web Publishing Assistant
The Properties dialog box, which includes several tabs, is displayed. These include the following:
Login Information Tab The property screen of the Login Information tab shows the user name, password (encrypted), and database name provided when you create a query. You can edit any field in the Login Information tab. Click on Apply or on OK to save your changes.
Query Tab The property screen of the Query tab shows the SQL instruction representing the defined query. You can edit the query in the field provided. Click on Apply or on OK to save the changes. If the programming option of this Web page query is When Data are Changed, you can only change the query if you change the programming option to a different option. If you change the text, a dialog box called Modify Template displays.
Figure 27.13: The Modify Template dialog is used to change the text of a query.
462
Oracle Web Publishing Assistant—Chapter 27
Modify Template Dialog Box The Oracle Web Publishing Assistant finds any change in your query. It is likely you will have to change the template associated to the query in order to generate the desired results. Select one of the following options and click on OK:
: : : :
Retain the current template—Select this option to use the same template. Generate a default template—Select this option to generate a default template based on the new specified query. Edit the current template—Select this option to edit your current template. The Oracle Web Publishing Assistant starts, as well as the default editor for the default templates. Select a different template—Select this option to specify a different template file. Click on Browse and insert the complete path, with the filename of a different template.
Scheduling Tab The property screen of the Scheduling tab displays the scheduling options, that is, the dates and times specified to update your Web page. You can change your scheduling options in this screen. Below are the options:
: : : : : :
Once On Day(s) of the Week On Day(s) of the Month At Regular Intervals When Data Change Manually
The When Data Change option will only be displayed when the Web page query was originally programmed with this option.
463
Chapter 27—Oracle Web Publishing Assistant
File Options Tab The property screen of the File Options tab displays the path and filename of the Web page that will be created, and the template to be used to update this page. You can change your file options and edit the template in this screen:
Figure 27.14: The File Options tab.
To edit a template, first click on Edit. The program associated to the .HTX (template) files is started. If there is no program associated to this type of file, Notepad starts.
Figure 27.15: Editing a template in Notepad.
464
Oracle Web Publishing Assistant—Chapter 27
Then edit the template and save your changes. NOTE: The Query ID field shows a number that can be used as a reference when you contact Oracle Worldwide Support to obtain information about the errors.
Creating a customized template by changing the .HTX file requires some knowledge of the HTML language. Be careful not to change the variable names. This is the change.htx file of the last query: <meta http-equiv="Content-Type" content="text/html"> Department List Department List
465
Chapter 27—Oracle Web Publishing Assistant
This is the html code generated by the changed template: <meta http-equiv="Content-Type" content="text/html"> Department List Department List
Remember that if you insert images in the figure, they must be in the directory where the htm program was generated, or have their path correctly specified.
466
Index %FOUND, 357, 359 %ISOPEN, 357, 359 %NOTFOUND, 358, 359 %ROWCOUNT, 358, 359 A aliases, 275 ALL views, 57-58 ALTER INDEX command, 211-212 ALTER SEQUENCE command, 224 ALTER TABLE command, 123, 182 ALTER TRIGGER command, 317 API, 380 application programming interface, see API application server, 30, 384 archiver, 18 ARCn, see archiver arithmetic operators, 137 audit trail, 38 audits, 37-38 autonomous transactions, 372-373 AVG function, 144 B B*-tree index, 86 background processes, 16 backups, see database backups base tables, 24, 55, 231 binary data type, 135 built-in SQL declarations, 46 business rules, 52 C character data type, 133-134 character operators, 137 CHECK, 53 CHECK constraint, 162, 164 checkpoint, 17
child table, 164 CKPT, see checkpoint client, 29, 377, 384 client/server architecture, 377 benefits of, 379-380 CLOSE command, 361 cluster keys, 27 clustered tables, 26-27 clusters, 26, 87 column, adding, 184-185 changing, 183-184 deleting, 185-186 referencing inside triggers, 318 COLUMN command, syntax, 110 using, 110-115 commands, editing, 106-108 line editing, 104-105 COMMIT command, syntax, 151 using, 151-153 communication protocol, 380 comparison operators, 137-138 complete export, 413 composite index, 204 compressed index, creating, 210-211 conflict detection, 397 constants, 291 constraints, 162 deferred, 167-168 disabling, 180-181 enabling, 182-183 types of, 163-166 control files, 10-11, 42 using, 11
467
Index control structures, 292-293 COUNT function, 144 CREATE FUNCTION command, syntax, 338-341 using, 341-342 CREATE INDEX command, 123 syntax, 206-207 using, 207-209 CREATE PACKAGE BODY command, 346-347 CREATE PACKAGE command, 346 CREATE PROCEDURE command, syntax, 331-333 using, 334-335 CREATE ROLE command, syntax, 269-270 CREATE SCHEMA command, syntax, 246 using, 246-247 CREATE SEQUENCE command, 217-218 CREATE SYNONYM command, 276 CREATE TABLE command, 123 syntax, 170-172, 188-201 CREATE TABLESPACE command, 187 CREATE TRIGGER command, 314-317 CREATE USER command, syntax, 250-252 using, 252 CREATE VIEW command, syntax, 234-235 using, 235-236 cumulative export, 413 current row, 353 currval, 219-220 cursor rows, accessing, 359-360 cursors, 14, 287, 353-354 closing, 361 creating, 354 declaring, 354-356 examples of, 361-362 opening, 356 types of, 353
468
D data, accessing, 43-44 data blocks, 7, 74 components of, 74-75 data consistency, 31-32 data definition language, 123 declarations, 45 data dictionary, 28, 55 structures, 55-56 views, 59-66 data integrity, 52, 148, 159-160 data manipulation language, 123 declarations, 45 data security, 33 data segments, 8, 77 data type synonyms, 132-133 data types, 130-131 Oracle 8, 131-132 data validation, 319 database backups, 43-44 database buffer cache, 13 database failures, 39-40 database links, 28, 90 database recovery, 40-43 database server, 384 database structure, 3-4 database triggers, see triggers database writer, see DWBn datafiles, 9, 71-72 using, 10 date data type, 134 DBA views, 58 DBA_TRIGGERS view, 326 DBVERIFY, 427 syntax, 427-428 DDL, see data definition language declaration handle, see cursors declaration section, 289 declarations, 367 see also SQL declarations DECLARE command, 354-355 DELETE command, 123 syntax, 149-150
Index delimiters, 440-442 DESCRIBE command, 109 syntax, 282-283 dictionary-managed tablespaces, 69 discretionary transaction management, 366-367 dispatcher, 18 distributed databases, 30-31 distributed processing, 29, 378-379 DML, see data manipulation language DROP INDEX command, 123 syntax, 214 DROP PACKAGE command, 350 DROP PROCEDURE command, 337-338 DROP ROLE command, 272 DROP SEQUENCE command, 223 DROP SYNONYM command, 279 DROP TABLE command, 123 syntax, 186 DROP TRIGGER command, 318 DROP USER command, 255 DROP VIEW command, 240 dual table, 59 DVERIFY, using Help in, 438 DWBn, 16 dynamic performance tables, 59 E EDIT command, 118 errors, correcting, 105 finding, 320-321 exception section, 291 execution section, 291 EXP command syntax, 403-406 explicit cursors, 353 attributes of, 357-358 export methods, 402-403 types, 413 Export program, executing, 408-410 Export utility, 401-402 execution modes, 403
using Help in, 406-408 exporting, 410-412 extended rowid, 136 extents, 7, 77 F FETCH command, 360 FOR..LOOP command, 296-297 using, 302-303, 362-363 foreign key, 53 FOREIGN KEY, 53 FOREIGN KEY constraint, 162, 164-165 free blocks, 77 function-based indexes, 209-210 functions, 25, 50, 88, 142-143, 338 creating, 338-342 examples, 143-145 executing, 342-343 G GET command, 117-118 GRANT command, 123 syntax, 253-254, 260-262 using, 254-255, 262-264 group functions, 142 H hash clusters, 27, 88 I IF..THEN command, 293-295 using, 304 IMP command syntax, 418-420 implicit cursors, 353 attributes of, 358-359 import methods, 416 Import utility, 415 execution modes, 417-418 using Help in, 420-422 importing, 422-426 privileges required for, 423 incremental export, 413 index segments, 8, 77 index-organized tables, 186-187
469
Index indexes, 26, 85-87, 203-205 and constraints, 205-206 creating, 205-211 deleting, 214 modifying, 211 obtaining information about, 212-213 re-creating, 212 unique, 204 when to create, 205 indexes, composite, see composite index input datafiles, 434 formats for, 434-437 INSERT command, 123, 145-146, 243 syntax, 146, 243 using, 146-148 instance, 4-5 INSTEAD OF triggers, 312 integrity, types of, 160-161 integrity constraints, see constraints integrity restrictions, 52-53 interface functions, 19 J job queue, 19 join view, 84 creating, 236-238 K key, 53 key compression, 210 key values, 53 key-preserved tables, 241 L large pool, 14 LGWR, 17 listener process, 382 local database, 31 locally managed tablespaces, 69-70 lock, 18 log writer, see LGWR logical database, 4 structures, 6-9 logical operators, 138
470
LOOP command, 295-296 M master groups, 386-387 master site, 387 materialized views, 90-91, 245 MAX function, 144 memory structures, 11-15 methods, 51 MIN function, 144 multimaster replication, 389-390 multiplexed control files, 42 multitiered architecture, 30, 383 N Navigator, using to create packages, 347-349 nested tables, 82 Net8, 21, 380-382 using, 381 nextval, 219-220 node, 31 NOT NULL, 52 NOT NULL constraint, 162, 163 nulls, 160 number data type, 133 O object privileges, 259-260 granting, 260-264 revoking, 266 object relational model, 23 online redo log, 41 OPEN command, 356 operator precedence, 137 operators, types of, 137-138 using, 139-142 Oracle and SQL, 122 configuration process, 20-21 database structure, 3-4 packages, 351 processes, 5, 15 server, 3
Index Oracle instance, see instance Oracle Web Publishing Assistant, 451 creating web page with, 451-458 using queries with, 461-466 Oracle 8 data types, 131-132 Oracle8i roles, 268 P package body, 346-347 packages, 25, 50, 89, 287, 345 creating, 344-347 creating in Navigator, 347-349 deleting, 350 recompiling, 349-350 referencing subprogram in, 349 structure of, 345-347 packages, Oracle, 351 PARENT KEY, 164-165 parent table, 164 partial backups, 43 PCTFREE, 75-77 PCTUSED, 75-77 PGA, see program global area physical database, 3-4 structures, 8-11 PL/SQL, 49, 287 advantages of, 49 commands, 154-155 integrating SQL into, 298-300 PL/SQL blocks, 288 autonomous, 373-374 components of, 288-291 PMON, see process monitor primary key, 53 values, 161 PRIMARY KEY, 53 PRIMARY KEY constraint, 162, 164 privileges, 35, 256 for importing, 423 granting, 36, 253-255, 260-264 granting roles to, 270 revoking, 265-266 types of, 257
procedure replication, 396 procedures, 25, 50, 88 process, 14 process architecture, 14-20 process monitor, 17-18 processes, 4-5, 11 program global area, 14 program interface, 19 program unit, 25 pseudo-columns, 219 Q queries, using with Oracle Web Publishing Assistant, 461-466 queue monitor, 19 R read-only tablespaces, 70 RECO, see recoverer records, discarded, 432 rejected, 432 recoverer, 18 recovery, see database recovery redo log, 40 redo log buffer, 13 redo record, 10 redo record files, 10-11 using, 11 referenced key, 53 referential integrity, 161 relational model, 22 remote database, 31 RENAME SYNONYM command, 279 replicated masters, 394 replication, 32, 385 catalog, 395 conflicts, 395-398 groups, 386-387 multimaster, 389-390 object, 385-386 sites, 387-388 snapshot, 390, 392
471
Index replication environment, managing, 395 restricted rowid, 136 result set, 353 REVOKE command, 265-266 roles, 36-37, 90, 267 creating, 268-269 deleting, 272-273 granting privileges to, 270 granting roles to, 270 granting to users, 271 Oracle8i, 268 viewing user’s, 271-272 ROLLBACK command, 151 using, 152-153 rollback segments, 8, 42, 78 rollbacks, 371 types of, 370 rolling back, 370-372 rowid, 80-81, 203, 220-222 rowid data type, 135-136 row-level triggers, 310-311 rownum, 221-222 S SAVE command, 116-117 savepoints, 48-49, 371-372 schema, 4, 7, 23, 32 schema object privileges, 35-36 schema objects, 4, 23, 79 obtaining information about, 281-282 security, 32-33 resources, 33-34 security domain, 35 segments, 8, 77-78 SELECT command, 123 syntax, 124-128 using, 124-130 using in view, 239-240 SELF-REFERENTIAL constraint, 165-167 sequence, default, 217 sequences, 24, 84-85, 217 creating, 222 deleting, 223
472
modifying, 224-225 obtaining information about, 222-223 using, 225-229 server, 29, 377 server processes, 15-16 session control declarations, 46 set operators, 138 SGA, see system global area shared pool, 13 single-row functions, 142 SMON, see system monitor snapshot group, 386-388 snapshot replication, 390 using, 392 snapshot sites, 386-388 snapshots, 90-91, 231, 245, 390 hybrid, 393-394 updatable, 391-392 using in disconnected environments, 393 space, allocating, 69-70 specification section, 345-346 SQL, 44-45, 121 and Oracle, 122 integrating into PL/SQL, 298-300 SQL declarations, 45-46, 122 SQL*Loader, 431 control file, 433 control file commands, 438-439 program, 437-438 schema, 431-432 using, 442-447 SQL*Plus, 95 commands, 102-104 configuring, 95-97 menus, 98-100 SQLLDR.EXE program, 437-438 START command, 118 statement-level triggers, 310-311 stored procedures, 287, 329 creating, 331-334 deleting, 337-338
Index executing, 335-337 Structured Query Language, see SQL synchronous data propagation, 397 synchronous data replication, 397-398 synonyms, 25, 85, 275 creating, 276-278 deleting, 279-280 renaming, 278-279 system backups, 43 system control declarations, 46 system event triggers, 312-313 system global area, 4, 12-13 system monitor, 17 system privileges, 35, 257-259 revoking, 265 system security, 33 System tablespace, 68
rolling back, 47-48, 370-372 triggers, 50, 54, 90, 161, 287, 307-308 components of, 309-310 creating, 314-317 deleting, 318 disabling, 317 enabling, 317 modifying, 317 obtaining information about, 326 referencing columns with, 318 replicating with, 322-323 restrictions on using, 308-309 types of, 310-313 two-phase commit, 31-32, 368-369 U UNIQUE, 52 unique key, 53 UNIQUE KEY constraint, 162, 163 unique values, 160 updatable web page, creating, 458-460 UPDATE command, 123 syntax, 149 using, 242-243 user, 91, 249 creating, 252-253 deleting, 255-256 granting roles to, 271 viewing, 264-265 viewing roles of, 271-272 user event triggers, 312-313 user processes, 4, 15 USER views, 56-57 USER_INDEXES view, 213 USER_SEQUENCES view, 223 USER_TRIGGERS view, 326-327 USER_VIEWS, view, 244 user-accessible view, 55
T table triggers, 310 tables, 24, 80-82 changing with views, 240-241 creating, 169-170, 173-180 creating multiple, 245-247 deleting, 186 index-organized, 186-187 modifying, 181 tablespaces, 6-7, 68 creating, 68-69 transporting, 71 types of, 69-71 temporary segments, 8, 78 tables, 82 tablespaces, 70-71 transaction control declarations, 45 transaction management, 366-367 discretionary, 366-367 transaction process language commands, 151 V transactions, 31-32, 46-47, 151, 365 variables, 289-290 autonomous, 372-373 views, 24, 82-84, 231-232 committing, 47-48, 368-369 advantages to using, 232-233 managing, 366-367
473
Index creating, 234-239 creating multiple, 245-247 deleting, 240 obtaining information about, 244 replacing, 243-244 restrictions on using, 233 using SELECT command in, 239-240 using to change tables, 240-241
474
views, materialized, see materialized views W web page, creating, 451-458 creating updatable, 458-460 WHILE command, 297 examples, 300-302 written redo log, 41-42