100% found this document useful (13 votes)
67 views82 pages

Get Mastering Oracle SQL 1st Edition Sanjay Mishra Free All Chapters

SQL

Uploaded by

adaniapalen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (13 votes)
67 views82 pages

Get Mastering Oracle SQL 1st Edition Sanjay Mishra Free All Chapters

SQL

Uploaded by

adaniapalen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Download the full version of the ebook now at ebookultra.

com

Mastering Oracle SQL 1st Edition Sanjay


Mishra

https://ebookultra.com/download/mastering-oracle-
sql-1st-edition-sanjay-mishra/

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


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

Mastering Oracle SQL 2nd Edition Mishra

https://ebookultra.com/download/mastering-oracle-sql-2nd-edition-
mishra/

ebookultra.com

Pro Oracle SQL Expert s Voice in Oracle 1st Edition Karen


Morton

https://ebookultra.com/download/pro-oracle-sql-expert-s-voice-in-
oracle-1st-edition-karen-morton/

ebookultra.com

Mastering Oracle Scheduler in Oracle 11g Databases 1st


Edition Ronald Rood

https://ebookultra.com/download/mastering-oracle-scheduler-in-
oracle-11g-databases-1st-edition-ronald-rood/

ebookultra.com

Oracle PL SQL Programming Sixth Edition Steven Feuerstein

https://ebookultra.com/download/oracle-pl-sql-programming-sixth-
edition-steven-feuerstein/

ebookultra.com
Beginning Oracle SQL 3rd Edition Lex De Haan

https://ebookultra.com/download/beginning-oracle-sql-3rd-edition-lex-
de-haan/

ebookultra.com

Oracle SQL Loader the definitive guide 1st Edition


Jonathan Gennick

https://ebookultra.com/download/oracle-sql-loader-the-definitive-
guide-1st-edition-jonathan-gennick/

ebookultra.com

Oracle SQL tuning pocket reference 1st ed Edition Mark


Gurry

https://ebookultra.com/download/oracle-sql-tuning-pocket-
reference-1st-ed-edition-mark-gurry/

ebookultra.com

Oracle SQL Plus the definitive guide 2nd ed Edition


Jonathan Gennick

https://ebookultra.com/download/oracle-sql-plus-the-definitive-
guide-2nd-ed-edition-jonathan-gennick/

ebookultra.com

Exper t Oracle SQL Optimization Deployment and Statistics


1st Edition Tony Hasler (Auth.)

https://ebookultra.com/download/exper-t-oracle-sql-optimization-
deployment-and-statistics-1st-edition-tony-hasler-auth/

ebookultra.com
Mastering Oracle SQL 1st Edition Sanjay Mishra Digital
Instant Download
Author(s): Sanjay Mishra, Alan Beaulieu
ISBN(s): 9780596001292, 0596001290
Edition: 1
File Details: PDF, 4.61 MB
Year: 2002
Language: english
,TITLE.12934 Page i Wednesday, March 27, 2002 2:34 PM

Mastering Oracle SQL

Sanjay Mishra and Alan Beaulieu

Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo


,COPYRIGHT.12657 Page ii Wednesday, March 27, 2002 2:34 PM

Mastering Oracle SQL


by Sanjay Mishra and Alan Beaulieu

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.


Printed in the United States of America.

Published by O’Reilly & Associates, Inc., 1005 Gravenstein Highway North,


Sebastopol, CA 95472.

O’Reilly & Associates books may be purchased for educational, business, or sales promotional
use. Online editions are also available for most titles (safari.oreilly.com). For more information
contact our corporate/institutional sales department: (800) 998-9938 or [email protected].

Editor: Jonathan Gennick


Production Editor: Colleen Gorman
Cover Designers: Ellie Volckhausen and Emma Colby
Interior Designer: David Futato

Printing History:
April 2002: First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered
trademarks of O’Reilly & Associates, Inc. Many of the designations used by manufacturers and
sellers to distinguish their products are claimed as trademarks. Where those designations appear
in this book, and O’Reilly & Associates, Inc. was aware of a trademark claim, the designations
have been printed in caps or initial caps. Oracle® and all Oracle-based trademarks and logos are
trademarks or registered trademarks of Oracle Corporation, Inc., in the United States and other
countries. O’Reilly & Associates, Inc., is independent of Oracle Corporation. The association
between the image of a lantern fly and the topic of mastering Oracle SQL is a trademark of
O’Reilly & Associates, Inc.

While every precaution has been taken in the preparation of this book, the publisher and the
authors assume no responsibility for errors or omissions, or for damages resulting from the use of
the information contained herein.

ISBN: 0-596-00129-0
[M]
,AUTHOR.COLO.12460 Page 1 Wednesday, March 27, 2002 2:33 PM

About the Authors


Sanjay Mishra is a certified Oracle database administrator with more than ten years of
IT experience. He has been involved in the design, architecture, and implementation of
many mission-critical and decision support databases. He has worked extensively in
database architecture, database management, backup/recovery, performance tuning,
Oracle Parallel Server, and parallel execution. He has a Bachelor of Science degree in
Electrical Engineering and a Master of Engineering degree in Systems Science and Auto-
mation. He is the coauthor of Oracle Parallel Processing and Oracle SQL Loader: The
Definitive Guide (both published by O’Reilly). Presently, he works as a database archi-
tect at Dallas-based i2 Technologies, and can be reached at [email protected].
Alan Beaulieu has been designing, building, and implementing custom database appli-
cations for over 13 years. He currently runs his own consulting company that
specializes in designing Oracle databases and supporting services in the fields of finan-
cial services and telecommunications. In building large databases for both OLTP and
OLAP environments, Alan utilizes such Oracle features as Parallel Query, Partitioning,
and Parallel Server. Alan has a Bachelor of Science degree in Operations Research from
the Cornell University School of Engineering. He lives in Massachusetts with his wife
and two daughters and can be reached at [email protected].

Colophon
Our look is the result of reader comments, our own experimentation, and feedback
from distribution channels. Distinctive covers complement our distinctive approach
to technical topics, breathing personality and life into potentially dry subjects.
The insect on the cover of Mastering Oracle SQL is a lantern fly. The lantern fly is
mostly tropical, with a wingspan of up to six inches. The lantern fly’s elongated head is
an evolutionary adaptation called automimicry, in which parts of the body are disguised
or artifically shifted to other areas to confuse predators: the lantern fly’s head looks like
a tail, and its tail looks like a head. On the rear it has artificial eyes and antennae.
Colleen Gorman was the production editor and copyeditor for Mastering Oracle SQL.
Sheryl Avruch and Ann Schirmer provided quality control. Tom Dinse wrote the index.
Ellie Volckhausen and Emma Colby designed the cover of this book, based on a
series design by Edie Freedman. The cover image is a 19th-century engraving from
Johnson’s Natural History. Emma Colby produced the cover layout with Quark-
XPress 4.1 using Adobe’s ITC Garamond font.
David Futato designed the interior layout. Neil Walls converted the files from
Microsoft Word to FrameMaker 5.5.6 using tools written in Perl by Erik Ray, Jason
McIntosh, and Neil Walls, as well as tools written by Mike Sierra. The text font is
Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is
LucasFont’s TheSans Mono Condensed. The illustrations that appear in the book
were produced by Robert Romano and Jessamyn Read using Macromedia FreeHand
9 and Adobe Photoshop 6. The tip and warning icons were drawn by Christopher
Bing. This colophon was written by Colleen Gorman.
,DEDICATION.12802 Page iii Wednesday, March 27, 2002 2:34 PM

I dedicate this book to my father.


I wish he were alive to see this book.
—Sanjay Mishra

To my daughters, Michelle and Nicole.


—Alan Beaulieu
,DEDICATION.12802 Page iv Wednesday, March 27, 2002 2:34 PM
,mast_ora_sqlTOC.fm.10634 Page v Wednesday, March 27, 2002 2:23 PM

Table of Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii

1. Introduction to SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What Is SQL? 1
A Brief History of SQL 2
A Simple Database 4
DML Statements 4

2. The WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14


Life Without WHERE 14
WHERE to the Rescue 15
WHERE Clause Evaluation 16
Conditions and Expressions 18
WHERE to Go from Here 24

3. Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Inner Joins 26
Outer Joins 30
Self Joins 37
Joins and Subqueries 42
DML Statements on a Join View 43
ANSI-Standard Join Syntax in Oracle9i 49

4. Group Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Aggregate Functions 55
The GROUP BY Clause 59
The HAVING Clause 65

v
,mast_ora_sqlTOC.fm.10634 Page vi Wednesday, March 27, 2002 2:23 PM

5. Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
What Is a Subquery? 68
Noncorrelated Subqueries 69
Correlated Subqueries 75
Inline Views 77
Subquery Case Study: The Top N Performers 89

6. Handling Temporal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95


Internal DATE Storage Format 95
Getting Dates In and Out of a Database 96
Date Manipulation 111
Oracle9i New DATETIME Features 124
INTERVAL Literals 132

7. Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144


Set Operators 145
Using Set Operations to Compare Two Tables 149
Using NULLs in Compound Queries 151
Rules and Restrictions on Set Operations 153

8. Hierarchical Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157


Representing Hierarchical Information 157
Simple Hierarchy Operations 160
Oracle SQL Extensions 163
Complex Hierarchy Operations 167
Restrictions on Hierarchical Queries 174

9. DECODE and CASE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175


DECODE, NVL, and NVL2 175
The Case for CASE 179
DECODE and CASE Examples 181

10. Partitions, Objects, and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192


Table Partitioning 192
Objects and Collections 202

11. PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213


What Is PL/SQL? 213
Procedures, Functions, and Packages 214
Calling Stored Functions from Queries 216

vi | Table of Contents
,mast_ora_sqlTOC.fm.10634 Page vii Wednesday, March 27, 2002 2:23 PM

Restrictions on Calling PL/SQL from SQL 220


Stored Functions in DML Statements 224
The SQL Inside Your PL/SQL 226

12. Advanced Group Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228


ROLLUP 228
CUBE 238
The GROUPING Function 244
GROUPING SETS 249
Oracle9i Grouping Features 250
The GROUPING_ID and GROUP_ID Functions 260

13. Advanced Analytic SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267


Analytic SQL Overview 267
Ranking Functions 272
Windowing Functions 286
Reporting Functions 291
Summary 296

14. SQL Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297


Know When to Use Specific Constructs 297
Avoid Unnecessary Parsing 302
Consider Literal SQL for Decision Support Systems 307

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308

Table of Contents | vii


,ch00.8321 Page viii Wednesday, March 27, 2002 2:18 PM

Preface

SQL, which stands for Structured Query Language, is the language for accessing a
relational database. SQL provides a set of statements for storing and retrieving data
to and from a relational database. It has gained steadily in popularity ever since the
first relational database was unleashed upon the world. Other languages have been
put forth, but SQL is now accepted as the standard language for almost all relational
database implementations, including Oracle.
SQL is different from other programming languages because it is nonprocedural.
Unlike programs in other languages, where you specify the sequence of steps to be
performed, a SQL program (more appropriately called a SQL statement) only
expresses the desired result. The responsibility for determining how the data will be
processed in order to generate the desired result is left to the database management
system. The nonprocedural nature of SQL makes it easier to access data in applica-
tion programs.
If you are using an Oracle database, SQL is the interface you use to access the data
stored in your database. SQL allows you to create database structures such as tables
(to store your data), views, and indexes. SQL allows you to insert data into the data-
base, and to retrieve that stored data in a desired format (for example, you might sort
it). Finally, SQL allows you to modify, delete, and otherwise manipulate your stored
data. SQL is the key to everything you do with the database. It’s important to know
how to get the most out of that interface. Mastery over the SQL language is one of
the most vital requirements of a database developer or database administrator.

Why We Wrote This Book


Our motivation for writing this book stems from our own experiences learning how
to use the Oracle database and Oracle’s implementation of the SQL language. Ora-
cle’s SQL documentation consists of a reference manual that doesn’t go into details
about the practical usefulness of the various SQL features that Oracle supports. Nor
does the manual present complex, real-life examples.

viii

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch00.8321 Page ix Wednesday, March 27, 2002 2:18 PM

When we looked for help with SQL in the computer book market, we found that
there are really two types of SQL books available. Most are the reference type that
describe features and syntax, but that don’t tell you how to apply that knowledge to
real-life problems. The other type of book, very few in number, discusses the applica-
tion of SQL in a dry and theoretical style without using any particular vendor’s
implementation. Since every database vendor implements their own variation of
SQL, we find books based on “standard” SQL to be of limited usefulness.
In writing this book, we decided to write a practical book focused squarely on Oracle’s
version of SQL. Oracle is the market-leading database, and it’s also the database on
which we’ve honed our SQL expertise. In this book, we not only cover the most impor-
tant and useful of Oracle’s SQL features, but we show ways to apply them to solve spe-
cific problems.

Objectives of This Book


The single most important objective of this book is to help you harness the power of
Oracle SQL to the maximum extent possible. You will learn to:
• Understand the features and capabilities of the SQL language, as implemented
by Oracle.
• Use complex SQL features such as outer joins, correlated subqueries, hierarchi-
cal queries, grouping operations, analytical queries, etc.
• Use DECODE and CASE to implement conditional logic in your SQL queries.
• Write SQL statements that operate against partitions, objects, and collections
such as nested tables and variable arrays.
• Use the new SQL features introduced in Oracle9i, such as new date and time fea-
tures, ANSI-compliant joins, and new grouping and analytical functions.
• Use best practices to write efficient, maintainable SQL queries.

Audience for This Book


This book is for Oracle developers and database administrators. Whether you are
new to the world of databases or a seasoned professional, if you use SQL to access an
Oracle database, this book is for you. Whether you use simple queries to access data
or embed them in PL/SQL or Java programs, SQL is the core of all data access tasks
in your application. Knowing the power and flexibility of SQL will improve your pro-
ductivity, allowing you to get more done in less time, and with increased certainty
that the SQL statements you write are indeed correct.

Preface | ix

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch00.8321 Page x Wednesday, March 27, 2002 2:18 PM

Platform and Version


We used Oracle8i (releases 8.1.6 and 8.1.7) and Oracle9i (release 9.0.1) in this book.
We’ve covered many of Oracle9i’s important new SQL features, including ANSI-
standard join syntax, new time/date datatypes, and various analytical functions.
Most of the concepts, syntax, and examples apply to earlier releases of Oracle as
well. We specifically point out the new Oracle9i features.

Structure of This Book


This book is divided into 14 chapters:
• Chapter 1, Introduction to SQL, introduces the SQL language and describes its
brief history. This chapter is primarily for those readers who have little or no
prior SQL experience. You’ll find simple examples of the core SQL statements
(SELECT, INSERT, UPDATE, and DELETE) and of SQL’s basic features.
• Chapter 2, The WHERE Clause, describes ways to filter data in your SQL state-
ments. You’ll learn to restrict the results of a query to the rows you wish to see,
and restrict the results of a data manipulation statement to the rows you wish to
modify.
• Chapter 3, Joins, describes constructs used to access data from multiple, related
tables. The important concepts of inner join and outer join are discussed in this
chapter. The new ANSI-compliant join syntax introduced in Oracle9i is also
discussed.
• Chapter 4, Group Operations, shows you how to generate summary informa-
tion, such as totals and subtotals, from your data. Learn how to define groups of
rows, and how to apply various aggregate functions to summarize data in those
groups.
• Chapter 5, Subqueries, shows you how to use correlated and noncorrelated sub-
queries and inline views to solve complex problems that would otherwise require
procedural code together with more than one query.
• Chapter 6, Handling Temporal Data, talks about handling date and time infor-
mation in an Oracle database. Learn the tricks and traps of querying time-based
data. Also learn about Oracle9i’s many new date and time datatypes.
• Chapter 7, Set Operations, shows you how to use UNION, INTERSECT, and
MINUS to combine results from two or more independent component queries
into one.
• Chapter 8, Hierarchical Queries, shows you how to store and extract hierarchi-
cal information (such as in an organizational chart) from a relational table. Ora-
cle provides several features to facilitate working with hierarchical data.

x | Preface

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch00.8321 Page xi Wednesday, March 27, 2002 2:18 PM

