100% found this document useful (10 votes)
34 views

Practical Guide to Using SQL in Oracle 1st Edition Richard Walsh Earp All Chapters Instant Download

Guide

Uploaded by

zyrapikedit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (10 votes)
34 views

Practical Guide to Using SQL in Oracle 1st Edition Richard Walsh Earp All Chapters Instant Download

Guide

Uploaded by

zyrapikedit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Download the full version of the ebook at

https://ebookfinal.com

Practical Guide to Using SQL in Oracle 1st


Edition Richard Walsh Earp

https://ebookfinal.com/download/practical-guide-
to-using-sql-in-oracle-1st-edition-richard-walsh-
earp/

Explore and download more ebook at https://ebookfinal.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Database Systems Using Oracle A Simplified Guide to SQL


and PL SQL 2nd Edition Nilesh Shah

https://ebookfinal.com/download/database-systems-using-oracle-a-
simplified-guide-to-sql-and-pl-sql-2nd-edition-nilesh-shah/

ebookfinal.com

Murach s Oracle SQL and PL SQL for Developers 2nd Edition


Joel Murach

https://ebookfinal.com/download/murach-s-oracle-sql-and-pl-sql-for-
developers-2nd-edition-joel-murach/

ebookfinal.com

Treating Self Injury A Practical Guide 1st Edition Barent


W. Walsh Phd

https://ebookfinal.com/download/treating-self-injury-a-practical-
guide-1st-edition-barent-w-walsh-phd/

ebookfinal.com

SQL QuickStart Guide The Simplified Beginner s Guide to


SQL Clydebank Technology

https://ebookfinal.com/download/sql-quickstart-guide-the-simplified-
beginner-s-guide-to-sql-clydebank-technology/

ebookfinal.com
Oracle SQL Recipes A Problem Solution Approach 1st Edition
Grant Allen

https://ebookfinal.com/download/oracle-sql-recipes-a-problem-solution-
approach-1st-edition-grant-allen/

ebookfinal.com

Treating Self Injury Second Edition A Practical Guide


Barent W. Walsh Phd

https://ebookfinal.com/download/treating-self-injury-second-edition-a-
practical-guide-barent-w-walsh-phd/

ebookfinal.com

Healthy SQL A Comprehensive Guide to Healthy SQL Server


Performance 1st Edition Robert Pearl

https://ebookfinal.com/download/healthy-sql-a-comprehensive-guide-to-
healthy-sql-server-performance-1st-edition-robert-pearl/

ebookfinal.com

Expert PL SQL Practices for Oracle Developers and DBAs 1st


Edition John Beresniewicz

https://ebookfinal.com/download/expert-pl-sql-practices-for-oracle-
developers-and-dbas-1st-edition-john-beresniewicz/

ebookfinal.com

Working with Specialized Language A Practical Guide to


Using Corpora 1st Edition Lynne Bowker

https://ebookfinal.com/download/working-with-specialized-language-a-
practical-guide-to-using-corpora-1st-edition-lynne-bowker/

ebookfinal.com
Practical Guide to Using SQL in Oracle 1st Edition
Richard Walsh Earp Digital Instant Download
Author(s): Richard Walsh Earp
ISBN(s): 9781598220636, 1598220632
Edition: 1
File Details: PDF, 3.75 MB
Year: 2008
Language: english
Practical Guide to
Using SQL in Oracle ®

Richard Walsh Earp


and
Sikha Saha Bagui

Wordware Publishing, Inc.


Library of Congress Cataloging-in-Publication Data

Earp, Richard Walsh, 1940-