• Chapter 9, DECODE and CASE, talks about two very powerful yet simple fea-
tures of Oracle SQL that enable you to simulate conditional logic in what is oth-
erwise a declarative language. CASE, an ANSI standard construct, was first
introduced in Oracle8i, and was enhanced in Oracle9i.
• Chapter 10, Partitions, Objects, and Collections, discusses the issues involved
with accessing partitions and collections using SQL. Learn to write SQL state-
ments that operate on specific partitions and subpartitions. Also learn to query
object data, nested tables, and variable arrays.
• Chapter 11, PL/SQL, explores the integration of SQL and PL/SQL. This chapter
describes how to call PL/SQL stored procedures and functions from SQL state-
ments, and how to write efficient SQL statements within PL/SQL programs.
• Chapter 12, Advanced Group Operations, deals with complex grouping opera-
tions used mostly in decision support systems. We show you how to use Oracle
features such as ROLLUP, CUBE, and GROUPING SETS to efficiently generate
various levels of summary information required by decision support applica-
tions. We also discuss the new Oracle9i grouping features that enable compos-
ite and concatenated groupings, and the new GROUP_ID and GROUPING_ID
functions.
• Chapter 13, Advanced Analytic SQL, deals with analytical queries and new ana-
lytic functions. Learn how to use ranking, windowing, and reporting functions
to generate decision support information. This chapter also covers the new ana-
lytic features introduced in Oracle9i.
• Chapter 14, SQL Best Practices, talks about best practices that you should follow
in order to write efficient and maintainable queries. Learn which SQL constructs
are the most efficient for a given situation. For example, we describe when it’s
better to use WHERE instead of HAVING to restrict query results. We also dis-
cuss the performance implications of using bind variables vis-à-vis literal SQL.

Conventions Used in This Book


The following typographical conventions are used in this book.
Italic
Used for filenames, directory names, table names, field names, and URLs. It is
also used for emphasis and for the first use of a technical term.
Constant width
Used for examples and to show the contents of files and the output of com-
mands.
Constant width italic
Used in syntax descriptions to indicate user-defined items.

Preface | xi

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch00.8321 Page xii Wednesday, March 27, 2002 2:18 PM

Constant width bold


Indicates user input in examples showing an interaction. Also indicates empha-
sized code elements to which you should pay particular attention.
Constant width bold italic
Used in code examples to emphasize aspects of the SQL statements, or results,
that are under discussion.
UPPERCASE
In syntax descriptions, indicates keywords.
lowercase
In syntax descriptions, indicates user-defined items such as variables.
[]
In syntax descriptions, square brackets enclose optional items.
{}
In syntax descriptions, curly brackets enclose a set of items from which you must
choose only one.
|
In syntax descriptions, a vertical bar separates the items enclosed in curly brack-
ets, as in {TRUE | FALSE}.
...
In syntax descriptions, ellipses indicate repeating elements.

Indicates a tip, suggestion, or general note. For example, we use notes


to point you to useful new features in Oracle9i.

Indicates a warning or caution. For example, we’ll tell you if a certain


SQL clause might have unintended consequences if not used carefully.

Comments and Questions


We have tested and verified the information in this book to the best of our ability,
but you may find that features have changed or that we have made mistakes. If so,
please notify us by writing to:
O’Reilly & Associates
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (FAX)

xii | Preface

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch00.8321 Page xiii Wednesday, March 27, 2002 2:18 PM

You can also send messages electronically. To be put on the mailing list or request a
catalog, send email to:
[email protected]
To ask technical questions or comment on the book, send email to:
[email protected]
We have a web site for this book, where you can find examples and errata (previ-
ously reported errors and corrections are available for public view there). You can
access this page at:
http://www.oreilly.com/catalog/mastorasql
For more information about this book and others, see the O’Reilly web site:
http://www.oreilly.com

Acknowledgments
We are indebted to a great many people who have contributed in the development
and production of this book. We owe a huge debt of gratitude to Jonathan Gennick,
the editor of the book. Jonathan’s vision for this book, close attention to details, and
exceptional editing skills are the reasons this book is here today.
Our sincere thanks to our technical reviewers: Diana Lorentz, Jeff Cox, Stephan
Andert, Rich White, Peter Linsley, and Chris Lee, who generously gave their valu-
able time to read and comment on a draft copy of this book. Their contributions
have greatly improved its accuracy, readability, and value.
This book certainly would not have been possible without a lot of hard work and sup-
port from the skillful staff at O’Reilly & Associates, including Ellie Volckhausen and
Emma Colby, the cover designers, David Futato, the interior designer, Neil Walls,
who converted the files, Colleen Gorman, the copyeditor and production editor, Rob
Romano and Jessamyn Read, the illustrators, Sheryl Avruch and Ann Schirmer, who
provided quality control, and Tom Dinse, the indexer. Also, thanks to Tim O’Reilly
for taking time to go through this book and providing valuable feedback.

From Sanjay
My heartfelt thanks to my coauthor Alan for his outstanding technical skills, and for
his constant cooperation during the writing of this book. Special thanks to Jonathan
for not only editing this book, but also for providing me with remote access to his
Oracle9i database.
My adventure with Oracle started in the Tribology Workbench project at Tata Steel,
Jamshedpur, India. Sincere thanks to my co-workers in the Tribology Workbench

Preface | xiii

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch00.8321 Page xiv Wednesday, March 27, 2002 2:18 PM

project for all the experiments and explorations we did during our learning days with
Oracle. Special thanks to Sarosh Muncherji, the Deputy Team Leader, for picking me
up for the project and then pushing me into the Oracle world by assigning me the
responsibility of being the DBA. Ever since, Oracle database technology has become
a way of life for me.
Sincere thanks to my co-workers at i2 Technologies for support and encouragement.
Last, but not the least, I thank my wife, Sudipti, for her support, understanding, and
constant encouragement.

From Alan
I would like to thank my coauthor Sanjay and my editor Jonathan Gennick for shar-
ing my vision for this book, and for their technical and editorial prowess. I would
never have reached the finish line without your help and encouragement.
Most of all, I would like to thank my wife, Nancy, for her support, patience, and
encouragement, and my daughters, Michelle and Nicole, for their love and inspiration.

xiv | Preface

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 1 Wednesday, March 27, 2002 2:18 PM

Chapter 1 CHAPTER 1
Introduction to SQL

In this introductory chapter, we explore the origin and utility of the SQL language,
demonstrate some of the more useful features of the language, and define a simple
database design from which most examples in the book are derived.

What Is SQL?
SQL, which stands for Structured Query Language, is a special-purpose language
used to define, access, and manipulate data. SQL is nonprocedural, meaning that it
describes the necessary components (i.e., tables) and desired results without dictat-
ing exactly how results should be computed. Every SQL implementation sits atop a
database engine, whose job it is to interpret SQL statements and determine how the
various data structures in the database should be accessed in order to accurately and
efficiently produce the desired outcome.
The SQL language includes two distinct sets of commands: Data Definition Lan-
guage (DDL) is the subset of SQL used to define and modify various data structures,
while Data Manipulation Language (DML) is the subset of SQL used to access and
manipulate data contained within the data structures previously defined via DDL.
DDL includes numerous commands for handling such tasks as creating tables,
indexes, views, and constraints, while DML is comprised of just four statements:
INSERT
Adds data to a database.
UPDATE
Modifies data in a database.
DELETE
Removes data from a database.
SELECT
Retrieves data from a database.

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 2 Wednesday, March 27, 2002 2:18 PM

Some people feel that DDL is the sole property of database administrators, while
database developers are responsible for writing DML statements, but the two are not
so easily separated. It is difficult to efficiently access and manipulate data without an
understanding of what data structures are available and how they are related; like-
wise, it is difficult to design appropriate data structures without knowledge of how
the data will be accessed. That being said, this book deals almost exclusively with
DML, except where DDL is presented in order to set the stage for one or more DML
examples. The reasons for focusing on just the DML portion of SQL include:
• DDL is well represented in various books on database design and administra-
tion as well as in SQL reference guides.
• Most database performance issues are the result of inefficient DML statements.
• Even with a paltry four statements, DML is a rich enough topic to warrant not
just one book, but a whole series of books.*
So why should you care about SQL? In this age of Internet computing and n-tier
architectures, does anyone even care about data access anymore? Actually, efficient
storage and retrieval of information is more important than ever:
• Many companies now offer services via the Internet. During peak hours, these
services may need to handle thousands of concurrent requests, and unaccept-
able response times equate to lost revenue. For such systems, every SQL state-
ment must be carefully crafted to ensure acceptable performance as data
volumes increase.
• We can store a lot more data today than we could five years ago. A single disk
array can hold tens of terabytes of data, and the ability to store hundreds of ter-
abytes is just around the corner. Software used to load or analyze data in these
environments must harness the full power of SQL in order to process ever-
increasing data volumes within constant (or shrinking) time windows.
Hopefully, you now have an appreciation for what SQL is and why it is important.
The next section will explore the origins of the SQL language and the support for the
SQL standard in Oracle’s products.

A Brief History of SQL


In the early 1970s, an IBM research fellow named Dr. E. F. Codd endeavored to apply
the rigors of mathematics to the then-untamed world of data storage and retrieval.
Codd’s work led to the definition of the relational data model and a language called

* Anyone who writes SQL in an Oracle environment should be armed with the following three books: a refer-
ence guide to the SQL language, such as Oracle SQL: The Essential Reference (O’Reilly), a performance-tun-
ing guide, such as Oracle SQL Tuning Pocket Reference (O’Reilly), and the book you are holding, which
shows how to best utilize and combine the various features of Oracle’s SQL implementation.

2 | Chapter 1: Introduction to SQL

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 3 Wednesday, March 27, 2002 2:18 PM

DSL/Alpha for manipulating data in a relational database. IBM liked what they saw,
so they commissioned a project called System/R to build a prototype based on
Codd’s work. Among other things, the System/R team developed a simplified ver-
sion of DSL called SQUARE, which was later renamed SEQUEL, and finally
renamed SQL.
The work done on System/R eventually led to the release of various IBM products
based on the relational model. Other companies, such as Oracle, rallied around the
relational flag as well. By the mid 1980’s, SQL had gathered sufficient momentum in
the marketplace to warrant oversight by the American National Standards Institute
(ANSI). ANSI released its first SQL standard in 1986, followed by updates in 1989,
1992, and 1999.
Thirty years after the System/R team began prototyping a relational database, SQL is
still going strong. While there have been numerous attempts to dethrone relational
databases in the marketplace, well-designed relational databases coupled with well-
written SQL statements continue to succeed in handling large, complex data sets
where other methods fail.

Oracle’s SQL Implementation


Given that Oracle was an early adopter of the relational model and SQL, one might
think that they would have put a great deal of effort into conforming with the vari-
ous ANSI standards. For many years, however, the folks at Oracle seemed content
that their implementation of SQL was functionally equivalent to the ANSI standards
without being overly concerned with true compliance. Beginning with the release of
Oracle8i, however, Oracle has stepped up its efforts to conform to ANSI standards
and has tackled such features as the CASE statement and the left/right/full outer join
syntax.
Ironically, the business community seems to be moving in the opposite direction. A
few years ago, people were much more concerned with portability and would limit
their developers to ANSI-compliant SQL so that they could implement their systems
on various database engines. Today, companies tend to pick a database engine to use
across the enterprise and allow their developers to use the full range of available
options without concern for ANSI-compliance. One reason for this change in attitude
is the advent of n-tier architectures, where all database access can be contained within
a single tier instead of being scattered throughout an application. Another possible
reason might be the emergence of clear leaders in the DBMS market over the last five
years, such that managers perceive less risk in which database engine they choose.

Theoretical Versus Practical Terminology


If you were to peruse the various writings on the relational model, you would come
across terminology that you will not find used in this book (such as relations and

A Brief History of SQL | 3

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 4 Wednesday, March 27, 2002 2:18 PM

tuples). Instead, we use practical terms such as tables and rows, and we refer to the
various parts of an SQL statement by name rather than by function (i.e., “SELECT
clause” instead of projection). With all due respect to Dr. Codd, you will never
hear the word tuple used in a business setting, and, since this book is targeted
toward people who use Oracle products to solve business problems, you won’t
find it here either.

A Simple Database
Because this is a practical book, it contains numerous examples. Rather than fabri-
cating different sets of tables and columns for every chapter or section in the book,
we have decided to draw from a single, simple schema for most examples. The sub-
ject area that we chose to model is a parts distributor, such as an auto-parts whole-
saler or medical device distributor, in which the business fills customer orders for
one or more parts that are supplied by external suppliers. Figure 1-1 shows the
entity-relationship model for this business.
If you are unfamiliar with entity-relationship models, here is a brief description of
how they work. Each box in the model represents an entity, which correlates to a
database table.* The lines between the entities represents the relationships between
tables, which correlate to foreign keys. For example, the CUST_ORDER table holds
a foreign key to the employee table, which signifies the salesperson responsible for a
particular order. Physically, this means that the CUST_ORDER table contains a col-
umn holding employee ID numbers, and that, for any given order, the employee ID
number indicates the employee who sold that order. If you find this confusing, sim-
ply use the diagram as an illustration of the tables and columns found within our
database. As you work your way through the SQL examples in this book, return
occasionally to the diagram, and you should find that the relationships start mak-
ing sense.

DML Statements
In this section, we introduce the four statements that comprise the DML portion of
SQL. The information presented in this section should be enough to allow you to
start writing DML statements. As is discussed at the end of the section, however,
DML can look deceptively simple, so keep in mind while reading the section that
there are many more facets to DML than are discussed here.

* Depending on the purpose of the model, entities may or may not correlate to database tables. For example,
a logical model depicts business entities and their relationships, whereas a physical model illustrates tables
and their primary/foreign keys. The model in Figure 1-1 is a physical model.

4 | Chapter 1: Introduction to SQL

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 5 Wednesday, March 27, 2002 2:18 PM

SALESPERSON MONTHS
SALESPERSON_ID: NUMBERS(5) YEAR: NUMBER(4)
NAME: VARCHAR2(50) MONTH: NUMBER(2)
PRIMARY_REGION_ID: NUMBER(5)

ORDERS
YEAR: NUMBER(4)
MONTH: NUMBER(2) REGION
CUST_NBR: NUMBER(5)
REGION_ID: NUMBER(5) REGION_ID: NUMBER(5)
SALESPERSON_ID: NUMBERS(5) NAME: VARCHAR2(50) JOB
TOT_ORDERS: NUMBER(7) SUPER_REGION_ID: NUMBER(5)
TOT_SALES: NUMBER(11,2) JOB_ID: NUMBER(3)
FUNCTION: VARCHAR2(20)
Order warehouse

CUST_ORDER
CUSTOMER ORDER_NBR: NUMBER(5) EMPLOYEE
CUST_NBR: NUMBER(5) EMP_ID: NUMBER(5)
CUST_NBR: NUMBER(5)
NAME: VARCHAR2(30) SALES_EMP_ID: NUMBER(5) FNAME: VARCHAR2(20)
REGION_ID: NUMBER(5) SALE_PRICE: NUMBER(9,2) LNAME: VARCHAR(20)
INACTIVE_DT: DATE ORDER_DT: DATE DEPT_ID: NUMBER(5)
INACTIVE_IND: CHAR(1) EXPECTED_SHIP_DT: DATE SALARY: NUMBER(5)
TOT_ORDERS: NUMBER(5) CANCELLED_DATE: DATE HIRE_DATE: DATE
LAST_ORDER_DT: DATE SHIP_DT: DATE JOB_ID: : NUMBER(3)
STATUS: VARCHAR(20) MANAGER_EMP_ID: NUMBER(5)

PART
PART_NBR: VARCHAR2(20)
LINE_ITEM DEPARTMENT
NAME: VARCHAR(30) Dept_ID: NUMBER(5)
SUPPLIER_ID: NUMBER(5) ORDER_NBR: NUMBER(5)
STATUS: VARCHAR2(10) PART_NBR: NUMBER2(20) NAME: VARCHAR2(20)
INVENTORY_QTY: NUMBER(5) QTY: NUMBER(5) LOCATION_ID: NUMBER(3)
UNIT_COST: : NUMBER(8,2) FILLED_QTY: NUMBER(5)
RESUPPLY_DATE: DATE

SUPPLIER INVENTORY_CLASS LOCATION


SUPPLIER_ID: NUMBER(5) INV_CLASS: VARCHAR2(3) LOCATION_ID: NUMBER(5)
NAME: VARCHAR2(30) LOW_COST: NUMBER(8,2) REGIONAL_GROUP: VARCHAR2(20)
HIGH_COST: NUMBER(8,2)

Figure 1-1. The parts distributor model

The SELECT Statement


The SELECT statement is used to retrieve data from a database. The set of data
retrieved via a SELECT statement is referred to as a result set. Like a table, a result set is
comprised of rows and columns, making it possible to populate a table using the result
set of a SELECT statement. The SELECT statement can be summarized as follows:
SELECT <one or more things>
FROM <one or more places>
WHERE <zero, one, or more conditions apply>

DML Statements | 5

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 6 Wednesday, March 27, 2002 2:18 PM

While the SELECT and FROM clauses are required, the WHERE clause is optional
(although you will seldom see it omitted). We therefore begin with a simple example
that retrieves three columns from every row of the customer table:
SELECT cust_nbr, name, region_id
FROM customer;

CUST_NBR NAME REGION_ID