Practical guide to using SQL in Oracle / by Richard Walsh Earp and Sikha Saha Bagui.
p. cm.
Includes index.
ISBN-13: 978-1-59822-063-6
ISBN-10: 1-59822-063-2 (pbk.)
1. SQL (Computer program language. 2. Oracle (Computer file)
3. Database management. I. Bagui, Sikha Saha, 1964-. II. Title.
QA76.73.S67B344 2008
005.75'65--dc22 2008034585
CIP

© 2008, Wordware Publishing, Inc.


All Rights Reserved
1100 Summit Avenue, Suite 102
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-13: 978-1-59822-063-6
ISBN-10: 1-59822-063-2
10 9 8 7 6 5 4 3 2 1
0809

Oracle is a registered trademark and PL/SQL and SQL*Plus are trademarks of Oracle Corporation in the United
States and other countries. UNIX is a registered trademark of The Open Group in the United States and other
countries.
Other brand names and product names mentioned in this book are trademarks or service marks of their
respective companies. Any omission or misuse (of any kind) of service marks or trademarks should not be
regarded as intent to infringe on the property of others. The publisher recognizes and respects all marks used by
companies, manufacturers, and developers as a means to distinguish their products.
This book is sold as is, without warranty of any kind, either express or implied, respecting the contents of this
book and any disks or programs that may accompany it, including but not limited to implied warranties for the
book’s quality, performance, merchantability, or fitness for any particular purpose. Neither Wordware Publishing,
Inc. nor its dealers or distributors shall be liable to the purchaser or any other person or entity with respect to
any liability, loss, or damage caused or alleged to have been caused directly or indirectly by this book.

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
Dedicated to my wife, Brenda,
and
my children, Beryl, Rich, Gen and Mary Jo

R.W.E.

Dedicated to my father, Santosh Saha, and mother, Ranu Saha,


and
my husband, Subhash Bagui,
and
my sons, Sumon and Sudip,
and
my brother and his wife, Pradeep and Shyamasri, and nieces,
Priyashi and Piyali

S. S.B.
This page intentionally left blank.
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Prologue The Software Engineering Process and Relational Databases . . . . . . . . 1


What Is a Database? . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Database Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
The Hierarchical Model . . . . . . . . . . . . . . . . . . . . . . . 3
Other Cardinalities . . . . . . . . . . . . . . . . . . . . . . . 6
The Network Model . . . . . . . . . . . . . . . . . . . . . . . . . 8
Contemporary Databases: The Relational Model . . . . . . . . . 9
The First, Second, and Third Normal Forms . . . . . . . . . . . . . 11
The First Normal Form . . . . . . . . . . . . . . . . . . . . . . 12
Non-1NF to First Normal Form (1NF) . . . . . . . . . . . . 13
The Second Normal Form . . . . . . . . . . . . . . . . . . . . . 14
Non-2NF to 2NF. . . . . . . . . . . . . . . . . . . . . . . . 16
The Third Normal Form . . . . . . . . . . . . . . . . . . . . . . 18
Non-3NF to 3NF. . . . . . . . . . . . . . . . . . . . . . . . 19
What Is the Software Engineering Process?. . . . . . . . . . . . . . 20

Chapter 1 Getting Started with Oracle. . . . . . . . . . . . . . . . . . . . . . . . . 25


Getting Started with Oracle in UNIX . . . . . . . . . . . . . . . . . 26
Signing on to Oracle in UNIX . . . . . . . . . . . . . . . . . . . 26
Setting Your System Parameters . . . . . . . . . . . . . . . . . . . 27
Setting the PAUSE Parameter . . . . . . . . . . . . . . . . . . 28
Setting the Prompt Parameter. . . . . . . . . . . . . . . . . . . 28
Showing Timing Statistics . . . . . . . . . . . . . . . . . . . . . 29
Viewing a List of System Parameters . . . . . . . . . . . . . . . 29
Oracle’s HELP Command in UNIX . . . . . . . . . . . . . . . . 30
Using Oracle Commands . . . . . . . . . . . . . . . . . . . . . . . . 31
Understanding SQL and Its Sublanguage . . . . . . . . . . . . . 31
Using SELECT Statement Syntax . . . . . . . . . . . . . . . . . . . 32
Re-executing a Command . . . . . . . . . . . . . . . . . . . . . 33
Accessing Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

v
Contents

Adding Comments to Statements . . . . . . . . . . . . . . . . . . . 35


A Few More Examples and Further Comments about Case . . . 36
Editing SQL Statements . . . . . . . . . . . . . . . . . . . . . . . . 36
Option 1: Editing SQL Statements Using an Editor . . . . . . . 37
Defining an Editor . . . . . . . . . . . . . . . . . . . . . . . 37
Editing the Buffer . . . . . . . . . . . . . . . . . . . . . . . 37
Saving the Buffer . . . . . . . . . . . . . . . . . . . . . . . 39
Using GET . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Using a Script File to Save Your Query . . . . . . . . . . . 40
Option 2: Editing SQL Statements or Queries Using SQLPLUS 41
Using the CHANGE Command . . . . . . . . . . . . . . . . 41
Using the LIST Command . . . . . . . . . . . . . . . . . . 42
Using the APPEND Command . . . . . . . . . . . . . . . . 43
Using the INPUT Command . . . . . . . . . . . . . . . . . 45
Using INPUT to Insert a Line . . . . . . . . . . . . . . . . 47
Using the DELETE Command . . . . . . . . . . . . . . . . 49
Displaying the Student-Course Database . . . . . . . . . . . . . . . 50
Displaying the Course Table (the Course Relation) . . . . . . . 50
Creating a Synonym for the Course Table . . . . . . . . . . . . . . . 51
Deleting a Synonym . . . . . . . . . . . . . . . . . . . . . . . . 52
Introducing the Oracle Data Dictionary . . . . . . . . . . . . . . . . 52
Using DESC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using a Convention for Writing SQL Statements . . . . . . . . . . . 55
Printing Query Results and Using Host . . . . . . . . . . . . . . . . 56
Signing Off from Oracle . . . . . . . . . . . . . . . . . . . . . . . . . 58
Exercises for Chapter 1. . . . . . . . . . . . . . . . . . . . . . . . . 59

Chapter 2 More “Beginning” SQL Commands . . . . . . . . . . . . . . . . . . . . . 63


An Extended SELECT Statement . . . . . . . . . . . . . . . . . . . 63
SELECTing Attributes (Columns) . . . . . . . . . . . . . . . . 65
Using ORDER BY . . . . . . . . . . . . . . . . . . . . . . . . . 66
SELECTing Rows . . . . . . . . . . . . . . . . . . . . . . . . . 70
Using AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Using OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Using BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . 73
A Simple CREATE TABLE Command . . . . . . . . . . . . . . . . 75
Inserting Values into an Existing Table . . . . . . . . . . . . . . . . 76
INSERT INTO..VALUES . . . . . . . . . . . . . . . . . . . . . 76
INSERT INTO..SELECT . . . . . . . . . . . . . . . . . . . . . 79
The UPDATE Command . . . . . . . . . . . . . . . . . . . . . . . . 82
The DELETE Command . . . . . . . . . . . . . . . . . . . . . . . . 84
Deleting a Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
vi
Contents

ROLLBACK, COMMIT, and SAVEPOINT . . . . . . . . . . . . . . 85


The ALTER TABLE Command . . . . . . . . . . . . . . . . . . . . 92
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Common Number Data Types . . . . . . . . . . . . . . . . . . . 95
CHAR Data Type. . . . . . . . . . . . . . . . . . . . . . . . . . 97
VARCHAR2 Data Type . . . . . . . . . . . . . . . . . . . . . . 98
NCHAR and NVARCHAR2 Data Types. . . . . . . . . . . . . . 98
LONG, RAW, LONG RAW, and BOOLEAN Data Types. . . . . 99
Large Object (LOB) Data Types. . . . . . . . . . . . . . . . . . 99
Abstract Data Types . . . . . . . . . . . . . . . . . . . . . . . 100
The XML Data Type . . . . . . . . . . . . . . . . . . . . . . . 100
The DATE Data Type and Type Conversion Functions . . . . 101
Entering Four-Digit Years . . . . . . . . . . . . . . . . . . 105
Exercises for Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . 107

Chapter 3 Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111


The Cartesian Product. . . . . . . . . . . . . . . . . . . . . . . . . 112
The Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Join Using ANSI Join Syntax . . . . . . . . . . . . . . . . . . . 115
Theta Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Table Aliases and an Introduction to Multi-table Joins. . . . . . . . 118
More on Comments . . . . . . . . . . . . . . . . . . . . . . . . . . 119
More on Multiple Table Joins and Join Conditions . . . . . . . . . . 121
Column Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
COUNT and Rownum . . . . . . . . . . . . . . . . . . . . . . . . . 128
Using COUNT. . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Using Rownum . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Outer Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Left Outer Join . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Right Outer Join. . . . . . . . . . . . . . . . . . . . . . . . . . 132
Handling Full Outer Joins . . . . . . . . . . . . . . . . . . . . 133
Outer Join with an AND Condition . . . . . . . . . . . . . . . . 135
Chaining Outer Joins . . . . . . . . . . . . . . . . . . . . . . . 136
Self Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Self Join and Outer Join . . . . . . . . . . . . . . . . . . . . . . 139
Exercises for Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . 139

Chapter 4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145


The COUNT Function. . . . . . . . . . . . . . . . . . . . . . . . . 146
Using SELECT and COUNT with DISTINCT. . . . . . . . . . 148

vii
Contents

More Basic Functions . . . . . . . . . . . . . . . . . . . . . . . . . 149


Aggregate Functions. . . . . . . . . . . . . . . . . . . . . . . . . . 150
Row-level Functions. . . . . . . . . . . . . . . . . . . . . . . . . . 151
The NVL Function . . . . . . . . . . . . . . . . . . . . . . . . 151
String Functions . . . . . . . . . . . . . . . . . . . . . . . . . 152
The SUBSTR and INSTR Functions . . . . . . . . . . . . 153
The RPAD and LPAD Functions . . . . . . . . . . . . . . 157
The LTRIM and RTRIM Functions . . . . . . . . . . . . . 158
The LENGTH Function . . . . . . . . . . . . . . . . . . . 158
Matching Substrings Using LIKE . . . . . . . . . . . . . . 159
LIKE as an Existence Match . . . . . . . . . . . . . . . . 159
LIKE with a Positioned Match and a Wildcard . . . . . . . 163
The UPPER and LOWER Functions . . . . . . . . . . . . 164
The Data Dictionary Revisited . . . . . . . . . . . . . . . . . . . . 165
Exercises for Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . 167

Chapter 5 Query Development, Privileges, and Derived Structures . . . . . . . . . 175


Query Development . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Using SAVE and EDIT . . . . . . . . . . . . . . . . . . . . . . 176
Deleting a Query . . . . . . . . . . . . . . . . . . . . . . . . . 181
Parentheses in SQL Expressions . . . . . . . . . . . . . . . . . . . 182
Derived Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Using the CREATE OR REPLACE VIEW Statements . . 185
Adding ORDER BY to CREATE OR REPLACE
VIEW Statements . . . . . . . . . . . . . . . . . . . . 186
Developing a Query Using Views . . . . . . . . . . . . . . 188
Creating Special View Column Names . . . . . . . . . . . 188
Granting and Revoking Privileges on Tables and Views. . . . . . . 190
Query Development and Derived Structures . . . . . . . . . . . . 191
Step 1: Developing a Query Step-by-Step . . . . . . . . . . . . 192
Step 2: Using a Derived Structure . . . . . . . . . . . . . . . . 195
Option 1: Make Your Query a View . . . . . . . . . . . . . 195
Option 2: Create a Temporary Table . . . . . . . . . . . . 196
Option 3: Use an Inline View . . . . . . . . . . . . . . . . 197
Option 4: Use a Snapshot . . . . . . . . . . . . . . . . . . 199
Exercises for Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . 200

Chapter 6 Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205


UNION Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 206
The IN and NOT..IN Predicates . . . . . . . . . . . . . . . . . . . 208
Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

viii
Contents

Using NOT..IN . . . . . . . . . . . . . . . . . . . . . . . . . . 212


The Difference Operation . . . . . . . . . . . . . . . . . . . . . . . 217
Exercises for Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . 222

Chapter 7 Subqueries versus Joins. . . . . . . . . . . . . . . . . . . . . . . . . . 227


The IN Subquery. . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
The Subquery as a Join . . . . . . . . . . . . . . . . . . . . . . . . 230
When the Join Cannot Be Turned into a Subquery. . . . . . . . . . 232
More Examples Involving Joins and IN . . . . . . . . . . . . . . . . 234
Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Subqueries with Operators . . . . . . . . . . . . . . . . . . . . . . 240
Exercises for Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . 242

Chapter 8 GROUP BY and HAVING . . . . . . . . . . . . . . . . . . . . . . . . . . 247


Aggregates/Column Functions . . . . . . . . . . . . . . . . . . . . 247
The GROUP BY Clause . . . . . . . . . . . . . . . . . . . . . . . . 248
GROUP BY and ORDER BY . . . . . . . . . . . . . . . . . . . 251
The HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . 253
HAVING and WHERE . . . . . . . . . . . . . . . . . . . . . . 254
GROUP BY and HAVING: Aggregates of Aggregates . . . . . . . . 256
Auditing IN Subqueries . . . . . . . . . . . . . . . . . . . . . . . . 258
Nulls Revisited. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Exercises for Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . 265

Chapter 9 Correlated Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . 269


Non-Correlated Subqueries . . . . . . . . . . . . . . . . . . . . . . 269
Correlated Subqueries. . . . . . . . . . . . . . . . . . . . . . . . . 271
Existence Queries and Correlation . . . . . . . . . . . . . . . . . . 274
EXISTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
From IN to EXISTS. . . . . . . . . . . . . . . . . . . . . . . . 282
NOT EXISTS . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
SQL Universal and Existential Qualifiers — the “for all” Query . . 291
Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Exercises for Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . 301

Chapter 10 CREATE TABLE and SQLLOADER. . . . . . . . . . . . . . . . . . . . . . . 307


The “Simple” CREATE TABLE . . . . . . . . . . . . . . . . . . . 308
The NOT NULL Constraint . . . . . . . . . . . . . . . . . . . . . . 309
PRIMARY KEY Constraints . . . . . . . . . . . . . . . . . . . . . 312

ix
Contents

Creating the PRIMARY KEY Constraint . . . . . . . . . . . . 313


At the Column Level . . . . . . . . . . . . . . . . . . . . . 313
At the Table Level . . . . . . . . . . . . . . . . . . . . . . 313
Using the ALTER TABLE Command . . . . . . . . . . . . 314
Adding a Concatenated Primary Key . . . . . . . . . . . . . . 314
Another Example of Adding a Concatenated Primary Key . . . 315
The UNIQUE Constraint . . . . . . . . . . . . . . . . . . . . . . . 316
The CHECK Constraint . . . . . . . . . . . . . . . . . . . . . . . . 317
Referential Integrity . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Defining the Referential Integrity Constraint . . . . . . . . . . 320
Adding the Foreign Key after Tables Are Created . . . . . . . 321
Using DELETE and the Referential Constraint . . . . . . . . . 322
ON DELETE RESTRICT . . . . . . . . . . . . . . . . . . 322
ON DELETE CASCADE . . . . . . . . . . . . . . . . . . 323
ON DELETE SET NULL . . . . . . . . . . . . . . . . . . 324
More on Constraint Names . . . . . . . . . . . . . . . . . . . . . . 324
SQLLOADER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
SQLLOADER Example 1 . . . . . . . . . . . . . . . . . . . . . 327
Another SQLLOADER Example . . . . . . . . . . . . . . . . . 330
Exercises for Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . 331

Chapter 11 Multiple Commands, START Files, and Reports in SQLPLUS . . . . . . . . 335


Creating a File (a START Table) and Starting It . . . . . . . . . . . 336
A START File (Script) with Editing Features . . . . . . . . . . . . 337
Using the DECODE, GREATEST, and LEAST Functions . . . . . 342
DECODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
GREATEST and LEAST . . . . . . . . . . . . . . . . . . . . . 345
Adding Reporting Features to a START File. . . . . . . . . . . . . 347
A New and Improved Script . . . . . . . . . . . . . . . . . . . . . . 349
Using START Files with ACCEPT and PROMPT . . . . . . . . . . 354
Using START Files with Positional Input . . . . . . . . . . . . . . 355
Exercises for Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . 357

Chapter 12 Beginning PL/SQL: Anonymous Blocks, Procedures,


Functions, and Packages . . . . . . . . . . . . . . . . . . . . . . . 361
Anonymous Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Elementary Procedures with Sequence Structures . . . . . . . . . 364
A Simple Example of a Procedure . . . . . . . . . . . . . . . . 365
Reusing a Procedure . . . . . . . . . . . . . . . . . . . . . . . 367
Deleting a Procedure . . . . . . . . . . . . . . . . . . . . . . . 367
Adding a Parameter List to a Procedure . . . . . . . . . . . . . 368
Performing More than One Action in a Procedure . . . . . . . 369

x
Contents

Procedures with Selection and Iteration Control Structures . . 371


Example of a Procedure with Selection . . . . . . . . . . . 371
Example of a Procedure with Iteration . . . . . . . . . . . 372
Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Example of a Function . . . . . . . . . . . . . . . . . . . . . . 374
Deleting a Function . . . . . . . . . . . . . . . . . . . . . . . . 375
Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Creating a Package . . . . . . . . . . . . . . . . . . . . . . . . 376
Another Approach to Creating This Package . . . . . . . . . . 379
Deleting a Package . . . . . . . . . . . . . . . . . . . . . . . . 380
Defining a PL/SQL INDEX BY Table . . . . . . . . . . . . . . . . . 380
Using a PL/SQL Table . . . . . . . . . . . . . . . . . . . . . . 382
Exercises for Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . 384

Chapter 13 Introduction to Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . 387


What Is a Trigger? . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
A Simple Trigger Example . . . . . . . . . . . . . . . . . . . . . . 389
How the Trigger Worked . . . . . . . . . . . . . . . . . . . . . 391
Row-Level Triggers versus Statement-Level Triggers . . . . . . . 392
Enabling and Disabling Triggers . . . . . . . . . . . . . . . . . . . 392
Enabling All Triggers for a Table . . . . . . . . . . . . . . . . 393
Deleting Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Values in the Trigger . . . . . . . . . . . . . . . . . . . . . . . . . 393
Using WHEN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
Performance Issues Using WHEN . . . . . . . . . . . . . . . . 395
A Trigger Where One Table Affects Another Trigger . . . . . . . . 395
Mutating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
Exercises for Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . 400

Chapter 14 SQL and XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405


Overview of XML . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Oracle and XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
XMLFOREST . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Using XMLELEMENT . . . . . . . . . . . . . . . . . . . . . . 409
Using XMLATTRIBUTES . . . . . . . . . . . . . . . . . . . . 412
Creating a Table Using the XMLType Data Type . . . . . . . . . . 414
Inserting Values into Tables with an XMLType Data Type . . 415
Extracting Information Using XPATH . . . . . . . . . . . . . . 417
Using EXTRACTVALUE . . . . . . . . . . . . . . . . . . 417
Using EXISTSNODE . . . . . . . . . . . . . . . . . . . . 417
Exercises for Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . 418

xi
Contents

Appendix A Some UNIX Commands . . . . . . . . . . . . . . . . . . . . . . . . . . 421


Commonly Used UNIX Commands . . . . . . . . . . . . . . . . . . 421
Summary Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
Other Miscellaneous Commands . . . . . . . . . . . . . . . . . . . 424
Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Using vi as Your Editor . . . . . . . . . . . . . . . . . . . . . . 425
Other vi Commands . . . . . . . . . . . . . . . . . . . . . 426
Using joe as Your Editor . . . . . . . . . . . . . . . . . . . . . 427

Appendix B The Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429


Beginning to Explore the Data Dictionary . . . . . . . . . . . . . . 430
Choosing a View from the Dictionary. . . . . . . . . . . . . . . . . 434
Choosing the View You Want to See . . . . . . . . . . . . . . . 434
Describing the View You Want to See . . . . . . . . . . . . . . 435
Finding the “Right” Columns . . . . . . . . . . . . . . . . . . 436
Finding out How Many Rows Are in the View . . . . . . . . . 436
Views of TABLES. . . . . . . . . . . . . . . . . . . . . . . . . 439
Other Objects — Tablespaces and Constraints . . . . . . . . . . . 440
Views of Tablespaces . . . . . . . . . . . . . . . . . . . . . . . 441
Views of Constraints . . . . . . . . . . . . . . . . . . . . . . . 443
Exercises for Appendix B . . . . . . . . . . . . . . . . . . . . . . . 445

Appendix C The Student Database and Other Tables Used in This Book . . . . . . . 447
The Student-Course Database . . . . . . . . . . . . . . . . . . . . 447
Entity Relationship Diagram of the Student-Course Database . . . 449
Other Tables Used in This Book . . . . . . . . . . . . . . . . . . . 450

Appendix D Glossary of Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453

Appendix E Important Commands and Functions . . . . . . . . . . . . . . . . . . . 467

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479

xii
Preface

Why This Book?


In recent years we have seen a dramatic increase in the
popularity of Oracle. Oracle is now the most widely used
database on the market. Due to this dramatic increase in
popularity, more and more schools and training organiza-
tions are using Oracle to teach database principles and
concepts. And given the current technological climate, the
computer industry needs application developers who can
write Oracle SQL code efficiently.
This book employs a step-by-step systematic
approach to learning Oracle SQL, database principles,
and concepts. It starts by presenting simple Oracle SQL
commands and functions, and slowly moves into more
complex query development and PL/SQL; it also intro-
duces SQL/XML. Each chapter includes numerous
examples, and if readers wish they can run these exam-
ples themselves using Oracle. Each chapter ends with a
series of exercises that reinforce and build on chapter
material. In doing these exercises, it is our hope and
expectation that readers will learn SQL and the underly-
ing principles of relational databases. As such, we do not
include the “answers” to the exercises.

xiii
Preface

Oracle and SQL


SQL is an abbreviation for SEQUEL (Structured English
Query Language), and was originally an IBM product.
Since the 1970s, when SEQUEL was introduced, it has
become the de facto standard “language” for accessing
relational databases. SQL is not really a language as
much as it is a database query tool. In this book, we will
concentrate on using the Oracle database engine to learn
and use SQL.
SQL allows you to define relational databases and
create tables; in this sense, SQL is a Data Definition Lan-
guage (DDL). Oracle also provides a utility called
SQL*Loader to load the created database with data.
After the database is created and populated, SQL pro-
vides a way to modify the database definition by using
DDL. It also allows you to query the relational database
in a most flexible way as well as change the data (i.e., per-
form data manipulation). Therefore, SQL is a Data
Manipulation Language (DML) as well as a DDL.
This book covers SQL as it is invoked via SQL*Plus,
which is a command-line system to launch interactive
commands. SQL*Plus is a powerful Oracle product that
takes your instructions for Oracle, checks them for cor-
rectness, submits them to the Oracle database engine,
and then modifies or reformats the response Oracle gives.
In short, SQL*Plus makes interacting with Oracle
smooth and easy.

Audience and Coverage


This book can be used in conjunction with standard data-
base texts used in universities and colleges; it can also be
used as a “stand-alone” text to learn SQL and Oracle. For
this latter scenario, we included a Prologue chapter. The
Prologue provides basic database background material
needed to begin using SQL and relational databases.

xiv
Preface

This book can be divided into two parts. Chapters 1


through 10 cover topics meant for introductory-level
database learning or a beginning SQL/Oracle class.
Chapters 11 through 14 contain a preview of advanced
topics that are usually covered in advanced database
classes. These chapters assume that the reader has some
programming background or experience.
The Prologue introduces some of the database terms
that will be used throughout the book and shows how and
why the relational database model fits into the database
world of today. Chapter 1 begins in a step-by-step man-
ner, beginning with “signing on.” Then it covers basic
Oracle/SQL topics such as SELECT, INSERT, and DELETE
(DML commands). Simple editing concepts are also intro-
duced in this chapter. Chapter 2 covers additional
beginning SQL commands and builds on the material in
Chapter 1. Chapter 3 introduces joins, which is a way to
put relational tables together. Chapters 4 and 5 get into
basic Oracle functions and query development as well as
the use of views and other derived structures. Chapter 6
covers simple set operations; Chapters 7, 8, and 9 cover
more advanced queries including using subqueries,
aggregate functions, and correlated subqueries. Chapters
10 through 13 introduce still more advanced SQL con-
cepts such as the load utility, start files, reports, some
introductory PL/SQL, and triggers. Chapter 14 intro-
duces SQL/XML. As we mentioned earlier, we have
included exercises at the end of every chapter to bolster
the material in the chapter and incorporate a review of
the chapter’s topics.
Appendix A presents some common UNIX com-
mands. Appendix B covers data dictionary concepts.
Appendix C illustrates the Student-Course tables and
other tables that have been used throughout the book. In
addition, we have provided a glossary of terms and a list
of important commands and functions for your reference.
Overall, we feel that this book is ideal for a beginning
Oracle user to get an overview of what SQL and Oracle

xv
Preface

entails. The book gives a very good “feel” for what Oracle
is and the many ways Oracle can be used.

Supplements
The exercises at the end of each chapter are drawn from
databases that we created and that can be downloaded
from http://www.cs.uwf.edu/~sbagui/. The download
instructions are also available at this web site. The files
can also be downloaded from http://www.wordware.com/
files/sql-oracle.

xvi
Acknowledgments

Our special thanks are due to our editors, Tim McEvoy,


Martha McCuller, and Beth Kohler.
We would also like to thank Dean Jane Halonen,
Interim President Judy Bense, and Interim Provost
Chula King for their inspiration, encouragement, support,
and true leadership. We would also like to express our
gratitude to Dr. Richard Podemski on the same endeavor.
Our sincere thanks also go to Dr. Leo TerHaar, chair,
Computer Science Department, for his advice, guidance,
and support, and encouraging us to complete this book,
and Dr. Norman Wilde and Dr. Ed Rodgers for their con-
tinuing support and encouragement throughout past
years. And, last but not least, we would like to thank our
fellow faculty members and Diana Walker for their con-
tinuous support.

— Richard Earp and Sikha Bagui

xvii
This page intentionally left blank.
Prologue |

Prologue

The Software
Engineering Process
and Relational
Databases

This chapter is provided for those readers who wish to


study SQL and database topics but feel that they lack suf-
ficient relational database background. It is not intended
to replace a course about databases; a theoretical data-
base course is often taught concurrently with a study of
this material.
We begin with some preliminary definitions and a
short history of databases; this material is followed by a
description of how and why the relational database model
fits into the database world of today. We then delve into a
more detailed description of relational databases and nor-
mal forms. Finally, we provide a brief explanation of
software engineering. Some knowledge of how software

1
The Software Engineering Process and Relational Databases

(SQL “programs,” if you will) might be developed is use-


ful in understanding why we suggest using some of the
formats and conventions in this book.

What Is a Database?
Data — facts about something — must be stored in some
fashion in order for it to be useful (that is, in order for it
to be found). A database is a collection of associated or
related data. For example, the collection of all the infor-
mation in a doctor’s office could be referred to as a
“medical office database”; all data in this database would
refer to information that is pertinent to the operation of a
medical office.
Before the age of computers, databases were kept on
paper (medical databases were kept in doctor’s offices,
personnel databases were kept in employment offices,
and so on). Over the years, databases have migrated from
paper to electronic media.
Regardless of the format (paper or electronic), infor-
mation stored in databases is organized into files. Files
are collections of data about one subject. A medical office
database might well have files other than patient data.
One might imagine that in a doctor’s office there would be
a pharmaceutical file, employee files, and so on. Individ-
ual data is stored in records within files. For example, Mr.
Smith’s medical records would be located in his doctor’s
patient files. Individual items in Mr. Smith’s records
would include his name, his address, and so on. Informa-
tion such as name and address is referred to as a field or
attribute. Thus, databases contain files, files contain
records, and records contain fields (attributes).

2
Prologue |

Database Models
A conceptual way of thinking about data in a database is
called a logical model. With a logical model, we conceptu-
alize how data might be organized. The way that data is
actually laid out on the disk — that is, where each bit is
located — is called a physical model.
Over the past 40 years or so, three basic camps of log-
ical database models evolved:
„ The hierarchical model
„ The network model
„ The relational model
All three of these models represent ways of logically per-
ceiving the arrangement of data in databases. As you will
see, the hierarchical and network models can infer some
knowledge of how the physical model operates, whereas
the relational model virtually ignores the physical model.
We will now give a little insight into each of these three
historically significant models to see how the relational
model has evolved into the dominant logical model.

The Hierarchical Model


The idea in a hierarchical model is that all data is logi-
cally arranged in a hierarchical fashion (also known as a
parent-child relationship). As an example, suppose that
your company had an employee database. Further, sup-
pose that this database contained files about employees
and files about the dependents of employees. Some
employees have dependents; some do not. For those
employees with dependents, there must be a reference in
an employee’s record to the location of corresponding
dependent records in the dependent file.

3
The Software Engineering Process and Relational Databases

If an employee had dependents, you could think of


that employee as being the “parent” of the dependent.
Thus, every dependent would have one employee-parent
and every employee could have one or more depend-
ent-children. (Please note that the parent and child
inference is not necessarily meant to be a personal rela-
tionship: child and parent are not meant to be taken
literally.) The connection of the employee to a dependent
and vice versa is called a relationship. Figure 1 illustrates
the hierarchical model.

Figure 1: Hierarchical model

In logical models, all relationships between records have


what are called structural constraints. Structural con-
straints indicate how many of one type of record is
related to another (also called cardinality) and whether
one type of record must have such a relationship (also
called participation or optionality).
For example, suppose that an employee may have one
or more dependents, and all dependents in a database
must be related to one and only one employee. We would
term the cardinality of this relationship of employee to
dependent as one to many, or 1:M. Further, since we say
that an employee may (or may not) have dependents, the
participation constraint of the relationship from the
employee side is partial or optional. Because a dependent
must be associated with one employee, the participation
from the dependent side is full or mandatory. Note that
the words “one or more” and “one and only one” indicate

4
Prologue |

cardinality. The words “may” and “must” indicate


optionality or participation.
In a hierarchical model, there are either one-to-one
(1:1) or one-to-many (1:M) relationships (as shown in Fig-
ures 2 and 3, respectively), but never many-to-one (M:1)
relationships. The most common relationship in a hierar-
chical model is 1:M. In our example, a 1:M relationship
means that one employee may have many dependents
(“many” meaning one or more). Further, the 1:M
employee-to-dependent relationship implies that each
dependent has one and only one employee-parent.

Figure 2: One-to-one (1:1) relationship

Less common, but allowable in hierarchical models, is the


1:1 relationship shown in Figure 2. In our employee
example, a 1:1 relationship would imply that one
employee might have one designated dependent and a
dependent would be related to only one employee. This
relationship might infer a “next-of-kin” designation, for
example.

Figure 3: One-to-many (1:M) relationship

5
The Software Engineering Process and Relational Databases

Other Cardinalities
A many-to-one (M:1) relationship between employee and
dependent would imply that a dependent might have mul-
tiple parents (multiple employees who “claimed” a
particular dependent). But, because the relationship is
M:1, it would infer that an employee could have at most
one dependent. Again, the M:1 relationship is not allowed
in hierarchical logical models.
The very common many-to-many (M:N) relationship,
shown in Figure 4, is not allowed in hierarchical database
models either. (Note that while M usually stands for
many, M:N is used more often than M:M to stand for
many-to-many because it’s important not to infer that the
values for M and N are equal; in fact, they usually are
not.) We will discuss examples of these hierarchically
unallowable relationships (M:1 and M:N) when we look at
the network model.

Figure 4: Many-to-many (M:N) relationship

Before the advent of computers, hierarchical databases


were implemented by choosing some way of physically
connecting the parent and child records. Suppose that an
employee, Mr. Smith, had three children: Sally, Ann, and
Tom. If we think back to paper records, we might visual-
ize that in the dependent file there could be a Sally Smith
record, an Ann Smith record, and a Tom Smith record.
Where would these independent records be in the
dependent file? Suppose we put the dependent records in
a filing cabinet and put the notation in Mr. Smith’s record
that his dependents were Sally (file drawer 1, record 2),

6
Prologue |

Ann (file drawer 3, record 12), and Tom (file drawer 2,


record 13). Here, we are using a system to physically
“point to” the dependent records from Mr. Smith’s
employee record. This scheme is called a multiple-child
pointer scheme.
On a disk, just as with the paper model, one record
“points to” physical locations for the dependent records.
There are actually multiple ways to implement the hierar-
chical model. In addition to using a disk address instead
of “file drawer x, record y,” a different way to implement
the employee-dependent relationship would be to have an
employee record point to a disk location for the first
dependent record. That dependent record would in turn
point to the disk location of the next dependent, and so on.
In this example, Mr. Smith would point to Sally, Sally
would point to Ann, and Ann would point to Tom. This is
called a linked list of child-records or, in older database
books, a chain of records because they can be thought of
as record-links that are chained together.
Regardless of how cleverly the physical record links
are established, the hierarchical model has two major
drawbacks:
„ The choice of the way in which the files are physically
linked impacts the way underlying database software
is developed and hence impacts database performance
both positively and negatively.
„ Not all situations fall into parent-child (hierarchical)
formats. What if one wanted to have a dependent (a
child record) point to multiple employees (multiple
parent records) and vice versa (that is, an M:N rela-
tionship)? This would not fit the hierarchical database
model well.

To see a way around these drawbacks, let’s take a look at


the network model.

7
The Software Engineering Process and Relational Databases

The Network Model


The network model handles the multiple parent concern
of the hierarchical model. In the network model, you are
not restricted to having one parent per child — a
many-to-one (M:1) and a many-to-many (M:N) relation-
ship is acceptable. As an example, if your
network-modeled database consisted of your
employee-dependent situation as in the hierarchical
model, but it was necessary to allow multiple parents for
each dependent person, then a dependent could have two
or more “parents.” Therefore, a dependent could relate to
one or more employees. In this case, we would say that
the relationship was many-to-many (M:N). An employee
may have many dependents (zero or more) and a depend-
ent must have a relationship to many (one or more)
employees.
Implementing the employee-dependent M:N database
in hierarchical databases involves creating redundant
files. However, in network databases, you can simply
have two or more connections or links from the depend-
ent-child to however many parents there are. If you
considered the multiple-child pointer scheme or the
chaining system we described earlier in a network set-
ting, you might imagine that the pointing schemes in
networked databases are very complex. Indeed they are.
To illustrate the network model, suppose we consider
a database of employees and projects to which they are
assigned. Figure 5 is an example of a network model in
which employees may be working on many projects, and
the projects may have many employees working on them.
This is a many-to-many (M:N) relationship between
employee and project.

8
Prologue |

Figure 5: The network model

In both the hierarchical and network models, database


software must be designed using some pointing scheme;
we need some method of connecting or linking records.
This choice of record connection then presents a hard-
ware-implemented connection, which impacts
performance both positively and negatively. Further, as
the database becomes more complicated, the paths of con-
nections and the maintenance problems with all the links
become exponentially more difficult for the software to
manage. As you can imagine, networked linking is more
complicated than hierarchical linking. As records are
updated, inserted, or deleted, all links must be main-
tained. The more complicated the system, the more
danger there is for dead links (i.e., corrupted links or lost
addresses).

Contemporary Databases: The Relational


Model
Dr. Edgar F. Codd introduced the relational model
around 1970 (Codd, 1970b). The relational model is
based on the idea that if you ignore the way data files are
connected and arrange your data into simple two-dimen-
sional, unordered tables, then you can develop an algebra
for queries and focus on the data as data, not as a physical
realization of a logical model.

9
The Software Engineering Process and Relational Databases

Before we delve into the details of the relational


model, however, it is important that you understand some
changes in terminology as databases evolved from file
systems to relational databases. As you may know, cur-
rent terminology refers to an entity as something we
record information about. For example, we record infor-
mation (data, facts) about employees; hence, an employee
is an entity. Whereas we used to refer to the employee
file, we now refer to the set of employee entities as an
employee entity set. Likewise, employee records (now
called entities) contain employee information fields (now
called attributes) of the employee entity. The reason for
using the terms entity set, entity, and attribute instead of
file, record, and field, respectively, is to disconnect the
idea of a physical file, record, and field from the logical
notion of these things.
The relational model is truly logical in that one is no
longer concerned with how data is physically stored.
Rather, files (called entity sets in the relational model)
are simply unordered, two-dimensional tables of simple
data values (or sets of rows). Necessarily, there are rules
that govern the way these tables “store” data. The first
rule is that the data itself must be atomic — that is, not
broken down into component parts. The tables of data are
called relations and because the data is stored in tables,
each table has columns (which represent the attributes)
and rows (which represent the instances of each entity). A
collection of tables is referred to as a relational database.
Table 1 shows an example of an employee relation (a table
with data in it).
Table 1: Example of an Employee relation (table)
Employee
name address project#
Smith 123 4th St. 101
Smith 123 4th St. 102
Jones 5 Oak Dr. 101

10
Prologue |

Employee is a table — a relation. The column names


name, address, and project# are attributes. A row, such
as
<Smith, 123 4th St, 102>

represents an employee entity occurrence (data about a


person named Smith, Smith’s address, and the project#
that Smith is working on). In relational databases, the
ordering of the rows in the table is not defined. The rows
are considered a set of rows and sets do not have an
order. Rows are either in the set or they or not, but where
they are in the set is irrelevant. Thus, Table 2 is equiva-
lent to Table 1.
Table 2: A reordered Employee table
Employee
name address project#
Smith 123 4th St. 102
Jones 5 Oak Dr. 101
Smith 123 4th St. 101

The First, Second, and Third Normal Forms


Obviously, databases contain more data than is illustrated
in the Employee table shown above. To arrive at a work-
able way of deciding which pieces of data go into which
tables and to arrange the tables so that Codd’s relational
algebra would work, Codd proposed something he
referred to as normal forms (Codd, 1970a, Codd, 1970c,
Codd, 1971). He originally defined three normal forms:
the first, second, and third normal forms. We’ll look at
each of these next.

11
The Software Engineering Process and Relational Databases

The First Normal Form


The first normal form (1NF) requires that data in tables
be atomic and be arranged in a two-dimensional layout.
Atomicity implies that there be no column that contains
repeating groups. Repeating groups refers to columns
that may contain multiple occurrences of data. A repeat-
ing group is an example of non-atomic data and violates
the definition of a relational table. A problem with putting
data in tables with repeating groups is that the table can-
not be easily indexed or arranged in such a way that data
in the repeating group can easily be found. Put another
way, data in repeating groups cannot be found without
searching each row individually.
An example of a table not in 1NF is where there is an
employee entity with attributes (fields) name, address,
and dependent name, as shown below:

Employee (name, address, {dependent name}),

where {dependent name} implies that the attribute is


repeated, with rows containing data as illustrated below:

Smith, 123 4th St., {John, Mary, Paul, Sally}


Jones, 5 Oak Dr., {Mary, Frank, Bob}
Adams, 33 Dog Ave., {Alice, Alicia, Mary}

What do you do if you want to store data about employees


and their dependents? Before tackling the problem of
dealing with non-1NF data, it is helpful to understand the
concept of a key. A key in a table is an attribute or group
of attributes that identifies a row — a unique handle
whereby one can find information in a table. In Table 2,
the key could be the employee’s last name. For example,
if you wanted information about Jones, you would access
Jones’s row. Clearly, if there were two people named
Jones, you would have to come up with a better key, such
as adding a unique employee number to the table.

12
Prologue |

To resolve the non-1NF problem (and other NF


problems that you will encounter), databases must be
normalized. The normalization process involves splitting
tables into two or more tables (also called decomposition).
Data can be reunited from decomposed tables with a
relational operation called a join. We will illustrate the
normalization process by first solving the non-1NF prob-
lem. To eliminate the non-1NF problem, we do the
following:

Non-1NF to First Normal Form (1NF)


The repeating group is moved to a new table with the key
of the table from which it came.
For now, we will assume that the last name of the
employee is the key in this version of Employee.

Non-1NF:

Smith, 123 4th St., {John, Mary, Paul, Sally}


Jones, 5 Oak Dr., {Mary, Frank, Bob}
Adams, 33 Dog Ave., {Alice, Alicia, Mary}

is decomposed into 1NF tables with no repeating groups,


as shown in Tables 3a and 3b.
Table 3a: Employee table in 1NF
Employee1
name address
Smith 123 4th St
Jones 5 Oak Dr
Adams 33 Dog Ave

13
The Software Engineering Process and Relational Databases

Table 3b: Dependent table in 1NF


Dependent
dependentName employeeName
John Smith
Mary Smith
Paul Smith
Sally Smith
Mary Jones
Frank Jones
Alice Adams
Alicia Adams
Mary Adams

In Table 3a, name is the key of Employee1 — it uniquely


identifies the rows. We would call name, as used here, a
primary key. A primary key is the key that we choose to
uniquely identify a row. In Table 3b, the primary key is a
combination (concatenation) of dependentName and
employeeName. Neither the dependentName nor the
employeeName is unique in Table 3b, and hence both
attributes are required to uniquely identify a row in the
table. The employeeName in Table 3b is called a foreign
key because it references a primary key: name in Table
3a. The original data could be reconstructed by combining
all the rows in Table 3a with the corresponding rows in
Table 3b where the employee names were equal. The
combination of tables based on the equality of some
attribute (column) is called an equi-join in a relational
database.

The Second Normal Form


The second normal form (2NF) requires that data in
tables depend on the whole key of the table. If a data item
depends on only part of a compound key, it is said to be a
partial dependency. Partial dependencies are not allowed

14
Prologue |

in the second normal form. Consider for example a table


called Employee2 with attributes name, job, salary, and
address, as shown below:

Employee2(name, job, salary, address)

And suppose that it takes a combination of the name and


job fields (which can also be shown as name + job) to
identify a salary field, but the address field depends only
on the name field. Name + job is a concatenated key and
is the primary key of this table. Dependence here means
identification. Since address depends on name, if you
know the name, this will identify the person’s address in
this data. We would say that the dependence of address
on name is a partial dependency because name is only
part of the primary key of the table. Table 4 shows some
sample data for the Employee2 table.
Table 4: A non-2NF table
Employee2
name job salary address
Smith Welder 14.75 123 4th St.
Smith Programmer 24.50 123 4th St.
Smith Waiter 7.50 123 4th St.
Jones Programmer 26.50 5 Oak Dr.
Jones Bricklayer 34.50 5 Oak Dr.
Adams Analyst 28.50 33 Dog Ave.

Can you see the problem developing here? The address is


repeated for each occurrence of a name. This repetition is
called redundancy and leads to anomalies. An anomaly
means that there is a restriction on doing something due
to the arrangement of the data. There are insertion anom-
alies, deletion anomalies, and update anomalies. The key
of this table is name + job. This is clear because neither
attribute will, by itself, identify information in a particular
row — it really takes both the name and job fields to iden-
tify a salary. (Try to answer the question “What is

15
The Software Engineering Process and Relational Databases

Smith’s salary?” without saying what the job is.) How-


ever, address depends only on the name, not the job. This
is an example of a partial dependency. Address depends
on only part of the key of this table.
A further rule of relational databases is that no part
of a primary key of a relation may be null (have a unde-
fined value); this is known as the entity-integrity
constraint. What’s wrong with null values in keys? If a
null were allowed in a key, the key would have a
non-unique value and hence not be a key at all.
An example of an insertion anomaly would be where
one would want to insert a person into Table 4a, but the
person to be inserted has not been assigned a job. This
insertion cannot be done because a value would have to be
known for the job attribute.
An example of an update anomaly would be where one
of the employees changed his or her address. Suppose the
person named Smith had a change of address. You would
have to change three rows to accommodate this one
address change.
An example of a delete anomaly would be where the
person named Adams quits, so Adams’ row is deleted.
However, the information that the analyst pay is $28.50 is
also lost. Therefore, a delete anomaly deletes more than is
desired. How do we decompose a non-2NF table to fix
these problems?

Non-2NF to 2NF
To make a non-2NF table a 2NF table, the partial
dependency has to be removed to a new table. The attrib-
utes (columns or fields) that are fully dependent of the
primary key (primary key here being name + job) are put
together with the primary key (as shown in Table 5a). The
salary is dependent on both parts of the primary key
(name and job), so salary is placed with the name and job
fields in Table 5a.

16
Prologue |

Table 5a: EmployeeSalary table


EmployeeSalary
name job salary
Smith Welder 14.75
Smith Programmer 24.50
Smith Waiter 7.50
Jones Programmer 26.50
Jones Bricklayer 34.50
Adams Analyst 28.50

Then, the fields that are not fully dependent on the pri-
mary key are placed with the part of the primary key that
they are dependent on. In this case, the address field
(which is only dependent on part of the primary key) is
placed with name (the part of the primary key that
address is dependent on). This is shown in Table 5b.
Table 5b: EmployeeInformation table
EmployeeInformation
name address
Smith 123 4th St.
Jones 5 Oak Dr.
Adams 33 Dog Ave.

Hence the non-2NF table, Table 4, is decomposed to the


2NF tables as shown in Tables 5a and 5b.
The key of the EmployeeSalary table (Table 5a) is as
before — the name and the job taken together. The key of
the EmployeeInformation table (Table 5b) is just the
name. Note that the “other” non-key attributes in both
tables now depend on the key (and only on the key). Also,
note the removal of redundancy and the elimination of
possible anomalies. For practice, try adding, deleting, and
updating rows and note that the anomalies are gone.

17
The Software Engineering Process and Relational Databases

The Third Normal Form


The third normal form (3NF) requires that data in tables
depend on the primary key of the table. 2NF problems
only appear when there is a concatenated key to begin
with; 3NF problems do not require a concatenated key.
3NF problems occur when some non-key data item is
more properly identified by something other than the key
of the table. A classic example of non-3NF relation could
be shown by the Employee3 table below. Employee3 has
the attributes name, address, project#, and
project-location.

Employee3(name, address, project#, project-location)

In Employee3 we will assume that the name field is the


primary key. Suppose that project-location in Employee3
means the location from which a project is controlled, and
is defined by the project#. Some sample data will illus-
trate the problem, as shown in Table 6.
Table 6: A non-3NF table
Employee3
name address project# project location
Smith 123 4th St. 101 Memphis
Smith 123 4th St. 102 Mobile
Jones 5 Oak Dr. 101 Memphis

Note the redundancy in Table 6. Project 101 is controlled


in Memphis, but every time a person is recorded as work-
ing on project 101, the fact that they work on a project
that is controlled in Memphis is recorded again. The same
anomalies — insert, update, and delete — are also pres-
ent in this table. You cannot add a project# or project
location unless you have a name. (Remember that name
cannot be null.) If you deleted Smith working on project
102 in Table 6, the “102, Mobile” information is also

18
Prologue |

deleted. Suppose project 101’s control location is moved to


Tuscaloosa. How many changes would this require?
The name, project#, project-location situation is
called a transitive dependency. This transitive depend-
ency is resolved by decomposing into 3NF as follows.

Non-3NF to 3NF
To make a non-3NF table into a 3NF table, the transitive
dependency has to be removed to a new table. Thus,
Table 6 is decomposed into two tables: Tables 7a and 7b.
Table 7a: Employee table in 3NF
Employee3a
name address project#
Smith 123 4th St. 101
Smith 123 4th St. 102
Jones 5 Oak Dr. 101

Table 7b: Project table in 3NF


Project
project# project location
101 Memphis
102 Mobile
101 Memphis

Again, observe the removal of the transitive dependency


and the anomaly problem.
Before concluding our discussion of normal forms,
note that there are other cases of non-normality that are
beyond the scope of this brief overview. These other cases
are not common, and a “good” relational database may be
thought of as one that is in the 3NF.
In summary, there are rules that define a relational
database. All data is laid out in two-dimensional tables.
The tables have no sense of ordering of rows. In fact, the
tables are often called “sets of rows.” All data is atomic. A

19
The Software Engineering Process and Relational Databases

primary key is a chosen unique row-identifier; if one


wants information from a row in a table, one gets it by the
primary key value. The 3NF means that the data in a
relation depends only on the primary key of the relation.
Data in 3NF is assumed to be in the 1NF and 2NF. Data
that is decomposed into the 3NF will avoid most redun-
dancy and anomaly problems.

What Is the Software Engineering Process?


As a further bit of orientation to the material contained in
this book, we wish to present some insight into the idea of
how software is developed. The term “software engineer-
ing” refers to a process of specifying, designing, writing,
delivering, maintaining, and finally retiring software.
Many excellent references on the topic of software engi-
neering (see Schach, 2005) are available to the interested
reader.
A basic idea in software engineering is that to build
software correctly, a series of standardized steps or
phases are required. The steps ensure that a process of
thinking precedes action. That is, thinking through “what
is needed” precedes “what is written.” One common ver-
sion of presenting the thinking before acting scenario is
referred to as a “waterfall model” as described in Classi-
cal and Object-Oriented Software Engineering (Schach,
2005). In the waterfall model the phases of software
development are supposed to flow from one to another in
a directional way without retracing.
Software production is like a life-cycle process — it is
created, used, and eventually retired. The “players” in the
software development life cycle may be placed into two
camps, often referred to as the user and the analyst.
Software is designed by the analyst for the user.

20
Prologue |

There is no general agreement among software


engineers as to the exact number of phases in the water-
fall-type software development model. For that matter,
many software engineering practitioners do not support
the waterfall model at all, and models vary greatly. A very
brief description of a software development process goes
like this:
Step 1 (or Phase 1). Requirements: find out what the user
wants/needs.
Step 2. Specification: write out the user’s wants/needs as
precisely as possible.
Step 3. Software is designed to meet the specification
from step 2.
Step 4. Software is written (developed).
Step 5. Software is turned over to user (implementation).
Step 6. Maintenance is performed on software until it is
retired.

In most software engineering models, some feedback


loops are allowed. For example, when completing step 2,
it is possible to go back to step 1 if the analyst does not
understand and communicate the user’s requirements.
For SQL users, the software process involves retriev-
ing data from a database. A database is a collection of
facts stored on some electronic media. Often the question
in SQL is “What does some user want to know?” This
question is called a query because it is a question directed
at the information contained in the database.
What does software engineering have to do with writ-
ing queries? We can draw a number of implications from
the software engineering process. In the normal business
world, the person who writes SQL queries is often not the
person who wants to know something. Imagine a supervi-
sor telling a SQL programmer to find the names of all the
customers who spent over $1,000 this month. The SQL

21
Random documents with unrelated
content Scribd suggests to you:
Elle avait bien compris quel homme était le comte Paul, et elle se
maintenait, en conséquence, dans son rôle de modestie sans
affectation. Elle jugeait bien la situation. Pour plaire à Paul et à sa
mère, elle n’avait vraiment que ce moyen : les tromper du tout au
tout sur sa personne morale.
V

Le docteur voyait juste : c’était une âme intéressante que celle du


comte Paul. Il n’était point compliqué, mais nettement double, aussi
prompt à douter qu’il était enclin à croire — aussi emporté dans sa
conception quasi-mystique du bien, que passionné au sens matériel
du mot.
Une anecdote de son enfance, que sa mère aimait à conter,
montre combien, tout petit, il avait déjà une conscience en éveil et
forte, en même temps que des gourmandises puissantes :
Un jour — il avait sept ans — sa grand’maman, qui habitait avec
eux le château d’Aiguebelle, n’était pas descendue se mettre à table.
On lui avait monté son déjeuner dans sa chambre. Elle fit
redemander d’une certaine confiture dont elle était friande.
— Tiens, petit Paul, c’est toi qui vas porter à bonne maman, qui
est dans sa chambre, cette assiette de confiture. Ça lui fera plaisir, si
c’est toi. Et dis-lui qu’on t’attend. Reviens tout de suite.
L’enfant se leva et s’en fut, bien attentif à ne pas renverser
l’assiette qu’il tenait à deux mains. Il y avait à table son précepteur,
l’abbé Tardieu, et deux dames du voisinage.
L’enfant parti, on continua de causer. Quelques instants
s’écoulèrent, et l’on s’étonnait de ne pas le voir revenir, lorsque tout
à coup, dans le vide sonore du vaste escalier, on entendit des cris
déchirants et des pleurs.
Tout le monde courut, croyant qu’il était tombé, blessé peut-
être… On le trouva debout à mi-étage, son assiette entre ses deux
mains un peu tremblantes, et versant de grosses larmes en pleine
confiture, tout haletant et suffoqué.
— Qu’as-tu, enfin ? Qu’as-tu, mon mignon ? Qu’est-il arrivé ?
Pourquoi pleures-tu ?
Il fit cette réponse étonnante, coupée de sanglots :
— … C’est que… jamais… je n’arriverai jusqu’en haut… Non,
maman, jamais ! jamais je ne pourrai la porter si loin… sans l’avoir
mangée !
— Ah ! dit l’abbé enchanté, c’est une conscience du bon Dieu !
Cela nous fera un de ces hommes rares qui savent résister aux pires
tentations, et qui seraient capables de mourir du seul désespoir
d’avoir commis une faute !
Paul aimait sa mère plus que tout au monde. Il aimait Albert de
Barjols autant que sa sœur Annette, et il était en outre attaché à cet
ami d’enfance par les mille liens subtils des pensées les plus
profondes, continuellement échangées.
Aucun des deux amis n’avait eu l’occasion de recevoir de l’autre
quelqu’un de ces importants services qui sont un point de départ
nécessaire aux amitiés romanesques. Ils s’étaient connus tout petits.
Ils s’aimaient dans leurs qualités heureuses ; ils se conseillaient l’un
l’autre ; ils s’excusaient ou se blâmaient utilement ; chacun d’eux
était pour l’autre une aide d’âme, un secours moral, un écho attendu,
une réponse appelée. Quand les longues absences du marin les
séparaient, il leur arrivait de passer des mois sans s’écrire, mais
comme ils étaient certains tous deux de se retrouver aussi aimants,
aussi prêts à tous les dons, à tous les dévouements, — la pensée de
leur amitié sans exigence leur suffisait, parce qu’elle les empêchait
de sentir l’esseulement dans le vide, — qui est l’unique vrai malheur
de la vie.
C’est Albert le positiviste qui avait trouvé cette formule,
approuvée par Paul : Ce qu’il y a d’estimable dans l’amour, c’est la
quantité d’amitié qu’on y retrouve à l’analyse.
Albert, d’esprit aussi littéraire, mais plus scientifique que Paul,
lisait beaucoup, pendant les longs loisirs que lui laissait son service
à bord ; et il se piquait d’éclairer, avec des idées précises, le
sentiment plus intuitif de Paul sur toutes choses.
Aucun d’eux ne croyait. Tous deux le cachaient à leur mère.
Albert professait un athéisme raisonné que Paul trouvait teinté
d’absurde. Il lui disait : « Moi, je ne crois plus, mais j’espère encore,
vaguement. Que savons-nous ? L’homme est si bête !… Je compte
beaucoup sur la bêtise de l’homme ! »
Tous deux, en renonçant à la foi de leur enfance, avaient gardé,
profondément gravée dans leur cœur, la morale que leur avait
enseignée la religion… « Il n’y a pas mieux, pour qui veut être un
honnête homme et un homme bon », disait Paul.
Le sens moral, disait-il, c’est l’instinct de conservation de
l’homme social ; il est inné aussi bien que celui de l’homme
physique. Or l’homme est, de par la nature, un être destiné à vivre
en société, comme l’abeille. Il y a une base commune à toutes les
morales, et les commandements de Dieu les résument toutes assez
bien. Ainsi disait Paul. — C’est une erreur accréditée d’assurer que
les penseurs de profession, ceux qui écrivent pour le public, sont les
seuls à penser, ou même les seuls à écrire. — Paul prétendait que
l’homme étant bien décidément privé de tout secours providentiel,
doit, s’il entend ses vrais intérêts, conclure à la nécessité d’être
meilleur pour soi-même c’est-à-dire pour son semblable. Dieu
n’étant plus là pour nous aimer, nous devons nous aimer davantage.
Plus l’homme se croit en droit de nier la Providence, plus il doit
s’efforcer de devenir lui-même une providence pour les autres
hommes, ses frères et ses fils. Si l’athée ne se résigne pas à
s’imposer les sacrifices qui font les héros, — il retombe à n’être que
l’animal le plus dangereux de la terre ; — c’est le chercheur de proie,
sans autre loi que son caprice et sa force, le monstre enragé, qu’il
faut étouffer bien vite, au nom de ses propres principes, — sous
peine de lui laisser détruire l’antique héritage de l’humanité qui
pense, qui sent et qui aime !
Nous errons sur un bateau perdu, au milieu des océans mornes,
sous le ciel noir de la science. Soyons-nous à nous-mêmes des
dieux plus bienfaisants que ceux des religions. Ceux-là, les
philosophes les ont détruits, sans doute par amour de la justice,
mais peut-être inconsidérément, — car, disait souvent Paul à Albert,
si Dieu était la forme la plus concrète, la plus vivante, la plus facile à
populariser, à faire aimer, — de l’idéal et de la morale nécessaires.
Les deux amis croyaient qu’on peut baser une morale divinement
humaine sur la seule charité. Seulement Paul était persuadé que
cette morale, toute abstraite, sans incarnation ni sanction, ne serait
jamais qu’une conception d’esprits cultivés, intransmissible à l’âme
élémentaire des masses. Bref, il regrettait Dieu, — tandis qu’Albert,
plein de quiétude, trouvait que de bonnes lois suffisent à régir un
peuple civilisé, et que les éclairs du Sinaï n’ajoutent rien à l’autorité
de la justice.
Si surprenant que cela puisse paraître à bien des gens, ces
sortes d’idées n’étaient pas pour eux de simples motifs à
bavardages. Leur vie, à toute heure, était influencée par leurs
convictions, et il ne se passait guère de jour où ils ne fissent quelque
effort pour être meilleurs, plus équitables. Il y a, comme cela, dans
des coins de France et du monde, sur des bateaux errants en mer,
dans des châteaux et dans des masures, quelques êtres attardés
qui réalisent par leurs actes, de personnelles, d’idéales conceptions
de bonté, de justice…
Est-ce à dire que les deux amis fussent des saints ? Loin de là,
puisqu’on semble exiger de ceux à qui on décerne les honneurs de
la sainteté, de surhumaines vertus, et que, pour les catholiques,
l’idée de pureté est presque liée à celle d’ascétisme.
Non, ils vivaient de la vie commune. Ils n’étaient pas sans
passions, ni certes, sans péchés. Ils étaient faibles, étant des
hommes. Ils étaient égoïstes souvent, jaloux à l’occasion ; ils
éprouvaient parfois des mouvements de rage ou d’envie, de sourdes
révoltes de la bête brute, car c’est dans un animal que s’élaborent
tous les nobles désirs de l’esprit, — dont la moindre conquête exige
un rude effort.
Mais tout le chaos des mauvais sentiments fatals était dominé en
eux par la possibilité toujours présente de se dépasser eux-mêmes,
dans un moment donné, — d’être meilleurs qu’eux-mêmes durant
cette minute qui suffit à faire un héros, qui est le temps de créer, la
minute infinie de l’amour.
Ainsi, ils avaient, malgré leurs nobles pensées, malgré leurs
aspirations hautes et leur ferme conception de l’idéal, quelques
erreurs à regretter : leur idéal en était-il moins respectable ? Non,
certes ! Rien n’est absurde, rien n’est malfaisant comme de refuser à
un coupable le droit d’affirmer la beauté du bien ! Celui-là au
contraire qui connaît l’âpreté des chemins du mal, n’est-il pas le
mieux venu à recommander le choix des autres, surtout si,
franchement, il avoue ses raisons ?
Les deux amis avaient donc à leur passif plus d’une faute et ne
conseillaient à personne de les imiter ; fautes d’amour, bien entendu.
Non pas tant Albert, qui n’avait guère connu pour maîtresses que de
petites sauvages en lointains pays… Mais Paul, en pays civilisé,
n’avait eu le choix, n’étant point marié, qu’entre de précaires amours
qui, toutes également, avaient blessé sa délicatesse affinée, son
sentiment du juste et du beau. Et ses meilleurs souvenirs n’allaient
pas sans quelques remords.
Il avait, en résumé, contre la femme qui n’est pas la Mère ou
l’Épouse, non seulement les répugnances persistantes d’un
catholique émancipé tardivement — et qui a gardé, au fond, sa
manière religieuse de juger le péché ; non seulement les
répugnances d’un simple honnête homme pour tout ce qui n’est pas
avouable et avoué, mais encore une sorte de haine particulière et
violente… N’était-ce pas cette race mystérieusement maligne,
sataniquement trompeuse, qui avait fait la honte de son père, et le
malheur de sa mère adorée ?
A être demeuré longtemps dans une solitude presque complète
auprès de cette mère en deuil d’un mari vivant, à toute minute
soucieuse de préserver son fils des moindres dangers du dehors,
Paul était resté longtemps enfant, et il avait gardé les expressions
passionnées d’une tendresse qui veut être consolante. Mais aussi,
— précocement réfléchi, — avec le désir douloureux de ne jamais
ressembler à celui qui aurait dû être son modèle vénéré, il avait
conçu de la femme l’opinion que la Bible légitime en ces termes :
« La femme est amère comme la mort ; ses cheveux sont des liens
et ses mains sont des chaînes. »
La femme, c’était le serpent. Il l’évita, et il songeait, le cas
échéant, à lui écraser la tête. Il la connut tard, bien après avoir
perdu, par la lecture des philosophes, la foi de son enfance. Le jour
où il se vit trompé par l’une d’elles, il ne fut pas surpris, ni trop
malheureux : il se réjouit d’être délivré, plus qu’il ne s’affligea d’être
trahi.
Albert, lui, parlait plus rondement de tout ce qui a trait à l’éternel
sujet. Il appelait le remords une perte de temps et affirmait qu’on a
plus tôt fait d’agir mieux que de regretter d’avoir mal agi. Il prétendait
que si on a conduit une femme à l’oubli de ses devoirs on n’a plus le
droit de la condamner, tandis que, tout en se blâmant lui-même,
Paul, en pareille occasion, n’accordait à la femme que son mépris,
attristé mais entier. Albert d’ailleurs avait une tendance naturelle à
prendre toutes choses du bon côté, à interpréter avec bienveillance
les actes douteux. Il n’était pas facilement soupçonneux, nullement
méfiant. Il n’avait été pris dans aucune aventure compliquée, dans
aucune intrigue, et s’étonnait ingénument de celles que lui contait
son ami. Au fond il avait la naïveté des savants pour qui tout est
théorie et que la vie n’a pas instruits à leurs dépens.
Paul au contraire, malgré ses résistances théoriques, s’était
trouvé à plusieurs reprises enlacé par de dangereuses coquettes.
Mais, armé de méfiance comme il l’était par le souvenir du malheur
de son père, il avait voulu et su les voir toutes à visage découvert.
Une d’elles avait été si agréablement surprise d’être démasquée,
elle en avait conçu une si vive admiration pour l’esprit de Paul,
qu’elle lui avait livré gaîment tous les secrets de sa vie. Il avait tiré
de là le plus clair de son expérience. Il avait reconnu, avec cette
Ariane, les moindres petits chemins contournés où un esprit de
femme rusée s’amuse à perdre un mari et un ou plusieurs amants…
Le danger de posséder cette sorte d’expérience apprise, méditée et
approfondie, c’est qu’on se sent porté à appliquer à toute la race des
femmes la mesure qui doit, en bonne justice, ne s’appliquer qu’à une
seule catégorie. C’était du moins l’avis d’Albert, qui, à tout instant
criait à Paul : Casse-cou !
D’ailleurs, Paul ne tombait généralement pas dans cette erreur
d’étendre sur toutes, sans examen, le scepticisme qui lui avait été
inspiré par ses propres mésaventures ni la méfiance qui lui était
conseillée par le souvenir toujours présent des mésaventures
paternelles. Il croyait qu’il y a, bien distinctes, deux sortes de
femmes : celle des Épouses, des Mères, des Sœurs — et la race
des Autres. C’était, en effet, pour lui comme deux races, si
essentiellement différentes qu’elles ne peuvent se mêler entre elles.
Il admettait des valeurs personnelles diverses dans un camp comme
dans l’autre, — mais c’était bien deux camps séparés par un
infranchissable fossé.
Sur ce point encore, il ne raisonnait pas. Il croyait cela
passionnément, comme autrefois il avait cru aux choses que lui
affirmait l’abbé, — et Albert avait fort à faire pour combattre ses
entêtements là-dessus.
Paul concluait toujours ainsi : « Laisse-moi mes idées : elles me
sauvent… Je ne veux pas faire courir à ma mère le risque d’avoir
pour belle-fille une de ces femmes qui sont faites pour rester parmi
les autres !… »
Paul, une fois, avait cru rencontrer la Fiancée, Son cœur avait
battu vite. Il s’était trouvé malheureusement que celle-là aimait
ailleurs…
Depuis, il ne cherchait plus, se disant que sa mère, vieillissante
et malade, avait besoin de lui, de la tendresse sûre de ses enfants,
et que se marier, c’était faire courir à cette mère chérie une trop
grande chance de malheur…
Or, depuis quelque temps, gagné de plus en plus à la cause de
l’indulgence et de la pitié quand même, il s’était mis à blâmer
sévèrement son habituelle tendance à douter de la plupart des
femmes. Il se méfiait de ses méfiances. Dans son honnêteté
philosophique, avide de progrès, il craignait de former des
jugements téméraires, de tourner au pessimiste aigri, et enfin, par-
dessus le marché, de passer sottement à côté du bonheur. Il
s’inquiétait donc de son scepticisme invétéré à l’endroit des femmes,
et, réagissant avec énergie, il accordait parfois d’aveugles
confiances à celles-là mêmes dont il avait pensé le plus de mal. En
ceci encore, il était compliqué, mais avec simplicité : nettement
double.
Mademoiselle Déperrier n’éveilla pas chez lui une ombre
d’inquiétude. Il la vit, et elle le charma. Il tendit son cœur vers elle,
naturellement, comme le voyageur du désert, altéré, court vers l’eau
qui semble pure sous un reflet de ciel…
Il la vit et il l’aima.
VI

Toutes les belles et bonnes raisons qu’il avait d’aimer avec


passion la jeune fille, Paul deux mois après, les expliquait
brusquement à son ami, — au moment précis où Albert allait lui dire,
pour son compte, — les mêmes choses.
Ce n’était donc pas Albert qui pouvait lui inspirer contre
Mademoiselle Déperrier le moindre doute. Le pauvre lieutenant de
vaisseau reçut cette confidence — amour et projet de mariage, —
comme un coup de couteau dont on meurt en silence.
Ils se promenaient sous les platanes d’Aiguebelle, à mi-coteau,
avec la mer à l’horizon, — et, par-dessus l’échiquier blanc et bleu
des salins, ils voyaient les grands bateaux en ce moment mouillés
là.
— Eh bien, qu’en dis-tu, Albert ?
Albert réfléchissait.
L’aveu de son amour à Paul, lui devenait impossible juste dans le
moment où il allait le faire. Parler franchement, c’était désespérer
son ami… Au profit de qui ? De lui-même ? Mais pourquoi serait-ce
lui le choisi de cette jeune fille ? Il y avait bien plus d’apparence
qu’elle aimerait un homme comme Paul… Les marins partent trop
souvent. Leurs femmes sont des demi-veuves…
A ces considérations, il en ajouta une décisive : il fallait qu’un des
deux amis se sacrifiât. Paul avait confessé son amour. Albert n’avait
encore rien dit. Le sacrifice le plus complet, le plus utile, le seul
heureux, c’était donc le sien, puisqu’il resterait ignoré. Paul en
pourrait jouir sans une ombre de regret.
Le brave garçon prit rapidement son parti.
— Mon cher frère, dit-il (ils s’appelaient quelquefois ainsi), je
crois, à en juger par toutes les apparences, que tu as bien placé ton
cœur. Tu seras heureux… comme tu le mérites. Mais moi, si tu te
maries bientôt…, je ne serai pas là.
— Comment donc ?
— J’ai sollicité avant-hier le commandement d’une canonnière au
Tonkin. Je suis chaudement appuyé par l’amiral Drevet : je me crois
sûr d’obtenir ce que je désire.
— Ah ! quel malheur ! dit simplement Paul, — habitué à ces
brusques départs du marin.
Ils continuèrent à parler de ce mariage.
Le soir même, le lieutenant de vaisseau écrivait à son ami :
« Je suis forcé de partir pour Paris, appelé par dépêche. Mon
affaire réussira. Sois heureux… sois heureux… »
Il y avait, dans la répétition de ces deux mots, une douleur que
Paul ne pouvait pas voir.
Albert ne se doutait pas qu’il allait laisser derrière lui sa sœur
Pauline désespérée du mariage de Paul. Elle avait, pour l’ami de
son frère, depuis qu’elle était née à la vie du cœur, un noble, un
profond amour, ignoré même de sa mère.
Il obtint son commandement, et partit, au grand chagrin
d’Annette, la petite sœur de Paul. Annette avait pour lui —
symétriquement ! — un amour de pensionnaire dont il était bien loin
de se douter, — et qui l’eût consolé peut-être…
Et, peu de temps après la conversation des deux amis et le
départ d’Albert, le comte Paul avait ouvert son cœur à sa mère…
Elle avait souri tristement… — et c’est alors qu’elle avait écrit à
l’abbé.
Quand elle eut reçu la réponse du vieux précepteur de Paul, il fut
convenu qu’on irait passer à Paris tout ce printemps. Elle voulait voir
et juger Mademoiselle Déperrier. De plus, le départ d’Albert laissait
bien seules Madame de Barjols et sa fille. On partit donc. La
présentation des dames Déperrier chez la comtesse d’Aiguebelle, à
Paris, se fit un soir où il y avait quelques personnes. Marie se tint sur
une réserve extrême… Et il n’y eut rien que l’observation en attente,
de part et d’autre.
Deux mois plus tard, en avril, Paul demandait à sa mère, pour la
centième fois : « Eh bien, que pensez-vous d’elle, ma mère ? »
— Donne-moi le temps de me reconnaître.
Mademoiselle Déperrier n’était pas sympathique à la comtesse.
Le cœur des mères voit profond. Mais la mère de Paul ne trouvait
rien à dire pour justifier son antipathie. Elle ne l’avouait donc pas, et
se contentait d’ajourner le prononcé de son jugement. Désolée
d’avoir à faire souffrir Paul, elle avait cependant ce courage.
— Tu ne peux vraiment pas, lui disait-elle en souriant, me forcer
à être aussi emportée que toi… Il y a dans ton opinion sur elle,
d’après tes propres théories, un élément d’erreur : l’amour même.
Moi, je n’ai qu’à l’aimer d’une amitié forte, qui naîtra uniquement de
mon jugement moral… Donne-moi le temps !
Il attendait avec confiance, — puisqu’il aimait.
VII

Ce n’était pas peu de chose — elle le comprenait bien, — que


d’apparaître à son provincial une femme « comme il faut », telle qu’il
devait l’entendre.
Dans ses tentatives variées d’ambitieuse inquiète, elle avait
naturellement pensé au théâtre. C’est le tremplin de beaucoup de
coquettes, un moyen de parvenir comme un autre, aujourd’hui ;
seulement, il y faut du talent, et c’est à quoi pensent le moins toutes
ces pauvrettes qui vont au feu de la rampe comme des papillons
affolés.
Un des jeunes acteurs, espérant, selon sa propre expression,
qu’il arriverait bien vite à « faire ses frais », avait donné des leçons
gratis, pendant une année ; puis, irrité tout à coup de voir qu’il n’avait
rien à espérer, il avait offert de se faire remplacer par un vieux
« cabot » de sa connaissance, pauvre et laid, qui, pour un déjeuner,
affirmait-il, donnerait des leçons de maintien et de diction, d’après
les plus solides principes.
Dès qu’il eut présenté le vieux, le jeune émule de Talma, qui avait
une affaire urgente dans les coulisses du Conservatoire, espaça ses
précieuses visites. On ne le voyait plus que deux fois par an.
En revanche, le vieux cabotin arrivait deux fois par semaine.
C’était un ancien élève de Samson. Il le disait et c’était vrai. Il avait
des cartes à un franc le cent sur lesquelles on lisait en lettres
grasses :

PINCHARD,
de la Comédie française.
Il y avait débuté en effet vers 1845. Il n’avait plus d’âge. C’était
un doux souffreteux, très honnête, très bon, mais doué à un degré
plaisant de tous les défauts particuliers à ceux de sa profession.
L’inaltérable gaîté qu’il gardait malgré l’excès de sa misère, lui faisait
tout pardonner.
Le malheureux avait même imaginé, un jour où il avait trop faim,
d’aller réciter des vers, dans les cours des maisons. C’était une
chose attendrissante que de lui voir rejouer, pour payer à table sa
place de parasite, son rôle de mendiant des rues.
— Le jour où je pris cette résolution, disait-il, j’entrai d’abord dans
une cour de la rue des Saints-Pères. J’avais appris avec beaucoup
de soin la Conscience de Victor Hugo, — mais la honte me
suffoquant, au moment de commencer, j’attaquai, sans le vouloir, le
récit de Théramène que je savais depuis mon enfance ! Ma douleur
était si vive, que je me sentis pathétique. Ah ! si un public
connaisseur, un vrai public, mon public de la Comédie française,
avait pu me voir ce jour-là !… On s’était mis aux fenêtres, et les sous
commencèrent à pleuvoir avec les quolibets.
Alors, il se mettait à mimer la scène, laissant tomber un sou à
terre, de temps à autre, et interrompant d’un « merci bien ! » du plus
piquant effet, l’illustre tirade, à la manière des joueurs d’orgue de
Barbarie.
— « A la fin, terminait-il, saisi par le désespoir de ma situation
personnelle, je tombai sur un genou, la tête dans mes mains, en
criant malgré moi : « Non ! non ! c’est trop souffrir ! » On attribua ma
douleur à Théramène ; on crut que je pleurais ce pauvre Hippolyte,
et, à toutes les fenêtres, éclatèrent des applaudissements, dont,
malgré mon désespoir, je me sentis encouragé, et même charmé !
« Cela parut si comique à une bande d’étudiants groupés à une
fenêtre du cinquième, qu’ils m’envoyèrent chercher, et de ce
moment, j’entrevis des jours meilleurs. J’allais, répétant
quotidiennement, dans les cours des maisons où logent des
étudiants, le récit de Théramène.
« Profitant de l’indication que m’avaient donnée « la nature » et le
hasard, je coupais le fameux récit de réflexions de mon cru sur ma
misère et le malheur des temps… Et cela m’a permis de vivre. Tout
le quartier me connaît sous le nom de Théramène… Appelez-moi
comme ça. Ça me fera plaisir, ça me rappelle mon plus gros
succès ! »
C’était un professeur économique qu’on avait pris en affection, ce
vieux. On lui mettait quelquefois un balai entre les mains ;
quelquefois, sous le pied, une brosse à cirer le parquet ; et il cirait, et
il balayait, disant : « L’art se rend utile : Utile dulci ! » Et, vraiment, il
lui était doux, à cet ingénu, de se rendre utile à qui l’aidait.
De fait, il était intéressant, et on l’aimait sans y prendre garde,
comme on aime un animal familier. C’était même, peut-être, le
meilleur des sentiments que Mademoiselle Déperrier eût au cœur,
celui que ce vieil innocent lui inspirait… Ah ! si elle n’avait pas eu de
connaissances pires ! Mais l’honnête Théramène eût certainement
méprisé bien des beaux messieurs qui venaient chez elle,
admirablement vêtus et correctement gantés, s’il eût pu voir leur
dedans.
Tout de même, c’était un spectacle inouï que d’assister à la leçon
du père Théramène chez les Déperrier, le mardi.
Léon Terral y venait souvent. Il y amenait deux ou trois amis. On
y voyait aussi le bas-bleu qui faisait les modes, deux ou trois
reporters qui pouvaient être utiles un jour, et autant de futurs auteurs
dramatiques, de ceux qui collaborent uniquement pour avoir leurs
entrées dans les coulisses des petits théâtres.
Peut-être, ce jour-là, eût-on malaisément reconnu la belle
Mademoiselle Déperrier, celle qui dans les salons plus ou moins
selects, mais enfin de ceux où l’on rencontre parfois du vrai monde,
se tenait droite, fière, en grande tenue de patricienne, s’imposant au
regard par la noblesse du maintien, la beauté de ses lignes fermes
et ondulées, et la pureté de son regard, un peu hautain.
Ces jours-là, chez elle, c’était la fête bohème. Sa mère ne s’y
amusait guère, parce qu’elle ne pouvait retenir mille objurgations
que Marie ne manquait jamais de relever. La mère était partagée
entre un désir déterminé de tirer parti de sa fille en la mariant à
quelque prince — et une jalousie féroce, qui enrageait de ne pouvoir
se dissimuler. De là une sourde querelle qui régnait éternellement
entre elles.
Madame Déperrier avait fini, les mardis, par rester confinée dans
sa chambre, d’où elle sortait de demi-heure en demi-heure pour faire
quelque admonestation à propos d’une parole plus mal sonnante
que les autres, surprise à travers la cloison.
Peu à peu, dans la chaleur des leçons, le vieux Théramène
s’était habitué à tutoyer couramment sa petite Marie. A l’indignation
de sa mère, Marie avait répondu, non sans quelque bonté :
— Quel mal ça peut-il faire ?… Pauvre homme ! il est si vieux…
Pourquoi l’humilier ? Veux-tu qu’il ne revienne plus ? Je serais bien
avancée ! Car, tu ne sais pas, au fond, il est très fort. Et il me
lâcherait, un peu raide. Et puis, ça m’amuse. C’est comme ça qu’on
fait au théâtre ; on se tutoie entre camarades, hommes et femmes.
Elle pensait encore : « Pourquoi empêcher cet homme de se
payer comme ça ? » Par de semblables raisonnements, trop
fréquents chez elle, elle acceptait, sans s’en douter, de se vendre en
détail. Elle ne s’appartenait plus. Elle appartenait à mille menues
dettes. C’est le destin des filles… Que de gens avaient ainsi main-
mise sur elle !
Il la tutoyait donc, Théramène ; elle en riait d’abord ; bientôt elle
se blasa, et c’était d’autant plus étrange, depuis qu’elle paraissait ne
plus voir ce qu’il y avait là de choquant.
— Voyons, ma petite Marie, le mot ne sort pas ; tu bafouilles.
Tiens-toi droite. Les mains comme ça… Marche donc avec tout le
corps. Tu as l’air de glisser dans une rainure…
Il redressait son dos voûté, et la vieillesse décrépite et laide
donnait sa leçon d’attitude et de noblesse à la beauté jeune.
Si l’on riait, mes bons ! Rien n’était plus divertissant.
C’était drôle surtout quand il répétait la théorie « telle que je l’ai
recueillie de la propre bouche de mon maître Samson ».
Il y avait toujours quelqu’un pour lui crier : « Le bourreau ? »
— Non, messieurs, répondait Théramène ; je parle de l’illustre
comédien.
Et il commençait :
— Quand vous rentrez chez vous, le soir, qu’est-ce que vous
faites ?
— Je prends mon bougeoir chez mon concierge, répondait
invariablement un des jeunes gens.
— Bon. Après ?
— Je monte mon escalier.
— Je veux bien ; mais, pour monter votre escalier, qu’est-ce que
vous faites ?
— Je lève le pied.
— Comme un caissier… C’est là que je vous attendais… Eh
bien ! messieurs, dans une tirade, le premier vers c’est la première
marche, et comme on lève le pied de marche en marche, vous
élevez la voix, de vers en vers — jusqu’où ?
— Jusque chez moi, au cinquième.
— Mais non ! Jusqu’au premier palier. Les paliers sont là pour
nous permettre de souffler — et de prendre des temps. Vous prenez
donc un temps… Et puis ?
— J’attaque le second étage…
— Jusqu’au palier suivant. Et puis ?
— Et puis, je rentre chez moi.
— Mais non, malheureux ! vous ne rentrez pas chez vous… Et
c’est bien là que je vous attendais, car aucune science ne
s’improvise ! Les secrets de l’art, monsieur, sont le trésor de
l’humanité. Ce sont des fruits, lentement mûris, que la tradition
conserve et transmet — lampada tradunt — et qui permettent à
Pinchard de donner la main à Molière, par une chaîne non
interrompue d’hommes de talent, j’oserai dire de génie.
Cette phrase était acclamée.
— Prenez un temps, Pinchard. Vous voilà au cinquième.
— A la fin de la tirade, poursuivait Pinchard imperturbable, vous
ne rentrez pas chez vous… Loin de là !… Vous vous précipitez
brusquement, la tête la première, dans la cage de l’escalier… c’est-
à-dire que vous laissez retomber tout à coup votre voix dans les
notes basses, en la prenant dans le creux, et vous faites un grand
effet sur le public !
De Marie, Théramène avait fait Rita…, Mariquita, Marita, Rita…
Si bien que toute la bande des littéraires se mit à l’appeler ainsi,
dans l’intimité, et Léon Terral tout le premier.
Elle se montrait à eux dans des demi-négligés un peu suspects.
Il fallait garder ce qu’elle avait de mieux pour la parade de la rue ou
des grandes soirées. Ici, à ces gens qu’elle comptait bien licencier
un jour, elle se laissait voir en déshabillé, avec une robe fatiguée,
fripée un peu, je ne sais quoi d’abandonné, de lâche, de médiocre
en elle. Ce n’était pas par respect pour sa personne, ni par goût du
joli, qu’elle aimait la propreté, mais seulement parce qu’elle la croyait
indispensable dans l’art de plaire. Or, qu’avait-elle besoin de plaire à
ces gens-là ! Il aurait fallu s’imposer un effort qu’ils ne méritaient pas.
C’est par paresse, et aussi par économie, qu’elle se relâchait ainsi
de son habituelle coquetterie… Ah ! si elle avait eu une femme de
chambre !… Mais, dès qu’elle serait riche, tout changerait… Et elle
rêvait quelquefois d’une salle de bain étonnante, où la baignoire
serait en argent massif, les robinets en or, et où elle prendrait des
bains de lait.
— En attendant, je suis bien assez belle pour eux, telle que je
suis. Mazette ! on leur en fournira, des filles comme moi, à regarder
pour rien, tant qu’ils veulent !
Lorsqu’elle revint d’Hyères, elle fit entendre à tout ce monde
inférieur que les réunions du soir n’auraient pas lieu cette année.
Elle ne voulait pas se faire surprendre, une belle après-midi, au
milieu de tout ce monde, par le comte Paul, qui ne pouvait tarder à
venir chez elle.
Le pauvre Théramène accourut désespéré.
— Mon petit Théramène, c’est fini, je n’ai plus besoin de vous ;
j’ai des raisons graves. Jusqu’ici ça pouvait aller, vos visites ; ça ne
peut plus. C’est un parti à prendre. Je comprends que ça vous
embête ; moi aussi d’ailleurs. Vous m’amusiez tant !
Le vieux bouffon avait des larmes plein ses yeux. Sa main
tremblait.
— C’est, que j’ai pris l’habitude de te voir, ma petite Rita. Je me
suis attaché à toi comme une vieille bête de toutou… Et puis, c’était
au moins un déjeuner par semaine, un vrai, avec des œufs dans les
omelettes.
— Qu’est-ce que vous voulez ? C’est comme ça !
— Je dirai à tout le monde que je suis le frotteur, fit-il tout à coup
avec une humilité sincère et tendre, qu’il accentua théâtralement en
pliant l’échine d’une façon burlesque.
Elle réfléchit :
— Comme ça, oui, si tu veux, père Théramène.
— Elle m’a tutoyé, l’enfant !
— Ça n’est pas la première fois.
— Et dis-moi, Rita, je déjeunerai encore, hein ?
— Oui, à la cuisine.
VIII

Elle avait ainsi fait la toilette de sa maison. Elle avait balayé les
bohèmes : le seul qui restât balayait la poussière de leurs souliers.
Et certains coins de l’appartement des Déperrier en avaient, ma foi,
besoin. Bien que le salon fût la pièce soignée, d’apparence presque
élégante, il ne fallait pas chercher longtemps pour voir que rien n’y
était de vrai luxe, mais le faux y avait quelque simplicité. On eût dit
qu’il n’était point question de tricher. C’est qu’elle avait du goût, et
savait donner aux étoffes les moins précieuses une élégance de bon
aloi par la manière dont elle les posait et les drapait, autour des
glaces et sur les meubles. Cela dissimulait bien des délabrements ;
l’art est le grand cache-misère. Le comte Paul, n’ayant jamais vu le
petit salon des dames Déperrier, n’avait été frappé que du goût de
l’arrangement, de l’heureux choix des pauvres bibelots. Il tournait
tout à l’éloge de la ravissante fille. Comme il n’arrivait jamais à
l’improviste, elle le recevait sous les armes. Alors, elle avait ses
chaussures les plus soignées, ses bas des grands jours, une robe
simple, le tout sortant des meilleures maisons, où elle obtenait des
rabais inouïs par l’entremise du bas-bleu chroniqueur de modes. Elle
n’était pas de ces lanceuses qui portent des toilettes de prix pour
rendre service aux couturiers… qui, en échange, les leur donnent.
Elle ne les payait qu’en partie, mais elle payait… « Comme ça,
personne n’avait rien à dire ! »
Quant à la comtesse d’Aiguebelle, malgré les craintes de Marie, il
lui était impossible d’être renseignée à fond sur elle, car du mauvais
monde, et même du bon, que fréquentaient les dames Déperrier,
personne ne pénétrait chez le comte Paul. Une chose encore les
préservait, c’est que certaines gens répugnent à certains moyens
d’information.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like