---------- ------------------------------ ----------
1 Cooper Industries 5
2 Emblazon Corp. 5
3 Ditech Corp. 5
4 Flowtech Inc. 5
5 Gentech Industries 5
6 Spartan Industries 6
7 Wallace Labs 6
8 Zantech Inc. 6
9 Cardinal Technologies 6
10 Flowrite Corp. 6
11 Glaven Technologies 7
12 Johnson Labs 7
13 Kimball Corp. 7
14 Madden Industries 7
15 Turntech Inc. 7
16 Paulson Labs 8
17 Evans Supply Corp. 8
18 Spalding Medical Inc. 8
19 Kendall-Taylor Corp. 8
20 Malden Labs 8
21 Crimson Medical Inc. 9
22 Nichols Industries 9
23 Owens-Baxter Corp. 9
24 Jackson Medical Inc. 9
25 Worcester Technologies 9
26 Alpha Technologies 10
27 Phillips Labs 10
28 Jaztech Corp. 10
29 Madden-Taylor Inc. 10
30 Wallace Industries 10
Since we neglected to impose any conditions via a WHERE clause, our query returns
every row from the customer table. If we want to restrict the set of data returned by
the query, we could include a WHERE clause with a single condition:
SELECT cust_nbr, name, region_id
FROM customer
WHERE region_id = 8;

CUST_NBR NAME REGION_ID


---------- ------------------------------ ----------
16 Paulson Labs 8
17 Evans Supply Corp. 8
18 Spalding Medical Inc. 8
19 Kendall-Taylor Corp. 8
20 Malden Labs 8

6 | Chapter 1: Introduction to SQL

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 7 Wednesday, March 27, 2002 2:18 PM

Our result set now includes only those customers residing in the region with a
region_id of 8. But what if we want to specify a region by name instead of region_id?
We could query the region table for a particular name and then query the customer
table using the retrieved region_id. Instead of issuing two different queries, however,
we could produce the same outcome using a single query by introducing a join, as in:
SELECT customer.cust_nbr, customer.name, region.name
FROM customer, region
WHERE region.name = 'New England'
AND region.region_id = customer.region_id;

CUST_NBR NAME NAME


---------- ------------------------------ -----------
1 Cooper Industries New England
2 Emblazon Corp. New England
3 Ditech Corp. New England
4 Flowtech Inc. New England
5 Gentech Industries New England

Our FROM clause now contains two tables instead of one, and the WHERE clause
contains a join condition that specifies that the customer and region tables are to be
joined using the region_id column found in both tables. Joins and join conditions
will be explored in detail in Chapter 3.
Since both the customer and region tables contain a column called name, you must
specify which table’s name column you are interested in. This is done in the previ-
ous example by using dot-notation to append the table name in front of each col-
umn name. If you would rather not type the full table names, you can assign table
aliases to each table in the FROM clause and use those aliases instead of the table
names in the SELECT and WHERE clauses, as in:
SELECT c.cust_nbr, c.name, r.name
FROM customer c, region r
WHERE r.name = `New England'
AND r.region_id = c.region_id;

In this example, we assigned the alias “c” to the customer table and the alias “r” to
the region table. Thus, we can use “c.” and “r.” instead of “customer.” and “region.”
in the SELECT and WHERE clauses.

SELECT clause elements


In the examples thus far, the result sets generated by our queries have contained col-
umns from one or more tables. While most elements in your SELECT clauses will
typically be simple column references, a SELECT clause may also include:
• Literal values, such as numbers (1) or strings ('abc')
• Expressions, such as shape.diameter * 3.1415927
• Functions, such as TO_DATE('01-JAN-2002','DD-MON-YYYY')
• Pseudocolumns, such as ROWID, ROWNUM, or LEVEL

DML Statements | 7

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 8 Wednesday, March 27, 2002 2:18 PM

While the first three items in this list are fairly straightforward, the last item merits
further discussion. Oracle makes available several phantom columns, known as
pseudocolumns, that do not exist in any tables. Rather, they are values visible during
query execution that can be helpful in certain situations.
For example, the pseudocolumn ROWID represents the physical location of a row.
This information represents the fastest possible access mechanism. It can be useful if
you plan to delete or update a row retrieved via a query. However, you should never
store ROWID values in the database, nor should you reference them outside of the
transaction in which they are retrieved, since a row’s ROWID can change in certain
situations, and ROWIDs can be reused after a row has been deleted.
The next example demonstrates each of the different elements from the previous list:
SELECT rownum,
cust_nbr,
1 multiplier,
'cust # ' || cust_nbr cust_nbr_str,
'hello' greeting,
TO_CHAR(last_order_dt, 'DD-MON-YYYY') last_order
FROM customer;

ROWNUM CUST_NBR MULTIPLIER CUST_NBR_STR GREETING LAST_ORDER


------ -------- ---------- ------------ -------- -----------
1 1 1 cust # 1 hello 15-JUN-2000
2 2 1 cust # 2 hello 27-JUN-2000
3 3 1 cust # 3 hello 07-JUL-2000
4 4 1 cust # 4 hello 15-JUL-2000
5 5 1 cust # 5 hello 01-JUN-2000
6 6 1 cust # 6 hello 10-JUN-2000
7 7 1 cust # 7 hello 17-JUN-2000
8 8 1 cust # 8 hello 22-JUN-2000
9 9 1 cust # 9 hello 25-JUN-2000
10 10 1 cust # 10 hello 01-JUN-2000
11 11 1 cust # 11 hello 05-JUN-2000
12 12 1 cust # 12 hello 07-JUN-2000
13 13 1 cust # 13 hello 07-JUN-2000
14 14 1 cust # 14 hello 05-JUN-2000
15 15 1 cust # 15 hello 01-JUN-2000
16 16 1 cust # 16 hello 31-MAY-2000
17 17 1 cust # 17 hello 28-MAY-2000
18 18 1 cust # 18 hello 23-MAY-2000
19 19 1 cust # 19 hello 16-MAY-2000
20 20 1 cust # 20 hello 01-JUN-2000
21 21 1 cust # 21 hello 26-MAY-2000
22 22 1 cust # 22 hello 18-MAY-2000
23 23 1 cust # 23 hello 08-MAY-2000
24 24 1 cust # 24 hello 26-APR-2000
25 25 1 cust # 25 hello 01-JUN-2000
26 26 1 cust # 26 hello 21-MAY-2000
27 27 1 cust # 27 hello 08-MAY-2000
28 28 1 cust # 28 hello 23-APR-2000
29 29 1 cust # 29 hello 06-APR-2000
30 30 1 cust # 30 hello 01-JUN-2000

8 | Chapter 1: Introduction to SQL

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 9 Wednesday, March 27, 2002 2:18 PM

Interestingly, your SELECT clause is not required to reference columns from any of
the tables in the FROM clause. For example, the next query’s result set is composed
entirely of literals:
SELECT 1 num, 'abc' str
FROM customer;

NUM STR
---------- ---
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc
1 abc

Since there are 30 rows in the customer table, the query’s result set includes 30 iden-
tical rows of data.

Ordering your results


In general, there is no guarantee that the result set generated by your query will be in
any particular order. If you want your results to be sorted by one or more columns,
you can add an ORDER BY clause after the WHERE clause. The following example
sorts the results from our New England query by customer name:
SELECT c.cust_nbr, c.name, r.name
FROM customer c, region r
WHERE r.name = 'New England'

DML Statements | 9

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 10 Wednesday, March 27, 2002 2:18 PM

AND r.region_id = c.region_id


ORDER BY c.name;

CUST_NBR NAME NAME


-------- ------------------------------ -----------
1 Cooper Industries New England
3 Ditech Corp. New England
2 Emblazon Corp. New England
4 Flowtech Inc. New England
5 Gentech Industries New England

You may also designate the sort column(s) by their position in the SELECT clause.
To sort the previous query by customer number, which is the first column in the
SELECT clause, you could issue the following statement:
SELECT c.cust_nbr, c.name, r.name
FROM customer c, region r
WHERE r.name = 'New England'
AND r.region_id = c.region_id
ORDER BY 1;

CUST_NBR NAME NAME


---------- ------------------------------ -----------
1 Cooper Industries New England
2 Emblazon Corp. New England
3 Ditech Corp. New England
4 Flowtech Inc. New England
5 Gentech Industries New England

Specifying sort keys by position will certainly save you some typing, but it can often
lead to errors if you later change the order of the columns in your SELECT clause.

Removing duplicates
In some cases, your result set may contain duplicate data. For example, if you are
compiling a list of parts that were included in last month’s orders, the same part
number would appear multiple times if more than one order included that part. If
you want duplicates removed from your result set, you can include the DISTINCT
keyword in your SELECT clause, as in:
SELECT DISTINCT li.part_nbr
FROM cust_order co, line_item li
WHERE co.order_dt >= TO_DATE('01-JUL-2001','DD-MON-YYYY')
AND co.order_dt < TO_DATE('01-AUG-2001','DD-MON-YYYY')
AND co.order_nbr = li.order_nbr;

This query returns the distinct set of parts ordered during July of 2001. Without the
DISTINCT keyword, the result set would contain one row for every line-item of
every order, and the same part would appear multiple times if it was included in mul-
tiple orders. When deciding whether to include DISTINCT in your SELECT clause,
keep in mind that finding and removing duplicates necessitates a sort operation,
which can add quite a bit of overhead to your query.

10 | Chapter 1: Introduction to SQL

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 11 Wednesday, March 27, 2002 2:18 PM

The INSERT Statement


The INSERT statement is the mechanism for loading data into your database. Data
can be inserted into only one table at a time, although the data being loaded into the
table can be pulled from one or more additional tables. When inserting data into a
table, you do not need to provide values for every column in the table; however, you
need to be aware of the columns that require non-NULL* values and the ones that do
not. Let’s look at the definition of the employee table:
describe employee

Name Null? Type


----------------------------------------- -------- ------------
EMP_ID NOT NULL NUMBER(5)
FNAME VARCHAR2(20)
LNAME NOT NULL VARCHAR2(20)
DEPT_ID NOT NULL NUMBER(5)
MANAGER_EMP_ID NUMBER(5)
SALARY NUMBER(5)
HIRE_DATE DATE
JOB_ID NUMBER(3)

The NOT NULL designation for the emp_id, lname, and dept_id columns indicates
that values are required for these three columns. Therefore, we must be sure to pro-
vide values for at least these three columns in our INSERT statements, as demon-
strated by the following:
INSERT INTO employee (emp_id, lname, dept_id)
VALUES (101, 'Smith', 2);

The VALUES clause must contain the same number of elements as the column list, and
the data types must match the column definitions. In the example, emp_id and dept_id
hold numeric values while lname holds character data, so our INSERT statement will
execute without error. Oracle always tries to convert data from one type to another
automatically, however, so the following statement will also run without errors:
INSERT INTO employee (emp_id, lname, dept_id)
VALUES ('101', 'Smith', '2');

Sometimes, the data to be inserted needs to be retrieved from one or more tables.
Since the SELECT statement generates a result set consisting of rows and columns of
data, you can feed the result set from a SELECT statement directly into an INSERT
statement, as in:
INSERT INTO employee (emp_id, fname, lname, dept_id, hire_date)
SELECT 101, 'Dave', 'Smith', d.dept_id, SYSDATE
FROM department d
WHERE d.name = 'Accounting';

* NULL indicates the absence of a value. The use of NULL will be studied in Chapter 2.

DML Statements | 11

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 12 Wednesday, March 27, 2002 2:18 PM

In this example, the purpose of the SELECT statement is to retrieve the department
ID for the Accounting department. The other four columns in the SELECT clause are
supplied as literals.

The DELETE Statement


The DELETE statement facilitates the removal of data from the database. Like the
SELECT statement, the DELETE statement contains a WHERE clause that specifies
the conditions used to identify rows to be deleted. If you neglect to add a WHERE
clause to your DELETE statement, all rows will be deleted from the target table. The
following statement will delete all employees with the last name of Hooper from the
employee table:
DELETE FROM employee
WHERE lname = 'Hooper';

In some cases, the values needed for one or more of the conditions in your WHERE
clause exist in another table. For example, your company may decide to outsource its
accounting functions, thereby necessitating the removal of all Accounting personnel
from the employee table:
DELETE FROM employee
WHERE dept_id =
(SELECT dept_id
FROM department
WHERE name = 'Accounting');

The use of the SELECT statement in this example is known as a subquery and will be
studied in detail in Chapter 5.

The UPDATE Statement


Modifications to existing data are handled by the UPDATE statement. Like the
DELETE statement, the UPDATE statement includes a WHERE clause in order to
specify which rows should be targeted. The following example shows how you might
give a 10% raise to everyone making less than $40,000:
UPDATE employee
SET salary = salary * 1.1
WHERE salary < 40000;

If you want to modify more than one column in the table, you have two choices: pro-
vide a set of column/value pairs separated by commas, or provide a set of columns
and a subquery. The following two UPDATE statements modify the inactive_dt and
inactive_ind columns in the customer table for any customer who hasn’t placed an
order in the past year:
UPDATE customer
SET inactive_dt = SYSDATE, inactive_ind = 'Y'
WHERE last_order_dt < SYSDATE — 365;

12 | Chapter 1: Introduction to SQL

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch01.8459 Page 13 Wednesday, March 27, 2002 2:18 PM

UPDATE customer
SET (inactive_dt, inactive_ind) =
(SELECT SYSDATE, 'Y' FROM dual)
WHERE last_order_dt < SYSDATE — 365;

The subquery in the second example is a bit forced, since it uses a query against the
dual* table to build a result set containing two literals, but it should give you an idea
of how you would use a subquery in an UPDATE statement. In later chapters, you
will see far more interesting uses for subqueries.

So Why Are There 13 More Chapters?


After reading this chapter, you might think that SQL looks pretty simple (at least the
DML portion). At a high level, it is fairly simple, and you now know enough about
the language to go write some code. However, you will learn over time that there are
numerous ways to arrive at the same end point, and some are more efficient and ele-
gant than others. The true test of SQL mastery is when you no longer have the desire
to return to what you were working on the previous year, rip out all the SQL, and
recode it. For one of us, it took about nine years to reach that point. Hopefully, this
book will help you reach that point in far less time.
While you are reading the rest of the book, you might notice that the majority of
examples use SELECT statements, with the remainder somewhat evenly distributed
across INSERT, UPDATE, and DELETE statements. This disparity is not indicative
of the relative importance of SELECT statements over the other three DML state-
ments; rather, SELECT statements are favored because we can show the query’s
result set, which should help you to better understand the query, and because many
of the points being made using SELECT statements can be applied to UPDATE and
DELETE statements as well.

* Dual is an Oracle-provided table containing exactly one row with one column. It comes in handy when you
need to construct a query that returns exactly one row.

DML Statements | 13

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 14 Wednesday, March 27, 2002 2:18 PM

Chapter
CHAPTER 2 2

The WHERE Clause

Whether we are querying, modifying, or deleting data, the WHERE clause is the
mechanism for identifying the sets of data we want to work with. In this chapter, we
explore the role of the WHERE clause in SQL statements, as well as the various
options available when building a WHERE clause.

Life Without WHERE


Before we delve into the WHERE clause, let’s imagine life without it. Say that you
are interested in doing some maintenance on the data in the part table. In order to
inspect the data in the table, you issue the following query:
SELECT part_nbr, name, supplier_id, status, inventory_qty
FROM part;

If the part table contains 10,000 items, the result set returned by the query would
consist of 10,000 rows, each with 5 columns. You would then load the 10,000 rows
into memory and make your modifications.
Once you have made the required modifications to your data in memory, it is time to
apply the changes to the part table. Without the ability to specify the rows to modify,
you have no choice but to delete all rows in the table and re-insert all 10,000 rows:
DELETE FROM part;

INSERT INTO part (part_nbr, name, supplier_id, status, inventory_qty)


VALUES ('XY5-1002', 'Wonder Widget', 1, 'IN-STOCK', 1);

/* 9,999 more INSERTs on the wall, 9,999 more INSERTS... */

While this approach works in theory, it wreaks havoc on performance, concurrency


(the ability for more than one user to modify data simultaneously), and scalability.
Now imagine that you want to modify data in the part table only for those parts sup-
plied by Acme Industries. Since the supplier’s name is stored in the supplier table,
you must include both the part and supplier tables in the FROM clause:

14

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 15 Wednesday, March 27, 2002 2:18 PM

SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,


s.supplier_id, s.name
FROM part p, supplier s;

If 100 companies supply the 10,000 parts in the part table, this query will return
1,000,000 rows. Known as the Cartesian product, this number equates to every possi-
ble combination of all rows from the two tables. As you sift through the million
rows, you would keep only those where the values of p.supplier_id and s.supplier_id
are identical and where the s.name column matches 'Acme Industries'. If Acme
Industries supplies only 50 of the 10,000 parts in your database, you will end up dis-
carding 999,950 of the 1,000,000 rows returned by your query.

WHERE to the Rescue


Hopefully, these scenarios give you some insight into the utility of the WHERE
clause, including the ability to:
1. Filter out unwanted data from a query’s result set.
2. Isolate one or more rows of a table for modification.
3. Conditionally join two or more data sets together.
To see how these things are accomplished, let’s add a WHERE clause to the previ-
ous SELECT statement, which strives to locate all parts supplied by Acme Industries:
SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,
s.supplier_id, s.name
FROM part p, supplier s
WHERE s.supplier_id = p.supplier_id
AND s.name = 'Acme Industries';

The WHERE clause here is comprised of two parts, known as conditions, which are
evaluated separately. Conditions always evaluate to either TRUE or FALSE; if there
are multiple conditions in a WHERE clause, they all must evaluate to TRUE in order
for a given row to be included in the result set.* For this example, a row created by
combining data from the part and supplier tables will only be included in the final
result set if both tables share a common value for the supplier_id column, and if the
value of the name column in the supplier tables matches 'Acme Industries'.† Any other
permutation of data from the two tables would evaluate to FALSE and be discarded.
With the addition of the WHERE clause to the previous example, therefore, Oracle
will take on the work of discarding undesired rows from the result set, and only 50

* This is an oversimplification. As you will see later, using the OR and NOT operators allows the WHERE
clause to evaluate to TRUE even if individual conditions evaluate to FALSE.
† Another oversimplification. The Oracle optimizer (the component tasked with finding the most efficient way
to execute a query) doesn’t first create every possible combination of rows from every table or view in the
FROM clause before it begins evaluating conditions. Rather, the optimizer chooses the order in which to
evaluate conditions and join data sets so execution time is (hopefully) minimized.

WHERE to the Rescue | 15

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 16 Wednesday, March 27, 2002 2:18 PM

rows will be returned by the query, rather than 1,000,000. Now that you have
retrieved the 50 rows of interest from the database, you can begin the process of
modifying the data. Keep in mind, however, that with the WHERE clause at your
disposal you will no longer need to delete and re-insert your modified data; instead,
you can use the UPDATE statement to modify specific rows based on the part_nbr
column, which is the unique identifier for the table:
UPDATE part
SET status = 'DISCONTINUED'
WHERE part_nbr = 'AI5-4557';

While this is certainly an improvement, we can do even better. If your intent is to


modify the status for all 50 parts supplied by Acme Industries, there is no need to
execute a query at all. Simply execute a single UPDATE statement that finds and
modifies all 50 records:
UPDATE part
SET status = 'DISCONTINUED'
WHERE supplier_id =
(SELECT supplier_id
FROM supplier
WHERE name = 'Acme Industries');

The WHERE clause in this statement consists of a single condition that equates the
supplier_id column to the value returned by a query against the supplier table. A
query wrapped in parentheses inside another SQL statement is known as a subquery;
subqueries will be studied extensively in Chapter 5, so don’t worry if this looks a bit
intimidating. The net result is that the condition will be rewritten to use the value
returned by the subquery, as in:
UPDATE part
SET status = 'DISCONTINUED'
WHERE supplier_id = 1;

When executed, the condition evaluates to TRUE for exactly 50 of the 10,000 rows
in the part table, and the status of those 50 rows changes to DISCONTINUED.

WHERE Clause Evaluation


Now that we have seen the WHERE clause in action, let’s take a look at how it is eval-
uated. As we mentioned, the WHERE clause consists of one or more conditions that
evaluate independently to TRUE or FALSE. If your WHERE clause consists of multi-
ple conditions, the conditions are separated by the logical operators AND and OR.
Depending on the outcome of the individual conditions and the placement of these
logical operators, Oracle will assign a final value of TRUE or FALSE to each candi-
date row, thereby determining whether a row will be included in the final result set.
Let’s look at the 'Acme Industries' query again:
SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,
s.supplier_id, s.name

16 | Chapter 2: The WHERE Clause

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 17 Wednesday, March 27, 2002 2:18 PM

FROM part p, supplier s


WHERE s.supplier_id = p.supplier_id
AND s.name = 'Acme Industries';

The WHERE clause consists of two conditions separated by AND. Thus, a row will
only be included if both conditions evaluate to TRUE. Table 2-1 shows the possible
scenarios when conditions are replaced by their possible outcomes.

Table 2-1. Multiple-condition evaluation using AND

Intermediate result Final result


WHERE TRUE AND TRUE TRUE
WHERE FALSE AND FALSE FALSE
WHERE FALSE AND TRUE FALSE
WHERE TRUE AND FALSE FALSE

Using basic logic rules, we can see that the only combination of outcomes that
results in a final value of TRUE being assigned to a candidate row is where both con-
ditions evaluate to TRUE. Table 2-2 demonstrates the possible outcomes if our con-
ditions had been separated by OR rather then AND.

Table 2-2. Multiple-condition evaluation using OR

Intermediate result Final result


WHERE TRUE OR TRUE TRUE
WHERE FALSE OR FALSE FALSE
WHERE FALSE OR TRUE TRUE
WHERE TRUE OR FALSE TRUE

Next, let’s spice our query up a bit by including parts supplied by either Acme Indus-
tries or Tilton Enterprises:
SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,
s.supplier_id, s.name
FROM part p, supplier s
WHERE s.supplier_id = p.supplier_id
AND (s.name = 'Acme Industries'
OR s.name = 'Tilton Enterprises');

We now have three separate conditions separated by AND and OR with parentheses
surrounding two of the conditions. Table 2-3 illustrates the possible outcomes.

Table 2-3. Multiple-condition evaluation using AND and OR

Intermediate result Final result


WHERE TRUE AND (TRUE OR FALSE) TRUE
WHERE TRUE AND (FALSE OR TRUE) TRUE
WHERE TRUE AND (FALSE OR FALSE) FALSE

WHERE Clause Evaluation | 17

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 18 Wednesday, March 27, 2002 2:18 PM

Table 2-3. Multiple-condition evaluation using AND and OR (continued)

Intermediate result Final result


WHERE FALSE AND (TRUE OR FALSE) FALSE
WHERE FALSE AND (FALSE OR TRUE) FALSE
WHERE FALSE AND (FALSE OR FALSE) FALSE

Since a particular part cannot be supplied by both Acme Industries and Tilton Enter-
prises, the intermediate results TRUE AND (TRUE AND TRUE) and FALSE AND
(TRUE AND TRUE) were not included in Table 2-3.
To liven things up even more, we can also throw in the NOT operator. The follow-
ing query returns data for parts supplied by anyone other than Acme Industries or
Tilton Enterprises:
SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,
s.supplier_id, s.name
FROM part p, supplier s
WHERE s.supplier_id = p.supplier_id
AND NOT (s.name = 'Acme Industries'
OR s.name = 'Tilton Enterprises');

Table 2-4 demonstrates how the addition of the NOT operator changes the outcome.

Table 2-4. Multiple-condition evaluation using AND, OR, and NOT

Intermediate result Final result


WHERE TRUE AND NOT (TRUE OR FALSE) FALSE
WHERE TRUE AND NOT (FALSE OR TRUE) FALSE
WHERE TRUE AND NOT (FALSE OR FALSE) TRUE
WHERE FALSE AND NOT (TRUE OR FALSE) FALSE
WHERE FALSE AND NOT (FALSE OR TRUE) FALSE
WHERE FALSE AND NOT (FALSE OR FALSE) FALSE

The use of the NOT operator in the previous example is a bit forced; we will see
more natural ways of expressing the same logic in later examples.

Conditions and Expressions


Now that we understand how conditions are grouped together and evaluated, let’s
look at the different elements that make up a condition. A condition is comprised of
one or more expressions along with one or more operators. Examples of expressions
include:
• Numbers
• Columns, such as s.supplier_id

18 | Chapter 2: The WHERE Clause

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 19 Wednesday, March 27, 2002 2:18 PM

• Literals, such as 'Acme Industries'


• Functions, such as UPPER('abcd')
• Lists of simple expressions, such as (1, 2, 3)
• Subqueries
Examples of operators include:
• Arithmetic operators, such as +, -, *, and /
• Comparison operators, such as =, <, >=, !=, LIKE, and IN
The following sections explore many of the common condition types that use differ-
ent combinations of the above expression and operator types.

Equality/Inequality Conditions
Most of the conditions that we use when constructing a WHERE clause will be
equality conditions used to join data sets together or to isolate specific values. We
have already encountered these types of conditions numerous times in previous
examples, including:
s.supplier_id = p.supplier_id

s.name = 'Acme Industries'

supplier_id = (SELECT supplier_id


FROM supplier
WHERE name = 'Acme Industries')

In all three cases, we have a column expression followed by a comparison operator


(=) followed by another expression. The conditions differ in the type of expression
on the right side of the comparison operator. The first example compares one col-
umn to another, the second example compares a column to a literal, and the third
example compares a column to the value returned by a subquery.
We can also build conditions that use the inequality comparison operator “!=”. In a
previous example, we used the NOT operator to find information about parts sup-
plied by every supplier other than Acme Industries and Tilton Enterprises. Using the
!= operator rather than using NOT makes the query easier to understand and
removes the need for the OR operator:
SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,
s.supplier_id, s.name
FROM part p, supplier s
WHERE s.supplier_id = p.supplier_id
AND s.name != 'Acme Industries'
AND s.name != 'Tilton Enterprises';

While this is an improvement over the previous version, the next section shows an
even cleaner way to represent the same logic.

Conditions and Expressions | 19

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 20 Wednesday, March 27, 2002 2:18 PM

Membership Conditions
Along with determining whether two expressions are identical, it is often useful to
determine whether one expression can be found within a set of expressions. Using
the IN operator, you can build conditions that will evaluate to TRUE if a given
expression exists in a set of expressions:
s.name IN ('Acme Industries', 'Tilton Enterprises')

You may also add the NOT operator to determine whether an expression does not
exist in a set of expressions:
s.name NOT IN ('Acme Industries', 'Tilton Enterprises')

Most people prefer to use a single condition with IN or NOT IN instead of writing
multiple conditions using = or !=, so we will take one last stab at our Acme/Tilton
query:
SELECT p.part_nbr, p.name, p.supplier_id, p.status, p.inventory_qty,
s.supplier_id, s.name
FROM part p, supplier s
WHERE s.supplier_id = p.supplier_id
AND s.name NOT IN ('Acme Industries', 'Tilton Enterprises');

Along with prefabricated sets of expressions, subqueries may be employed to gener-


ate sets on the fly. If a subquery returns exactly one row, you may use a comparison
operator; if a subquery returns more than one row, or if you’re not sure whether the
subquery might return more than one row, use the IN operator. The following exam-
ple updates all orders that contain parts supplied by Eastern Importers:
UPDATE cust_order
SET sale_price = sale_price *1.1
WHERE cancelled_dt IS NULL
AND ship_dt IS NULL
AND order_nbr IN
(SELECT li.order_nbr
FROM line_item li,part p, supplier s
WHERE s.name = 'Eastern Importers'
AND s.supplier_id = p.supplier_id
AND p.part_nbr = li.part_nbr);

The subquery evaluates to a (potentially empty) set of order numbers. All orders
whose order number exists in that set are then modified by the UPDATE statement.

Range Conditions
If you are dealing with dates or numeric data, you may be interested in whether a value
falls within a specified range rather than whether it matches a specific value or exists in
a finite set. For such cases, you may use the BETWEEN…AND operator, as in:
DELETE FROM cust_order
WHERE order_dt BETWEEN '01-JUL-2001' AND '31-JUL-2001';

20 | Chapter 2: The WHERE Clause

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 21 Wednesday, March 27, 2002 2:18 PM

To determine whether a value lies outside a specific range, you can add the NOT
operator:
SELECT order_nbr, cust_nbr, sale_price
FROM cust_order
WHERE sale_price NOT BETWEEN 1000 AND 10000;

When using BETWEEN, make sure the first value is the lowest of the two values
provided. While “BETWEEN 1 AND 10” and “BETWEEN 10 AND 1” might seem
logically equivalent, specifying the higher value first guarantees that your condition
will always evaluate to FALSE.
Ranges may also be specified using the operators <, >, <=, and >=, although doing
so requires writing two conditions rather than one. The previous query could also be
expressed as:
SELECT order_nbr, cust_nbr, sale_price
FROM cust_order
WHERE sale_price < 1000 OR sale_price > 10000;

Matching Conditions
When dealing with character data, there are some situations where you are looking
for an exact string match, and others where a partial match is sufficient. For the lat-
ter case, you can use the LIKE operator along with one or more pattern-matching
characters, as in:
DELETE FROM part
WHERE part_nbr LIKE 'ABC%';

The pattern-matching character “%” matches strings of any length, so all of the fol-
lowing part numbers would be deleted: 'ABC', 'ABC-123', 'ABC9999999'. If you need
finer control, you can use the underscore (_) pattern-matching character to match
single characters, as in:
DELETE FROM part
WHERE part_nbr LIKE '_B_';

For this pattern, any part number with exactly 3 characters with a B in the middle
would be deleted. Both pattern-matching characters may be utilized in numerous
combinations to find the desired data. Additionally, the NOT operator may be
employed to find strings that don’t match a specified pattern. The following exam-
ple deletes all parts whose name does not contain a Z in the third position followed
later by the string “T1J”:
DELETE FROM part
WHERE part_nbr NOT LIKE '_ _Z%T1J%';

Oracle provides a slew of built-in functions for handling character data that can be
used to build matching conditions. For example, the condition part_nbr LIKE 'ABC%'
could be rewritten using the SUBSTR function as SUBSTR(part_nbr, 1, 3) = 'ABC'. For

Conditions and Expressions | 21

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 22 Wednesday, March 27, 2002 2:18 PM

definitions and examples for all of Oracle’s built-in functions, see Oracle SQL: The
Essential Reference (O’Reilly).

Handling NULL
The NULL expression represents the absence of a value. If, when entering an order
into the database, you are uncertain when the order will be shipped, it is better to
leave the ship date undefined than to fabricate a value. Until the ship date has been
determined, therefore, it is best to leave the ship_dt column NULL. NULL is also
useful for cases where data is not applicable. For example, a cancelled order’s ship-
ping date is no longer applicable and should be set to NULL.
When working with NULL, the concept of equality does not apply; a column may be
NULL, but it will never equal NULL. Therefore, you will need to use the special
operator IS when looking for NULL data, as in:
UPDATE cust_order
SET expected_ship_dt = SYSDATE + 1
WHERE ship_dt IS NULL;

In this example, all orders whose shipping date hasn’t been specified will have their
expected shipping date bumped forward by one day.
You may also use the NOT operator to locate non-NULL data:
UPDATE cust_order
SET expected_ship_dt = NULL
WHERE ship_dt IS NOT NULL;

This example sets the expected shipping date to NULL for all orders that have
already shipped. Notice that the SET clause uses the equality operator (=) with
NULL, whereas the WHERE clause uses the IS and NOT operators. The equality
operator is used to set a column to NULL, whereas the IS operator is used to evalu-
ate whether a column is NULL. A great many mistakes might have been avoided had
the designers of SQL chosen a special operator to be utilized when setting a column
to NULL (i.e., SET expected_ship_dt TO NULL), but this is not the case. To make
matters worse, Oracle doesn’t complain if you mistakenly use the equality operator
when evaluating for NULL. The following query will parse and execute but will
never return rows:
SELECT order_nbr, cust_nbr, sale_price, order_dt
FROM cust_order
WHERE ship_dt = NULL;

Hopefully, you would quickly recognize that the previous query never returns data
and replace the equality operator with IS. However, there is a more subtle mistake
involving NULL that is harder to spot. Say you are looking for all employees who are
not managed by Jeff Blake, whose employee ID is 11. Your first instinct may be to
run the following query:

22 | Chapter 2: The WHERE Clause

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 23 Wednesday, March 27, 2002 2:18 PM

SELECT fname, lname, manager_emp_id


FROM employee
WHERE manager_emp_id != 11;

FNAME LNAME MANAGER_EMP_ID


-------------------- -------------------- --------------
Alex Fox 28
Chris Anderson 28
Lynn Nichols 28
Eric Iverson 28
Laura Peters 28
Mark Russell 28

While this query returns rows, it leaves out those employees who are top-level man-
agers and, thus, are not managed by anyone. Since NULL is neither equal to 11 nor
not equal to 11, this set of employees is absent from the result set. In order to ensure
that all employees are considered, you will need to explicitly handle NULL, as in:
SELECT fname, lname, manager_emp_id
FROM employee
WHERE manager_emp_id IS NULL OR manager_emp_id != 11;

FNAME LNAME MANAGER_EMP_ID


-------------------- -------------------- --------------
Bob Brown
John Smith
Jeff Blake
Alex Fox 28
Chris Anderson 28
Lynn Nichols 28
Eric Iverson 28
Laura Peters 28
Mark Russell 28

Including two conditions for every nullable column in your WHERE clause can get a
bit tiresome. Instead, you can use Oracle’s built-in function NVL, which substitutes
a specified value for columns that are NULL, as in:
SELECT fname, lname, manager_emp_id
FROM employee
WHERE NVL(manager_emp_id, -999) != 11;

FNAME LNAME MANAGER_EMP_ID


-------------------- -------------------- --------------
Bob Brown
John Smith
Jeff Blake
Alex Fox 28
Chris Anderson 28
Lynn Nichols 28
Eric Iverson 28
Laura Peters 28
Mark Russell 28

Conditions and Expressions | 23

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 24 Wednesday, March 27, 2002 2:18 PM

In this example, the value -999 is substituted for all NULL values, which, since -999
is never equal to 11, guarantees that all rows whose manager_emp_id column is
NULL will be included in the result set. Thus, all employees whose manager_emp_id
column is NULL or is not NULL and has a value other than 11 will be retrieved by
the query.

WHERE to Go from Here


This chapter has introduced the role of the WHERE clause in different types of SQL
statements as well as the various components used to build a WHERE clause.
Because the WHERE clause plays such an important role in many SQL statements,
however, the topic is far from exhausted. Additional coverage of WHERE clause top-
ics may be found in:
• Chapter 3, in which various flavors of join conditions are studied in detail
• Chapter 5, which probes the different types of subqueries along with the appro-
priate operators for evaluating their results
• Chapter 6, in which various methods of handling date/time data are explored
• Chapter 14, which explores certain aspects of the WHERE clause from the
standpoint of performance and efficiency
Additionally, here are a few tips to help you make the most of your WHERE clauses:
1. Check your join conditions carefully. Make sure that each data set in the FROM
clause is properly joined. Keep in mind that some joins require multiple condi-
tions. See Chapter 3 for more information.
2. Avoid unnecessary joins. Just because two data sets in your FROM clause con-
tain the same column does not necessitate a join condition be added to your
WHERE clause. In some designs, redundant data has been propagated to multi-
ple tables through a process called denormalization. Take the time to under-
stand the database design, and ask your DBA or database designer for a current
data model.
3. Use parentheses. Oracle maintains both operator precedence and condition pre-
cedence, meaning there are clearly defined rules for the order in which things
will be evaluated, but the safest route for you and for those who will later main-
tain your code is to dictate evaluation order using parentheses. For operators,
specifying (5 * p.inventory_qty) + 2 rather than 5 * p.inventory_qty + 2 makes
the order in which the operations should be performed clear. For conditions, use
parentheses any time the OR operator is employed.
4. Use consistent indentation. For example, if the previous line contains a left
parenthesis without a matching right parenthesis, indent the current line to
show that it is a continuation of the previous line.

24 | Chapter 2: The WHERE Clause

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch02.8613 Page 25 Wednesday, March 27, 2002 2:18 PM

5. When using OR, put the condition requiring the least effort to evaluate first. If
the first condition evaluates to TRUE, Oracle won’t bother evaluating the
remaining OR’d conditions, possibly saving significant execution time. This
strategy is useful with correlated subqueries, which are generally executed once
per candidate row.
6. Handle NULLs properly. After writing your WHERE clause, inspect each condi-
tion with respect to its ability to properly handle NULL values. Take the time to
understand the table definitions in your database so that you know which col-
umns allow NULLs.
7. Pick up introductory books on logic and set theory at your local library. While
understanding these two topics won’t necessarily get you invited to more cock-
tail parties, it will certainly make you a better SQL programmer.

WHERE to Go from Here | 25

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch03.8749 Page 26 Wednesday, March 27, 2002 2:19 PM

Chapter
CHAPTER 3 3

Joins

Most of the things in life are not self-contained. There is not one shop where you will
find all your requirements. This is valid for database tables as well. Quite often, you
need information from more than one table. The SQL construct that combines data
from two or more tables is called a join. This chapter takes you into the details of
joins, their types, and their usage.
A join is a SQL query that extracts information from two or more tables or views.
When you specify multiple tables or views in the FROM clause of a query, Oracle
performs a join, linking rows from multiple tables together. There are several types of
joins to be aware of:
Inner joins
Inner joins are the regular joins. An inner join returns the rows that satisfy the
join condition. Each row returned by an inner join contains data from all tables
involved in the join.
Outer joins
Outer joins are an extension to the inner joins. An outer join returns the rows
that satisfy the join condition and also the rows from one table for which no cor-
responding rows (i.e., that satisfy the join condition) exist in the other table.
Self joins
A self join is a join of a table to itself.
The following sections discuss each of these joins with examples.

Inner Joins
An inner join returns the rows that satisfy the join condition. Let’s take an example
to understand the concept of a join. Say you want to list the name and department
name for each employee. To do this, you would use the following SQL statement:
SELECT E.LNAME, D.NAME
FROM EMPLOYEE E, DEPARTMENT D

26

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch03.8749 Page 27 Wednesday, March 27, 2002 2:19 PM

WHERE E.DEPT_ID = D.DEPT_ID;

LNAME NAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING

14 rows selected.

This example queries two tables, because the employee name is stored in the
EMPLOYEE table, whereas the department name is stored in the DEPARTMENT
table. Notice that the FROM clause lists two tables EMPLOYEE and DEPART-
MENT, separated by a comma (,). If you need to join three or more tables, you have
to specify all the tables in the FROM clause separated by commas. The SELECT list
may include columns from any of the tables specified in the FROM clause.
Note the use of table aliases in this query. It is common practice to use table aliases
while selecting data from multiple tables. Whenever there is an ambiguity in the col-
umn names, you must use a table alias (or the table name) to qualify any ambiguous
column names. For example, the column name DEPT_ID appears in both the tables.
Therefore, the table aliases E and D are used in the WHERE clause to ask Oracle to
equate DEPT_ID column from EMPLOYEE table with the DEPT_ID column from
the DEPARTMENT table. Note that the table aliases have been used with the col-
umns in the SELECT clause as well, even though the column names are unambigu-
ous. It is good practice to use table aliases everywhere in a query if you are using
them at all.

Cartesian Product
If you don’t specify the join condition while joining two tables, Oracle combines each
row from the first table with each row of the second table. This type of result set is
called as a Cartesian product. The number of rows in a Cartesian product is the prod-
uct of the number of rows in each table. Here’s an example of a Cartesian product:
SELECT E.LNAME, D.NAME
FROM EMPLOYEE E, DEPARTMENT D;

Inner Joins | 27

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch03.8749 Page 28 Wednesday, March 27, 2002 2:19 PM

LNAME NAME
---------- --------------
SMITH ACCOUNTING
ALLEN ACCOUNTING
WARD ACCOUNTING
JONES ACCOUNTING
MARTIN ACCOUNTING
BLAKE ACCOUNTING
...
...
...
SCOTT OPERATIONS
KING OPERATIONS
TURNER OPERATIONS
ADAMS OPERATIONS
JAMES OPERATIONS
FORD OPERATIONS
MILLER OPERATIONS

56 rows selected.

Note that since the query didn’t specify a join condition, each row from the
EMPLOYEE table is combined with each row from the DEPARTMENT table. Need-
less to say, this result set is of little use. More often than not a Cartesian product pro-
duces a result set containing misleading rows. Therefore, unless you are sure that
you want a Cartesian product, don’t forget to include the join condition when you
specify more than one table in the FROM clause.

Join Condition
Usually when you perform a join, you specify a condition in the WHERE clause that
relates the tables specified in the FROM clause. This condition is referred to as the
join condition. The join condition specifies how the rows from one table will be com-
bined with the rows of another table. Usually, the join condition is applied to the for-
eign key columns. In the first example in the previous section, the WHERE clause
specifies the join condition by which the DEPT_ID column of the EMPLOYEE table
is equated with the DEPT_ID column of the DEPARTMENT table:
WHERE E.DEPT_ID = D.DEPT_ID

To perform the join, Oracle picks up one combination of rows from the two tables,
and checks to see whether the join condition is true. If the join condition is true,
Oracle includes this combination of rows in the result set. The process is repeated for
all combinations of rows from the two tables. Some of the things that you should
know about the join condition are discussed in the following list.
• The columns specified in the join condition need not be specified in the SELECT
list. In the following example, the join condition involves the DEPT_ID column
from the EMPLOYEE and DEPARTMENT tables; however, the DEPT_ID col-
umn is not selected:

28 | Chapter 3: Joins

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch03.8749 Page 29 Wednesday, March 27, 2002 2:19 PM

SELECT E.LNAME, D.NAME


FROM EMPLOYEE E, DEPARTMENT D
WHERE E.DEPT_ID = D.DEPT_ID;
• Usually the join condition is specified on the foreign key columns of one table
and the primary key or unique key columns of another table. However, you can
specify other columns as well. Each join condition involves columns that relate
two tables.
• A join condition may involve more than one column. This is usually the case
when a foreign key constraint consists of multiple columns.
• The total number of join conditions is always equal to the total number of tables
less one.
• A join condition must involve columns with compatible datatypes. Note that the
datatype of the columns involved in a join condition need to be compatible, not
the same. Oracle performs automatic datatype conversion between the join col-
umns, if required.
• It is not necessary that a join condition involve the equal to (=) operator. A join
condition may contain other operators as well. Joins involving other operators
are discussed later in this section.

Equi-Join Versus Non-Equi-Join


The join condition determines whether the join is an equi-join or a non-equi-join.
When a join condition relates two tables by equating the columns from the tables, it is
an equi-join. When a join condition relates two tables by an operator other than equal-
ity, it is a non-equi-join. A query may contain equi-joins as well as non-equi-joins.
Equi-joins are the most common join type. For example, if you want to list all the
parts supplied by all the suppliers, you can join the SUPPLIER table with the PART
table by equating the SUPPLIER_ID from one table to that of the other:
SELECT S.NAME SUPPLIER_NAME, P.NAME PART_NAME
FROM SUPPLIER S, PART P
WHERE S.SUPPLIER_ID = P.SUPPLIER_ID;

However, there are situations in which you need non-equi-joins to get the required
information. For example, if you want to list the INVENTORY_CLASS of each
PART, you need to execute the following query:
SELECT P.NAME PART_NAME, C.CLASS INV_CLASS
FROM PART P, INVENTORY_CLASS C
WHERE P.UNIT_COST BETWEEN C.LOW_COST AND C.HIGH_COST;

Note the use of the BETWEEN operator while relating the UNIT_COST column
from the PART table with the LOW_COST and HIGH_COST columns of the
INVENTORY_CLASS table.

Inner Joins | 29

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
,ch03.8749 Page 30 Wednesday, March 27, 2002 2:19 PM

Outer Joins
Sometimes while performing a join between two tables, you need to return all the
rows from one table even when there are no corresponding rows in the other table.
Consider the following two tables, SUPPLIER and PART:
SELECT * FROM SUPPLIER;

SUPPLIER_ID NAME
----------- ------------------------------
101 Pacific Disks, Inc.
102 Silicon Valley MicroChips
103 Blue River Electronics

SELECT * FROM PART;

PART_NBR NAME SUPPLIER_ID STATUS INVENTORY_QTY UNIT_COST RESUPPLY_DATE


-------- ------------------ ----------- ------ ------------- --------- -------------
HD211 20 GB Hard Disk 101 ACTIVE 5 2000 12-DEC-00
P3000 3000 MHz Processor 102 ACTIVE 12 600 03-NOV-00

If you want to list all the suppliers and all the parts supplied by them, it is natural to
use the following query:
SELECT S.SUPPLIER_ID, S.NAME SUPPLIER_NAME, P.PART_NBR, P.NAME PART_NAME
FROM SUPPLIER S, PART P
WHERE S.SUPPLIER_ID = P.SUPPLIER_ID;

SUPPLIER_ID SUPPLIER_NAME PART_NBR PART_NAME


----------- ------------------------------ ---------- -------------------
101 Pacific Disks, Inc. HD211 20 GB Hard Disk
102 Silicon Valley MicroChips P3000 3000 MHz Processor

Note that even though we have three suppliers, this query lists only two of them,
because the third supplier (Blue River Electronics) doesn’t currently supply any part.
When Oracle performs the join between SUPPLIER table and PART table, it matches
the SUPPLIER_ID from these two tables (as specified by the join condition). Since
SUPPLIER_ID 103 doesn’t have any corresponding record in the PART table, that
supplier is not included in the result set. This type of join is the most natural, and is
known as an inner join.

The concept of the inner join is easier to understand in terms of the


Cartesian product. While performing a join of SUPPLIER and PART
tables, a Cartesian product is first formed (conceptually, Oracle
doesn’t physically materialize this Cartesian product), and then the
conditions in the WHERE clause restrict the results to only those rows
where the SUPPLIER_ID values match.

However, we want to see all the suppliers even if they don’t supply any parts. Oracle
provides a special type of join to include rows from one table that don’t have matching

30 | Chapter 3: Joins

This is the Title of the Book, eMatter Edition


Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
Other documents randomly have
different content
d’une nouvelle machine qui me préoccupe. Elle me paraît
ingénieuse, et il est possible que je me décide à l’expérimenter.
Il parlait d’un ton naturel, mais savait parfaitement qu’elle n’était
pas dupe de sa tranquillité apparente. Il y avait entre eux une
affection appuyée sur une confiance sans bornes et une admiration
mutuelle, affection profonde, quoique peu démonstrative. Mais ils
étaient identifiés l’un à l’autre, bien qu’il y eût, sur beaucoup de
points, une divergence à peu près complète dans leur manière de
penser et de sentir.
Douée d’une foi très vive, Mme de Preymont avait essayé de la
donner à son fils ; mais il l’avait promptement perdue dans les écarts
d’un cerveau vigoureux et indépendant, et surtout dans la
misanthropie secrète, dans le pessimisme de ses pensées. Mais il
admirait, il aimait la vertu sereine de sa mère, et savait qu’il n’y avait
pas une de ses qualités qu’elle n’eût acquise ou développée par
l’influence mystérieuse de ses croyances. Peut-être devait-il à cet
exemple de rester spiritualiste, à défaut de religion positive, et
d’avoir une notion non seulement exacte, mais délicate, du bien et
du mal.
Mme de Preymont l’écouta d’un air incrédule et lui dit :
— Aujourd’hui, Marc, tu as eu enfin le courage d’aller voir
Suzanne !
Cette attaque subite déplut à Preymont, et ses sourcils se
froncèrent.
— Si tu souffres, reprit-elle vivement, avoue-le-moi. Je suis là
pour te tendre une main amie.
Elle avait parlé avec la hâte d’une résolution arrêtée qu’il paraît
très difficile d’exécuter. Preymont, en effet, même avec elle, n’était
pas d’un abord facile sur le terrain des sentiments intimes. Il recula
dans l’embrasure de la fenêtre et s’adossa les bras croisés contre un
des battants ouverts.
— Je n’ai rien à avouer, dit-il avec calme. Oui… je suis allé voir
Suzanne. Elle paraît très heureuse, et comment pourrait-il en être
autrement ? Pourtant je ne suis pas sans inquiétude.
— Pourquoi ? demanda Mme de Preymont. Crains-tu que son père
n’ait trop pesé sur sa détermination ? Mais si M. Varedde ne lui était
pas sympathique, elle ne l’accepterait pas.
— Je ne lui fais pas l’injure de croire le contraire, dit-il avec
vivacité. Varedde est, sous tous les rapports, dans une bonne
moyenne, il n’a rien de déplaisant, mais elle est certainement
supérieure à lui. Il est vrai qu’elle ne s’en doute pas, et d’ailleurs,
quels points de comparaison a-t-elle pour le juger ?
— Je ne partage pas tes inquiétudes, ou, pour mieux dire, tes
préventions, répondit Mme de Preymont. Elle se marie avec un
honnête garçon qui l’aime, et, bien que ce mariage ne soit pas celui
que j’eusse désiré pour elle, il y a beaucoup de chances de bonheur
dans la balance.
— Sans doute ! sans cela vous et moi serions intervenus. Mais,
continua Preymont avec irritation, vous avouerez du moins qu’il ne la
sort pas complètement d’un milieu pour lequel assurément elle n’est
point faite, surtout après avoir reçu une éducation qui a développé
sa distinction naturelle. Personnellement je ne connais pas beaucoup
Varedde, mais certains propos me font craindre qu’il ne soit assez
vulgaire, et que son mariage ne soit pour lui une bonne affaire.
Cependant, s’il l’aime vraiment, et comment ne l’aimerait-il pas ?
Bien du temps passera avant qu’elle voie juste, et, si ce moment
arrive, les enfants seront là pour compenser les mécomptes.
D’ailleurs, que sait-on ? Elle ne sera pas ce qu’elle pourrait devenir
dans des conditions différentes, elle est trop jeune encore pour ne
pas subir l’influence de l’entourage. Je ne sais si Varedde la connaît
bien, mais elle est adorable avec l’exagération de ses qualités, sa
décision et la fougue de ses jeunes appréciations.
Preymont se parlait à lui-même. Il avait oublié la présence de sa
mère qui l’écoutait le cœur serré. Quand il s’agissait de son fils, elle
perdait la rectitude d’un jugement ordinairement très droit, et, fière
de son intelligence, de son énergie, ne voyant en lui que l’homme
supérieur, elle rêvait toujours qu’il bût à la source sur laquelle
chaque passant de la vie se penche avec avidité.
— Ah ! Marc, dit-elle, si tu avais laissé entrevoir…
— Entrevoir quoi, ma pauvre mère ? interrompit-il vivement. Je ne
pouvais être pour elle qu’un ami, que le vieux compagnon qui la
faisait sauter sur ses genoux lorsqu’elle avait cinq ans. Croyez bien,
continua-t-il avec une amertume qu’il ne pouvait réprimer, que je ne
suis pas un homme à ses yeux, mais un être à part. Il n’y a pas une
de ses paroles confiantes, de ses familiarités naïves, de ses
confidences qui ne m’en soient une preuve.
— Un mot aurait pu tout changer, Marc.
— Tout changer… vous le dites bien. Notre amitié se fût à tout
jamais évanouie, et je ne serais plus dans son souvenir qu’un
grotesque personnage.
— Grotesque !… un homme de ta valeur !
Il se mit à rire.
— Les mères sont incorrigibles, dit-il en portant à ses lèvres la
main de Mme de Preymont ; elles s’obstinent à rêver alors que le rêve
devrait être enseveli sous les saisons passées. Souvenez-vous
d’anciennes déceptions, et croyez que j’ai enterré, bien enterré la
jeunesse et ses désirs.
Il les avait enfouis en effet au fond de lui-même, en se jurant de
n’y plus jamais songer ; mais ils s’échappaient de leur prison, ils
renaissaient si vigoureux qu’il lui fallait une volonté de fer pour les
obliger à rentrer sous les verrous.
— Pour en finir avec ce sujet, reprit-il, si je m’étais trouvé dans
des circonstances normales, je ne dis pas que vos rêves ne se
fussent pas rencontrés avec mes sentiments. Maintenant n’en
parlons plus jamais. Le sort de Suzanne est fixé désormais, et le
mien l’est depuis longtemps. C’est celui d’un solitaire, mais d’un
solitaire qui a bien des compensations aux épreuves de sa vie.
Et il ajouta avec un sourire qui donnait de la séduction à son
visage ordinairement trop sérieux :
— Suis-je donc bien à plaindre de vivre auprès de vous ?
Beaucoup d’hommes n’ont pas choisi d’autre sort. C’est à vous que
je dois l’orientation de mon intelligence, ma situation, et je suis bien
heureux de vous devoir même les joies du foyer. Vous m’avez ainsi
tout donné.
— Oui…, répondit machinalement Mme de Preymont, tout !…
excepté la goutte de bonheur que chacun demande à la vie.
Preymont se mordit les lèvres et ne répondit pas. Il détestait
qu’on ouvrît la porte de sa cellule intime, lui-même n’y entrait qu’en
tremblant, car il en sortait toujours meurtri. Sa mère le savait et
regrettait les mots qu’elle avait prononcés involontairement.
Preymont regardait devant lui ; les lèvres serrées énergiquement,
il luttait pour contenir l’orage qui voulait éclater. Il y avait des mois
que, se débattant vainement, il ne pouvait plus remonter la pente au
bas de laquelle il avait glissé. Mais, depuis longtemps, sa vie morale
était assise sur un orgueil hautain et philosophique, et il entendait
que ce compagnon, gardien fidèle de son énergie, le soutînt dans la
crise qu’il traversait.
Des chiens de garde qui aboyèrent firent diversion à leurs
pensées ; en même temps une voix mâle et sympathique criait
gaiement :
— Pourquoi ouvrez-vous de si grands yeux, vieille Marion ? Ai-je
l’air d’un fantôme ? Après tout, je puis bien avoir la figure hâve d’un
affamé. Il y a huit heures que je n’ai mangé, grâce à ma brute de
voiturier qui a failli me verser trois fois dans le fossé avec son maudit
cheval.
— Mais c’est Saverne ! s’écria M. de Preymont en se dirigeant
vivement vers la porte.
Quand il entra dans la cour plantée sur laquelle ouvrait la façade
de l’habitation, le nouveau venu tenait son voiturier par la nuque, et
le secouait avec un entrain que l’arrivée de Preymont ne réussit
point à calmer.
— Je te dirai bonjour dans un instant, Marc, cria-t-il ; il faut
d’abord que j’en finisse avec ce gredin qui me réclame vingt francs
quand je ne lui en ai promis que quinze ; et encore si je t’arrive
intact, ce n’est pas de sa faute. En vérité, continua-t-il avec un
redoublement de vigueur, j’aimerais mieux me jeter au fond d’un
puits avec ma bourse que de lui céder… Là ! je crois que nous
sommes plus sage.
Il recula de quelques pas pour contempler son œuvre dans la
personne du cocher qui, rouge, essoufflé et furieux, était partagé
entre le désir de se jeter sur Saverne et celui de prendre la fuite. Les
formes athlétiques du jeune homme et l’impétuosité de caractère
dont il venait d’avoir une preuve pénible, le décidèrent pour la fuite.
Il empocha en jurant l’argent que Saverne lui tendait et se sauva.
— Très bien, dit Saverne d’un ton satisfait, la victoire me reste.
— Mais elle te fût restée sans tant d’énergie, répondit Marc en
riant.
— Bah ! c’eût été plus long, et j’aime les moyens expéditifs.
L’animal était en train de discuter.
Il s’approcha de Mme de Preymont qui avait assisté en souriant à
la fin de la scène.
— Il me semble que j’arrive comme un intrus, lui dit-il. Je n’y
comprends rien, car j’ai écrit pour m’annoncer.
— La lettre ne nous est pas parvenue, répondit-elle, mais vous
savez, mon cher enfant, que votre chambre est toujours prête.
— Ces imbéciles de la poste n’en font jamais d’autres ! s’écria
Saverne avec indignation. Ce soir même je griffonne contre eux un
article qui les fera enrager, j’en réponds !
— Êtes-vous bien sûr que la lettre ne soit pas dans votre poche ?
demanda Mme de Preymont.
— Par exemple !… je l’ai mise moi-même dans la boîte.
Saverne se fouillait avec la vivacité d’un accusé qui tient à
prouver au plus vite son innocence.
— Pardieu, la voici ! dit-il en la présentant avec la plus grande
aisance. Seulement elle arrive après mon individu. C’est une belle
occasion pour Marc de répéter que je suis un étourdi.

É
— Étourdi ou non, tu es comme toujours trois fois le bienvenu,
répondit M. de Preymont d’un ton affectueux.
Leur amitié remontait au collège. Lorsque l’enfant difforme et
timide s’était trouvé livré sans défense à la persécution traditionnelle
de ses camarades, Saverne, quoique sensiblement plus jeune que
lui, l’avait pris sous sa protection, et, pendant que ses poings
robustes mettaient la paix, son bon cœur avait de chaudes paroles
pour consoler Preymont, qui ne devait pas plus oublier cette
intervention bienfaisante que la profonde amertume de ces jours
passés.
Une solide amitié se cimenta entre eux, et, plus tard, les rôles
furent intervertis, car Saverne, à peine eut-il la bride sur le cou,
s’empressa de dévorer son patrimoine, et Preymont, tout en
essayant de calmer sa fougue par de bons conseils, le tira plus d’une
fois d’un mauvais pas en lui prêtant sa bourse. Ses conseils, écoutés
et approuvés avec enthousiasme, glissaient sur une nature
excellente, facile à l’entraînement, s’abandonnant aux caprices du
moment avec l’insouciance d’un esprit dont les principes sont
élastiques et dont la liberté n’est entravée par aucun lien de famille.
Mais Saverne avait le don rare de plaire à tout le monde ; les gens
les plus sérieux lui pardonnaient les écarts de sa nature superficielle
en faveur de sa bonne humeur inaltérable, de la franchise avec
laquelle il avouait ses torts et d’une verve qui entraînait les rieurs de
son côté.
Mme de Preymont le traitait en enfant très aimé pour lequel on a
des indulgences inépuisables, et Saverne, sans intérieur, sans
famille, considérait comme sienne la maison de son ami. Il vivait
largement du produit de ses talents. Caricaturiste recherché, il
écrivait en outre d’une plume légère et facile dans différentes feuilles
périodiques.
— Eh bien, enfant terrible, lui dit Mme de Preymont, quelles
sottises avez-vous faites depuis que je vous ai vu ?
Saverne, qui dégustait des fraises, cessa de manger pour
réfléchir sérieusement, et s’écria d’un air étonné :
— Aucune !… Par le ciel, madame, c’est étonnant !
— Alors vous nous revenez tout à fait converti. La dernière fois
que nous avons causé ensemble, vous parliez de mariage avec une
grande sagesse.
— Ah ! ma sagesse est plus grande que jamais, je ne demande
qu’à la suivre, mais…
Il jeta un regard éploré à Marc.
— Mais ta sagesse ne s’accorde pas avec celle… de tout le
monde, répondit Preymont en souriant.
— Tu l’as dit, répliqua Didier piteusement. Et pourtant je suis
fatigué de vivre seul… du moins sans intérieur régu… bref, tu
comprends ! ajouta-t-il en noyant l’explication dans son café et le
respect que lui inspirait Mme de Preymont.
— J’aime à vous voir cet air soucieux, lui dit-elle, nous en
reparlerons, et je ferai en sorte de vous découvrir une sage petite
femme.
— Une sage petite femme ! répéta Saverne d’un ton inquiet.
Sage… oui, mais pas trop sérieuse, n’est-ce pas ? Je ne veux pas
d’une vertu coiffée d’un bonnet de coton ! s’écria-t-il avec effroi.
— Rassurez-vous, répondit Mme de Preymont en riant. Ce n’est
pas de nos jours que la vertu est tentée de mettre cette coiffure à la
mode.
Preymont conduisit son ami dans une chambre dont les vastes
proportions plaisaient à Saverne.
— Les femmes comme ta mère sont des femmes admirables,
déclara Didier, mettant en une minute le désordre autour de lui.
Admirables ! il n’y a pas d’autre expression. Seulement ces saintes,
entortillées de vertus et de bonnes pensées, ne connaissent pas plus
la vie qu’un enfant, et ne se doutent pas de l’embarras dans lequel
est plongé un pauvre garçon rempli de bon vouloir, mais orné d’un
crampon.
— Peut-être que si… mais je ne crois pas que ton malheur lui
inspire une profonde commisération.
— Voilà, voilà ! qu’est-ce que je disais ? s’écria Saverne en
bouleversant son sac de voyage pour chercher, sans la trouver, la
clef de sa malle. Elle croit qu’il est facile de vivre dans une cellule,
un capuchon sur le chef, une tête de mort devant soi pour méditer
et une cruche d’eau pour se restaurer… Mais bah ! je ne veux penser
à rien ce soir. Tout s’arrangera : mon crampon s’en ira au diable, et
je prierai ta mère de me trouver une femme, car, après tout, je dois
avouer qu’elle ne m’a jamais parlé de cellule, et que j’ai confiance en
son jugement.
Impatienté de ne pas trouver la clef qu’il cherchait, il fit sauter la
serrure de sa malle et en éparpilla le contenu autour de lui.
— Voilà qui est fait, dit-il avec satisfaction. Ton valet de chambre
se débrouillera demain avec mes effets. Une nuit passée à l’air leur
fera du bien, car c’est moi qui les ai fourrés là dedans, et je n’ai
jamais la patience de les arranger avec symétrie.
— Quand tu seras marié, ta malle ne ressemblera plus à une
hotte de chiffonnier, répondit Preymont en riant. Bonsoir !
Au moment d’ouvrir la porte, il se retourna pour dire avec effort :
— A propos de mariage… tu arrives précisément pour assister à
celui d’une cousine à moi.
— Ah !… est-ce la petite Suzanne que j’ai vue ici autrefois ?
— Oui… c’est Mlle Jeuffroy.
— Enfant, elle était gentille. Qu’est-elle devenue comme femme ?
— Tu la verras après-demain, c’est le jour du contrat, et je te
ferai inviter.
— Bravo ! j’étudierai sur le fiancé quelle tête il faut avoir quand
on se marie, et je trouverai bien parmi les invités quelques
silhouettes pour mon crayon.
Preymont, après une journée d’efforts pour se dominer, éprouvait
un impérieux besoin de solitude. Il sortit, puis traversa la route et les
prés qui séparaient la propriété des bords de la Loire.
Souvent, dans le même endroit, il était venu, fatigué d’un travail
aride ou saisi de tristesse devant des désirs irréalisables, chercher
dans l’imposant silence et la tranquille limpidité de la nuit le calme
extérieur qui agit sur la pensée. Mais alors il ne trouva dans la
solitude qu’un homme malheureux.
« J’aime…, pensait-il, moi qui n’ai même pas le droit, sans être
ridicule, d’associer ce mot à mes pensées. »
Et il se sentait aux prises avec des accès de misanthropie, de
colère, de découragement que son orgueil et sa philosophie étaient
impuissants à vaincre.
La réflexion, l’expérience et une tendance à la spéculation
avaient développé une largeur de pensée innée chez lui. Il aimait à
généraliser ses idées dans la contemplation de la place infime que,
pris isolément, l’homme occupe dans l’univers. Le regard posé sur le
renouvellement de la nature et des siècles, les lignes avaient alors à
ses yeux leurs proportions réelles, et il aimait à trouver ainsi une
liberté de jugement qui aurait détruit en lui les préjugés s’il en avait
eu. Il était résulté de cette tendance d’esprit que non seulement il
restait étranger aux vanités mesquines et aux intolérances étroites,
mais qu’il s’était créé une sorte de stoïcisme, à l’aide duquel il
prétendait s’élever au-dessus des faiblesses de l’amour-propre et de
la passion.
Mais, malgré ses affirmations, il y avait manque d’équilibre entre
ses sensations, ses sentiments et sa pensée. Il le voyait quand il se
laissait entraîner, parce qu’il souffrait, à des emportements
misanthropiques, malgré l’indulgence, malgré la profonde pitié qu’il
puisait pour l’humanité dans une intelligence saine et large.
Quand il remonta chez lui, la vie calmée de la nature endormie
n’avait fait qu’assister aux luttes d’un cœur ardent et comprimé,
plein d’une passion qui le livrait à une profonde angoisse.
III

Le lendemain, il écrivit à M. Jeuffroy pour lui demander s’il


pouvait, sans indiscrétion, lui présenter Saverne au contrat, car il
savait que M. Varedde, en grand deuil de ses parents, désirait que le
mariage se fît dans la plus complète intimité, à la très vive
satisfaction de son beau-père, dont les dépenses se trouvaient ainsi
forcément limitées.
— Saverne, Saverne ! répéta M. Jeuffroy en lisant le billet devant
sa sœur. Je connais ce nom-là… Il y a longtemps qu’il n’est venu ici,
mais je me rappelle l’avoir vu une fois. Parbleu, j’y suis ! c’est un
dessinateur et un écrivain. Je ne sais pas ce qu’il écrit, mais il est
connu.
Mlle Constance n’ouvrait jamais un livre, et considérait qu’un
auteur est un phénomène que les simples particuliers, heureusement
pour eux, ne sont pas appelés à rencontrer dans leur chemin.
— Un homme qui écrit ! s’écria-t-elle ; et Mme de Preymont l’a
chez elle !… Pauvre femme ! que va-t-elle lui donner à manger ?
— Hum ! je n’aime guère ces gens-là ! reprit M. Jeuffroy, dont la
large face exprimait cependant une certaine satisfaction. Des
viveurs, des paniers percés !
— Que vas-tu faire, mon frère ?
— Parbleu ! je vais dire à Preymont de l’amener ; Varedde ne
pourra pas en être contrarié. D’ailleurs, c’est flatteur d’avoir à sa
table un homme dont le nom est souvent dans le journal.
Ce fut avec un visage impassible que Preymont, habitué à cacher
ses impressions, partit avec sa mère et Saverne pour aller remplir
son rôle de témoin.
Lorsqu’ils entrèrent dans le salon, Suzanne, dont la beauté était
mise en relief par une toilette élégante donnée par Mlle Constance,
causait avec son fiancé, un grand garçon bien planté, mais que
Saverne, stupéfait de la rare beauté de Mlle Jeuffroy, jugea
absolument indigne de baiser même le bout des doigts de la jeune
fille.
Assise bien droite dans un fauteuil, ses papillotes un peu jaunes
arrangées avec ordre sous un bonnet de dentelle, vêtue d’une robe
de soie noire qu’elle avait eue pour le mariage de son frère et que
quelques ornements de sa façon essayaient de rajeunir, Mlle
Constance, un sourire de béatitude sur les lèvres, ressemblait à une
apparition étrange et surannée. Si parfois elle avait rêvé qu’en des
temps différents la beauté de sa nièce l’eût fait aimer d’un prince,
elle songeait que les mœurs actuelles ne sont point à dédaigner, et
qu’il est bien doux de conserver le droit de manifester son amour à
ceux qu’on aime.
Quand le notaire commença la lecture du contrat, Suzanne,
étouffant un soupir d’ennui, se tourna vers le jardin et s’abandonna
à ses pensées heureuses.
La chaleur, cette année-là très tardive, était apparue subitement,
plongeant dans un délire joyeux tous les êtres qui tiennent d’elle ou
la vie ou la joie. Comme des fous ravis, ils s’agitaient en masse avec
un bruit assourdissant, s’acheminant affairés vers on ne sait quel but
mystérieux. Les feuilles tremblaient d’ivresse sous la caresse d’un
souffle parfumé ; un fin duvet, échappé de grands peupliers, suivait
tous les caprices de la brise pour venir tomber en si grande quantité
dans les allées que le sol, par endroits, semblait enfoui sous une
neige blonde. Ce duvet léger s’aventurait dans les rayons de vive
lumière qui pénétrait dans les appartements ouverts ; il s’y précipitait
avec elle, effleurant en passant le visage de la jeune fille sans réussir
à la distraire de sa rêverie.
A quelques pas d’elle, Preymont contemplait, avec des pensées
bien différentes, la joyeuse folie de la vie qui parait de sa jeunesse
jusqu’aux vieux et sombres ifs, dressant dans le jardin les formes
laides et bizarres qu’on leur avait données. Il sentait sourdre dans
son âme une vieille, une ardente colère contre tout ce qui est vie et
joie. Il savait que, dans d’autres circonstances, il eût pu se faire
aimer de cette femme ravissante et mettre à ses pieds les trésors
d’un cœur affamé qu’il avait cru mort aux rêves de bonheur.
Les visages et les objets qui l’entouraient lui étaient odieux ; il se
demandait avec irritation quel était son rôle au milieu des rouages
éternels de la nature, lui auquel les joies et les devoirs les plus
légitimes étaient refusés. Ancienne et dévorante pensée qui, lorsque
la passion n’en était pas comme aujourd’hui l’inspiratrice, avait
cependant étendu son ombre épaisse sur ses efforts et ses travaux
dans les moments les plus brillants de leur réussite.
Il tressaillit, comme un homme réveillé brusquement, quand
Saverne, absorbé jusque-là dans la contemplation de Suzanne, se
pencha à son oreille pour lui dire :
— Quelle ravissante créature !… mais comprend-on pourquoi elle
épouse un grand gaillard aussi banal ! je le trouve vulgaire.
— Elle le voit sous un autre jour, répondit Preymont d’un ton bref,
et la réputation de M. Varedde est celle d’un très brave garçon.
— Je pense bien qu’on ne la donne pas à un repris de justice !
répliqua Saverne. Un brave garçon ! bel argument, ma foi, pour
marier une femme qui, si elle le voulait, bouleverserait la cervelle de
tous les hommes.
Une interruption dans la lecture du contrat l’obligea au silence.
Suzanne, n’entendant plus la voix forte et monotone du lecteur,
tourna la tête et vit que M. Varedde discutait à voix basse avec le
notaire.
— Je crois, monsieur, qu’il y a là une erreur.
— Aucune erreur !… M. Jeuffroy m’a donné écrite l’énumération
des titres qui devaient être portés sur le contrat, et je n’ai eu qu’à
copier exactement.
— Eh bien, reprit Varedde, M. Jeuffroy a eu une distraction ; ce
sera facile de rectifier.
Le notaire toussa d’une façon significative, et lui dit tout bas
précipitamment :
— Prenez garde ! ce n’est pas l’habitude de mon client de se
tromper sur des chiffres.
— Raison de plus pour m’expliquer, répondit-il.
Il se tourna vers M. Jeuffroy, qui attendait d’un air tranquille la fin
du colloque.
— Je disais à monsieur qu’il y a une erreur, reprit-il. Voulez-vous
bien examiner avec moi ?
— Une erreur !… quelle erreur ? répondit M. Jeuffroy en se levant.
— Voulez-vous que nous passions dans votre cabinet pour nous
expliquer, monsieur ? Nous serons plus libres, et nous n’ennuierons
personne de ces détails.
Suzanne, surprise en les voyant s’éloigner, interrogea Preymont,
qui répondit d’un ton insouciant :
— Un malentendu, je crois, que ces messieurs vont éclaircir en
quelques mots.
— C’est la faute du notaire, dit Mlle Constance, vaguement
inquiète. Il aura mal compris les idées de mon frère.
Mais l’explication se prolongeait et dégénérait en altercation. M.
Varedde ayant élevé la voix, on l’entendit s’écrier avec colère :
— Ce n’est qu’une duperie, monsieur ! et si vous avez cru que je
n’étais pas assez expérimenté en affaires pour m’en apercevoir, vous
vous étiez trompé. J’ai toujours entendu épouser une femme qui
m’apportât 100,000 francs de dot parfaitement liquides ; mais vous
vous êtes arrangé de façon que la dot promise se trouve réduite à
60 ou 70,000 francs au plus… Je refuse de signer le contrat si vous
ne le rectifiez pas.
Suzanne n’entendit pas la réponse de son père ; elle s’était levée
pâle d’émotion et les yeux indignés.
Sa tante entra précipitamment dans le cabinet de M. Jeuffroy.
— Qu’y a-t-il ? pourquoi vous fâchez-vous ? demanda-t-elle d’une
voix étranglée par l’inquiétude.
— Mademoiselle, répondit M. Varedde qui paraissait très excité,
monsieur votre frère a bien promis une dot de 100,000 francs, mais
il en a représenté un bon tiers en valeurs à peu près fictives, car il
sait aussi bien que moi qu’elles n’auront plus cours dans un temps
très rapproché, et que le taux en est du reste absolument illusoire.
Peut-être avait-on espéré que la fraude passerait inaperçue, ou que,
si près du mariage, je n’oserais pas protester.
— Vous pourriez ménager vos expressions ! s’écria M. Jeuffroy
furieux. Un père est bien libre de constituer la dot de sa fille comme
il lui convient, sans pour cela commettre de fraude.
— Certainement, monsieur, vous êtes très libre, mais je le suis
également de me retirer si vous me poussez à bout.
Le notaire se tenait coi, voyant que la bourrasque était trop forte
pour qu’il pût intervenir. Il en observait les différentes phases avec la
mine placide d’un homme dont l’expérience est grande.
Mlle Constance, épouvantée, prit son frère à part et lui dit :
— Il faut céder, mon frère. Un mariage manqué fait un tort
considérable à une jeune fille. Et puis, il faut penser avant tout à
Suzanne, au chagrin qu’elle aurait… Change vite les valeurs.
— Je ne changerai rien, répondit M. Jeuffroy en frappant du pied.
Je ne vois pas pourquoi ma fille et mon gendre n’auraient pas aussi
bien que moi quelques valeurs médiocres. Varedde aime Suzanne ou
ne l’aime pas. Quelques sous de plus ou de moins ne font rien à
l’affaire.
— Mais il peut bien l’aimer et tenir à la dot, répondit Mlle
Constance au désespoir. Mon frère, pense à Suzanne et fais un
sacrifice.
— Sacrifice, sacrifice !… propos de femme ! répondit M. Jeuffroy
dont les petits yeux, sous l’empire de la colère, avaient découvert le
moyen de devenir expressifs. Vais-je me mettre sur la paille sous
prétexte que Suzanne est ma fille ? Je ne changerai rien, rien aux
dispositions prises.
Son avarice, dans le moment, dominait sa vanité et toutes les
considérations qui le pressaient de marier sa fille. L’entêtement d’un
esprit borné s’en mêlait, mais, au milieu de ces différents
sentiments, il n’oubliait pas que, en méditant de duper M. Varedde, il
avait songé à la générosité de sa sœur si un conflit se produisait. Le
parti de la vieille fille fut en effet pris immédiatement. La somme en
discussion représentait à peu près la moitié du petit capital que,
chaque année, elle augmentait avec délices par ses économies, mais
elle n’hésita pas à s’en dépouiller.
— J’en aurai toujours assez, dit-elle à son frère ; il nous faut si
peu de chose pour vivre, à Fanchette et à moi !
— Ma foi, répondit M. Jeuffroy d’un ton maussade, si tu veux
faire un cadeau à ta nièce, tu es bien libre. Pour moi, je ne puis rien
de plus.
Mlle Constance courut à M. Varedde et lui dit :
— Tout est arrangé, mon cher monsieur, je prends pour moi les
valeurs qui ne vous plaisent pas, et je les remplace par une partie
des miennes. Elles sont, au reste, à Suzanne, puisque toute ma
fortune doit lui revenir un jour.
Varedde respira ; il craignait d’être allé trop loin et d’avoir amené
une rupture. Il aimait réellement Suzanne, mais il était de ceux qui,
après avoir pesé tous les avantages d’un mariage, n’entendent pas
qu’une parcelle leur en soit enlevée. Cependant ce fut en hésitant
qu’il répondit à Mlle Constance :
— Mais, mademoiselle, c’est une affaire entre moi et M. Jeuffroy.
Je ne vous demande rien, et je ne sais si je dois accepter.
— Pourquoi n’accepteriez-vous pas, monsieur, si moi j’accepte ?
Varedde se retourna vivement et se trouva en face de Suzanne,
dont les grands yeux bleus brillaient de colère. Il resta tout interdit,
se demandant avec une terrible inquiétude si elle avait entendu les
propos exaspérés que, dans son emportement, il n’avait pu retenir. Il
crut habile de traiter légèrement l’incident :
— Ma chère enfant, lui dit-il en souriant, les questions d’argent ne
vous regardent pas ; que venez-vous faire ici ?
— Ce que je crois devoir faire, monsieur, répondit-elle d’un ton
dédaigneux.
— C’est me répondre d’un ton un peu désobligeant, chère
Suzanne. Je vous en prie, rentrez dans le salon, l’affaire sera réglée
dans une minute, et nous vous rejoignons.
— L’affaire, comme vous l’appelez, est toute réglée, répliqua
Suzanne. Ma chère, ma bonne tante, j’accepte votre aumône.
— Mademoiselle ! s’écria Varedde en rougissant de colère.
— Quoi ?… le mot vous déplaît ?… mettez don si vous voulez, et
qu’on termine au plus vite.
La jeune fille, très pâle, était si belle que le notaire, malgré ses
cheveux gris, faillit tomber amoureux d’elle. Elle parlait d’un ton
décidé qui frappait de surprise M. Jeuffroy et produisait sur Varedde
une impression extrêmement pénible, car il avait été convaincu
jusque-là qu’une jeune fille de dix-neuf ans est une enfant sans
initiative et maniable comme de la cire molle.
— Suzanne, ma chère Suzanne, lui dit-il en l’attirant malgré elle
dans l’embrasure de la fenêtre, cette scène est déplorable, je la
regrette amèrement. Pourquoi cet air en colère ? Que supposez-
vous ? N’allez pas imaginer que je ne vous aime pas parce que je
refuse d’être dupe.
— Est-ce que mon père est capable de duper qui que ce soit,
monsieur ? répondit Suzanne avec véhémence.
Furieux contre lui-même, Varedde répliqua :
— Je suis trop ému en vous voyant cet air mécontent, Suzanne,
pour peser mes mots. Si je vous ai blessée par certaines
expressions, j’en suis sincèrement désolé. Faites la part de la
surexcitation du moment. C’est fini, n’est-ce pas ?
— Mais le malentendu n’existe plus, monsieur, répondit Suzanne
à haute voix. Ma tante a levé toutes les difficultés ; vous vouliez cent
mille francs, vous les aurez !… et, comme vous le disiez, n’en parlons
plus.
Puis elle ajouta plus bas, d’un ton ironique :
— Quant à votre amour, je n’ai évidemment aucune raison d’en
douter. J’y crois, oh ! très fermement.
Le malheureux Varedde, interdit, sentait qu’il jouait un rôle
pitoyable, qu’elle le tenait sous ses pieds et que, devant cette colère
de femme offensée, le plus sage parti était de ne rien dire.
Mlle Constance, qui avait fait rectifier le contrat, s’approcha d’eux
et enleva la position.
— Tout est en règle maintenant, mes chers enfants : terminons
vite. Que doivent penser les Preymont et les témoins ?
— Ma tante a raison, monsieur, reprit Suzanne, ce malheureux
incident n’a que trop duré. Par égard pour moi, veuillez ne plus
discuter.
Lorsque, malgré un mouvement de Preymont pour l’arrêter,
Suzanne était entrée dans le cabinet de son père, elle en avait
refermé la porte, et les invités, réduits aux conjectures,
échangeaient leurs suppositions.
— Ah ! s’écria Saverne avec indignation, je crois, en vérité, qu’il
marchande… c’est dégoûtant !
— L’expression est un peu vive, monsieur, releva un des témoins
de M. Varedde. En quoi est-ce dégoûtant de penser à ses intérêts et
de ne pas vouloir être attrapé ?
— Attrapé !… ah ! le mot est joli ! répliqua Saverne avec chaleur.
Attrapé ! quand il devrait mendier à genoux la main de Mlle Suzanne,
et ne penser qu’à son infériorité devant tant de grâce et tant de
beauté… La belle affaire que trente mille francs ! A la place de Mlle
Jeuffroy, je flanquerais votre ami à la porte !
— Mais taisez-vous donc ! lui dit tout bas Mme de Preymont en
posant la main sur son bras pour calmer son exaltation. De quoi
vous mêlez-vous ? Devenez-vous fou ?
Preymont écoutait silencieusement. Pour lui qui aimait
passionnément Suzanne dont il connaissait le caractère fier et entier,
il se demandait, avec angoisse, ce que deviendrait une vie
commencée par une blessure qui devait révolter la jeune fille.
Il l’examina avec attention quand elle rentra dans le salon. Sans
rien dire, elle alla reprendre la place qu’elle occupait précédemment.
« Que pense-t-elle ? » se demandait Preymont en remarquant
qu’elle pâlissait et rougissait alternativement sous l’excitation de ses
sentiments intimes.
— Un léger malentendu, expliqua le notaire, tout est réglé
maintenant. Je crois que nous pouvons procéder aux signatures…
Mademoiselle Suzanne, voulez-vous venir signer ?
Mais il répéta deux fois la question sans qu’elle entendît sa voix.
— Ma chère Suzanne, dit Marc en lui prenant la main, on
demande votre signature.
Elle se leva aussitôt et s’approcha de la table en disant :
— M. Varedde a-t-il signé ?
— C’est vous, mademoiselle, qui devez commencer, lui dit le
notaire ; c’est un usage courtois.
— Non… je ne signerai qu’après lui. Monsieur, signez, je vous
prie.
Devant le ton impérieux de la jeune fille, M. Varedde eut quelque
peine à retenir un geste de colère ; mais il se contint, et, après avoir
signé d’une main nerveuse, il lui passa la plume. Elle la jeta devant
elle, prit vivement le contrat et le déchira.
A cet acte imprévu, Mlle Constance, stupéfaite, poussa un cri ; M.
Jeuffroy, furieux, s’avança vers sa fille et lui saisit le poignet en
disant :
— Sotte !… deviens-tu folle ?
M. Varedde la regardait sans pouvoir prononcer un mot.
— Monsieur, lui dit Suzanne, qui, par un énergique effort de
volonté, parlait avec calme, je n’épouserai jamais un homme qui m’a
marchandée. Voici la bague de fiançailles, on vous renverra le reste
aujourd’hui même.
— De quel droit te permets-tu…, commença M. Jeuffroy.
Mais M. Varedde l’interrompit d’un geste et, tout tremblant de
colère, s’écria :
— Comment ! pour une simple discussion d’argent, vous renoncez
à m’épouser ?… Pourtant, mademoiselle, si vous êtes loyale, il me
semble que vous devez avoir un peu d’affection pour l’homme à qui
vous donniez votre main !
— Osez, s’écria Suzanne avec impétuosité, osez affirmer que, si
ma tante n’avait pas eu la générosité de se dépouiller pour
compléter ma dot, vous n’auriez pas rompu !… Vous vous permettez
de mettre en doute ma loyauté monsieur, continua-t-elle les yeux
étincelants ; mais votre amour si souvent affirmé, où est-il ? Dans
l’offense faite à votre fiancée, ou dans l’insulte jetée à mon père ?
— Je sais que je vous ai donné prise sur moi, répondit M.
Varedde, et il est difficile de raisonner avec une femme en colère ;
mais si vous m’aimiez réellement, vous pardonneriez facilement
quelques mots trop vifs.
— Il y a autre chose que des mots trop vifs, répliqua Suzanne
d’une voix tremblante, et la sympathie ne résiste pas à certaines
épreuves ; j’avais donné la mienne à quelqu’un qui n’était pas vous.
Elle lui tourna le dos et quitta le salon.
Son départ fut suivi d’un moment de stupeur. Saverne, transporté
d’enthousiasme, eût voulu précipiter par la fenêtre le père et le
fiancé, puis s’élancer sur les pas de la jeune fille, lui exprimer son
ardente admiration, s’en faire aimer en deux temps et l’emmener
très loin dans les régions de l’amour chevaleresque.
Bouleversé et pâle comme un mort, Preymont se pencha vers sa
mère et lui dit :
— Vous seule pouvez trouver le mot qui lui fera du bien. Suivez-
la, je vous en prie, et, si c’est possible, que Mlle Constance ne
l’accable pas de ses consolations.
Ensuite il s’efforça d’empêcher que les esprits surexcités
n’allassent trop loin.
Après quelques paroles vives échangées avec M. Jeuffroy,
Varedde se retira, suivi immédiatement de Preymont et des quelques
personnes présentes.
L’événement avait été si rapide que M. Jeuffroy, resté seul, se
demandait s’il était bien éveillé. Sa rage, son dépit et son chagrin se
résumaient dans cette pensée :
« La triple sotte ! où a-t-elle pris un pareil caractère ? Nous
verrons si je ne le fais pas plier… Elle me payera ce scandale ! »
Il s’était dit, en cédant au désir de diminuer la dot promise, qu’un
homme amoureux écouterait d’une oreille distraite l’énumération
ennuyeuse des valeurs sur lesquelles il pouvait bien, du reste, avoir
des aperçus très superficiels, mais que, dans le cas contraire, il
céderait facilement. Il voyait maintenant que Varedde était de la race
des intéressés, et, malgré sa colère, il le jugeait favorablement.
Mais il ne trouvait aucune circonstance atténuante à la conduite
de sa fille, dont il avait complètement oublié de faire entrer la dignité
et la fierté blessées dans les éventualités prévues. Enfin il
enveloppait Mlle Constance dans son ressentiment :
« Une autre sotte !… puisqu’elle voulait bien faire un cadeau à sa
nièce, elle aurait pu le dire plus tôt. Et encore ça parle de sacrifice !…
Nous voilà dans de beaux draps, grâce à elle ! »
Sa première pensée avait été de céder à la colère et de monter
immédiatement chez sa fille ; mais la nécessité de prendre certaines
mesures l’obligea à sortir, et il ne rentra que pour le dîner.
Pendant ce temps, Suzanne, très surexcitée, n’éprouvait aucune
défaillance et s’efforçait de consoler Mlle Constance désespérée.
— Comment pouvez-vous pleurer ! disait-elle avec animation.
Vaut-il un regret ? N’avez-vous pas entendu qu’il parlait de se
retirer ? Mettez-moi un peu plus haut, ma chère vieille tante ; vous
qui êtes si généreuse, vous devriez le mépriser.
— Mon Dieu, mon Dieu ! répétait la pauvre fille, il est si naturel
de penser à ses intérêts, ma Suzanne ! mais tu es une enfant, tu ne
sais rien de la vie ; on a besoin d’argent. Un si bon parti !
— Vous l’appelez encore un bon mariage quand vous venez de
voir ce qu’était l’homme ! s’écria la jeune fille.
Elle n’essaya plus de discuter, et pendant que Mlle Constance
allait quitter ses vieux atours et narrer à Fanchette son désespoir,
elle s’abandonna à ses pensées sans chercher à calmer leur
surexcitation.
Cependant, elle se disait avec inquiétude :
« Que pense mon père ? pourquoi ne l’ai-je pas encore vu ? »
Ce ne fut pas sans quelque appréhension que, décidée à réagir
immédiatement contre elle-même, elle descendit pour le dîner,
songeant qu’elle délivrerait M. Jeuffroy de son plus grave souci en lui
prouvant, par son air calme, que la blessure se cicatriserait
aisément.
Il entrait dans la salle à manger lorsque Suzanne arrivait. Elle fit
précipitamment quelques pas vers lui, espérant un peu que, pour la
consoler, il allait la prendre dans ses bras comme un père aimant ;
mais elle s’arrêta court devant la mine rogue de M. Jeuffroy qui
s’assit à table sans parler. Il ne rompit le silence que pour se plaindre
amèrement des dépenses inutiles qu’un dîner manqué de quinze
couverts lui avait imposées. Il fit comparaître la cuisinière, et lui
donna des ordres minutieux pour conserver le plus longtemps
possible une partie des mets dont la vue l’horripilait.
— Nous pouvons vivre là-dessus au moins huit jours, lui dit-il. Je
n’entends pas vous donner un sou avant la fin de la semaine
prochaine.
La surexcitation de Suzanne s’abattait plus rapidement qu’un
vent vif sous une pluie fine. Elle luttait contre un accès de
désolation. Jusque-là sa colère contre M. Varedde l’avait soutenue et
ne lui avait pas permis de réfléchir à la conduite de son père ; mais
soudain un doute, qu’elle se reprochait comme une faute énorme, lui
serrait le cœur.
Après le dîner, il lui ordonna d’un ton brusque de passer avec lui
dans le salon.
— Je ne vous ai pas encore dit ma pensée sur votre conduite,
mademoiselle ; je voudrais bien savoir dans quels romans vous avez
pu trouver l’idée qu’une jeune fille avait le droit de mettre à la porte
un fiancé honorable choisi par son père.
— Honorable ! s’écria Suzanne. Mon père, vous trouvez honorable
qu’il songeât à m’abandonner pour une question d’argent ?
— Voilà déjà de grands mots. T’abandonner ! est-ce qu’il en était
seulement question ? Les affaires te regardent-elles ? Est-ce qu’à
chaque instant il n’y a pas quelque discussion sur la forme d’un
contrat ? Ta conduite a été ridicule, inepte, inqualifiable !
Suzanne avait une de ces intelligences nettes et un de ces
caractères bien trempés qui ne se laissent pas démonter par des
reproches injustes ou des idées froissant leur droiture.
— Si c’était à refaire, mon père, et bien que désolée de vous
causer quelque peine, je n’agirais pas autrement, répondit-elle avec
fermeté.
— Quelque peine ! voyez-vous cela, quelque peine ! C’est parler
légèrement de la situation dans laquelle je me trouve, grâce à toi…
Toute la ville glose déjà. On est capable de me jeter la pierre,
quoique j’aie agi selon mon droit.
— Puisque vous avez agi selon votre droit, mon père, comment
pouvez-vous me reprocher d’avoir rompu avec un homme qui vous
accusait d’une chose déshonorante ?
M. Jeuffroy, devant un raisonnement qui défiait la contradiction,
employa, pour avoir raison, un moyen connu et apprécié de bien des
gens :
— Tais-toi… tu n’ouvres la bouche que pour dire des sottises. Je
suis vraiment bien malheureux. J’arrange pour toi un mariage
excellent avec un charmant garçon, je me réjouissais de penser que
ma fille allait être heureuse, et, par caprice, elle détruit mon
ouvrage. Elle me met à dos la meute des malveillants, elle m’attire
une scène désagréable, elle nous donne tous en risée à un tas de
gens dépités de te voir faire un excellent mariage…
Excité par ses paroles, il se tourna vers Mlle Constance qui
essayait de le calmer et de défendre Suzanne :
— Quant à toi, tu as agi comme une imbécile. Puisque tu voulais
faire un cadeau, il fallait le dire tout de suite ; nous aurions ainsi
évité le scandale de mademoiselle ma fille.
Suzanne s’avança vers sa tante et l’embrassa, en disant d’une
voix entrecoupée :
— Je vous serai éternellement reconnaissante de ce que vous
avez fait, ma tante. Vous avez agi d’une façon admirable, je ne
l’oublierai jamais ; mon affection pour vous est, si c’est possible,
encore plus vive qu’elle ne l’était auparavant.
— Ma chère enfant, j’aurais tout donné pour que ce malheur ne
fût pas arrivé. Il ne faut pas en vouloir à ton père, lui dit-elle tout
bas, il a tant de chagrin qu’il est tout hors de lui. Mais, continua-t-
elle plus haut avec une lueur d’espoir, M. Varedde reviendra peut-
être, et vous vous raccommoderez.
Suzanne, découragée, s’éloigna de quelques pas et répondit :
— Une pareille démarche serait loin de lui rendre mon estime.
— C’est un entêtement inouï ! s’écria M. Jeuffroy exaspéré, et un
monstrueux égoïsme quand je viens de te montrer tous les
désagréments que ta conduite va m’attirer. Si, après ta scène
ridicule, Varedde te faisait l’honneur de revenir à toi, tu devrais
t’estimer bien heureuse.
La jeune fille se mit à pleurer à chaudes larmes. Elle éprouvait
l’impression désolée d’un voyageur exténué, qui a passé
brusquement d’un pays charmant dans une contrée aride dont il ne
voit pas la fin. Elle était prise de vertige devant l’abîme qui la
séparait de son père, et, dans sa double déception, celle que lui
causait M. Jeuffroy était peut-être la plus cuisante. Quels que soient
les liens du sang, il est contre nature d’aimer ardemment ceux qui
ne répondent ni à votre affection ni à votre intérêt, et la tendresse
de Mlle Jeuffroy s’était refroidie en face de l’indifférence ou de
l’attitude désagréable de son père. Mais du moins, quels que fussent
ses étonnements et sa peine devant certains propos, malgré son
aversion secrète pour une existence parcimonieuse et les idées
qu’elle entendait émettre, jamais le plus léger soupçon n’avait altéré
sa confiance dans l’honorabilité de M. Jeuffroy.
Emportée par son angoisse, elle s’approcha de lui et dit d’un ton
suppliant :
— Mon père, dites-moi que M. Varedde vous a… je vous en prie,
dites que…
Mais retenue par sa pudeur filiale, épouvantée d’une pensée qui
la troublait déjà comme un remords, elle s’interrompit et s’enfuit.
— Qu’est-ce qu’il lui prend ? s’écria M. Jeuffroy au comble de
l’étonnement. Que veut-elle dire, ma sœur ?
— Je n’en sais rien ; mais ce que je sais, mon frère, répondit la
vieille fille avec énergie, c’est que tu as été dur pour elle, que tu l’as
fait pleurer, et que je ne veux pas de ça !
Et, sans attendre la réponse de M. Jeuffroy, elle partit, le laissant
chercher seul la solution du problème. Mais il pouvait d’autant moins
la découvrir que, devant la colère de sa fille contre M. Varedde, il
était resté fort convaincu qu’elle ne soupçonnait pas ses agissements
paternels.
IV

Après une nuit d’insomnie, Preymont, quand il ouvrit sa fenêtre,


salua le jour et respira l’air parfumé du matin avec l’enthousiasme
d’un être qui, par miracle, a reconquis le droit de vivre.
Il finissait de s’habiller quand Saverne entra dans sa chambre.
— Mon cher, lui dit-il, figure-toi que l’ex-fiancé est en bas et
demande à te parler immédiatement.
— Je m’y attendais, répondit Preymont avec ennui.
— Est-ce que tu consens à recevoir un pareil pied-plat ?
— Il est évident que je ne puis pas m’en dispenser, et d’ailleurs
ton expression est bien exagérée.
— Ah bien, tu es indulgent ! s’écria Saverne. J’aime à croire que
tu ne prêteras pas la main à un rapprochement ? Elle serait
malheureuse comme les pierres avec ce butor ! J’ai pensé toute la
nuit à cette admirable fille. Quelle femme, mon cher ! Ah ! il parlait
de la planter là ! eh bien, elle l’a chassé comme un valet avec une
présence d’esprit merveilleuse. Je n’ai jamais rien vu de plus
empoignant que cette jeune fille en colère tenant tête à tout le
monde, son beau visage renversé en arrière. Comprend-on qu’elle
est la fille de ce gros bonhomme, qui ressemble à une omelette
soufflée avec sa face rouge et bouffie !
— Voyons, laisse-moi descendre, répondit Preymont, en
s’efforçant de sourire et de dissimuler son inquiétude devant
l’enthousiasme de Saverne.
— Crois-tu qu’elle consente à renouer avec l’animal qui t’attend ?
— Tout est possible dans ce domaine-là, répondit froidement
Preymont.
Il écouta, avec sa mine impassible et un peu dédaigneuse, la
longue justification de M. Varedde, qui lui raconta ses impressions
dans les plus grands détails.
— Permettez-moi une question, monsieur, lui dit Preymont. Vous
n’aviez donc pas lu le contrat ?
— Si, monsieur ; mais, dans le projet que j’avais approuvé, il
n’était question que de la totalité des chiffres, et je m’étais fié à M.
Jeuffroy pour les détails. De là ma colère… bien légitime, vous
l’avouerez.
— Enfin vous n’aviez pas lu l’acte dans sa forme définitive ?
insista Preymont.
— Non… et je déplore aujourd’hui ma négligence. Mais je n’ai pas
perdu l’espoir de renouer. Puis-je espérer, monsieur, que vous
voudrez bien être mon interprète auprès de Mlle Jeuffroy ? Votre
parenté, votre intimité dans la maison, surtout la confiance que vous
inspirez à Mlle Suzanne, et que je lui ai souvent entendu exprimer,
vous donnent auprès d’elle une autorité unique. Dites-lui, je vous en
prie, mes amers regrets et mon ardent désir que sa décision ne soit
pas irrévocable. Il est impossible qu’elle reste froide devant une
démarche qui lui prouve mon attachement, en mettant à ses pieds
mon orgueil et mon juste ressentiment.
Preymont éprouvait une extrême répugnance à répondre
affirmativement. Il était si las des luttes passées, si anxieux de
l’avenir, si révolté secrètement du rôle mondain que les
circonstances lui imposaient vis-à-vis d’une femme qu’il adorait, qu’il
eût voulu rejeter loin de lui, comme une misérable défroque, les
obligations de sa situation. Mais il s’était toujours traité comme un
coursier rétif dont la soumission était pour lui une question d’amour-
propre. A chaque pas, fait dans la possession de lui-même, il avait
éprouvé un âpre plaisir à sentir qu’il devenait le maître dans sa
maison. Aussi, quels que fussent ses dégoûts, un effort de son
énergie orgueilleuse le soumettait presque toujours aux exigences
du devoir qui se présentait à lui. De plus, dans la circonstance
présente, il craignait de se trahir, car ce philosophe redoutait le
ridicule.
— Je consens, monsieur, répondit-il froidement, à répéter
textuellement vos paroles à ma cousine.
— Mais ne les approuverez-vous pas d’un mot en ma faveur ?
Preymont hésita, puis répondit nettement :
— Non… étant convaincu maintenant que ce mariage ne ferait
plus son bonheur.
— Enfin, monsieur, reprit Varedde avec impatience, puis-je
espérer que vous resterez neutre et n’influencerez pas contre moi
Mlle Suzanne ?
— Si j’accepte la mission que vous me faites l’honneur de me
confier, évidemment ce n’est pas avec l’intention de vous desservir,
répondit Preymont ironiquement. Je commencerai par exprimer
bonnement à ma cousine ce que vous-même m’avez dit, mais
ensuite mon attitude dépendra de sa réponse.
— Vos paroles ne manquent pas de sous-entendus, répondit
Varedde irrité.
— Remarquez, monsieur, que vous me demandez un service,
répliqua Preymont d’un ton sec ; je consens à vous le rendre, mais
c’est tout.
M. Varedde fut sur le point de s’emporter, mais il savait qu’une
démarche de Preymont pourrait avoir la plus heureuse influence sur
la décision de Suzanne, et il reprit avec plus de calme :
— Je ne puis, monsieur, forcer plus avant votre bienveillance.
Tarderez-vous à faire cette démarche ?
— J’y vais à l’instant, répondit Preymont avec résolution.
Ils sortirent ensemble et, à la porte de la cour, rencontrèrent
Saverne, qui voulait se donner la satisfaction de dévisager avec
impertinence M. Varedde ; mais, une autre idée lui étant venue, il
prit à part Preymont pour lui dire :
— Est-ce que tu vas en ambassadeur chez Mlle Jeuffroy ?
— Oui…
— Si j’allais avec toi ?
— En vérité, répondit Preymont impatienté, ton enthousiasme te
fait perdre toute notion des convenances. Est-ce le jour et l’heure de
lui faire une visite ?
Mais Saverne avait en tête de revoir la jeune fille le matin même,
et, après avoir déclaré que son idée n’avait pas le sens commun, il
suivit de loin son ami qui traversa rapidement la petite ville à
l’extrémité de laquelle était située la propriété de M. Jeuffroy.
Preymont espérait un peu trouver Suzanne sous les charmilles ;
mais, en approchant du parc, il la vit sortir par la porte qui donnait
accès sur la route. Elle la traversa pour descendre au bord de la
rivière, dans un endroit ombragé qui appartenait à M. Jeuffroy.
Ce fut d’un air tranquille qu’elle accueillit Preymont, bien que son
visage fatigué portât des traces de larmes récentes.
— Comment m’avez-vous découverte ici ? demanda-t-elle.
— Je vous ai vue sortir du parc au moment où moi-même
j’arrivais. Je suis content de vous trouver seule, chère Suzanne ; M.
Varedde sort de chez moi…
Elle fit un geste d’indifférence.
— Il m’a prié d’être son ambassadeur auprès de vous et…
— Que réclame-t-il ? interrompit Suzanne d’un ton ironique.
Manque-t-il quelque chose dans les cadeaux renvoyés ? J’ai
cependant surveillé moi-même l’envoi. Je ne crois pas que nous
l’ayons lésé d’une perle ou d’un chiffon.
— Ne le mettez pas si bas, répondit Preymont doucement ; il ne
pense qu’à vous, qu’à son amour perdu, et m’a prié instamment de
vous exprimer ses regrets et l’ardent espoir que vous consentirez à
renouer avec lui.
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!

ebookultra.com

You might also like