CENGAGE
Learning·
A Guide to SQL, Ninth Edition
Philip J. Pratt and Mary Z. Last
Vice President, General Manager, Social
Science & Qua litative Business: Erin Joyner
Product Director: Joe Sabatino
Product Manager: Jason Guyler
Content Developer: Wendy Langerud,
54 Carlisle
© 2015 (engage Learn ing®
WCN: 02-300
ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced, transmitted, stored, or used in any form or by
any means graphic, electronic, or mechan ica l, including but not limited to
photocopying, recording, scann ing, digit izi ng, taping, Web distribution,
information networks, or information storage and retrieval systems, except
as perm itted under Section 107 or 108 of the 1976 United States Copyright
Act, without the prior written perm ission of the publisher.
Managing Deve loper: Greg Albert
Product Assistant: Brad Su llender
Marketing Director: Michele McTighe
Senior Marketing Manager: Eric La Scola
Marketing Coordinator: Will iam Guiliani
IP Analyst: Sara Crane
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706.
For permission to use material from this text or product,
submit all requests online at www.cengage.com/permissions.
Further permissions questions can be emailed to
permissionrequest@cengage.com .
Senior IP Project Manager: Kathryn Kucharek
Manufacturing Planner: Ron Montgomery
Art and Design Direction, Production
Management, and Composition:
Lumina Datamatics, Inc.
Cover Image: © majcot/Shutterstock.com
Some of the product names and company names used in this book have
been used for identification purposes on ly and may be trademarks or
registered trademarks of their respective manufacturers and sellers.
Library of Congress Control Number: 2014951565
ISBN: 978-1-111-52727-3
Cengage Learning
20 Channel Center Street
Boston, MA 02210
USA
(engage Learning is a leading provider of custom ized learn ing solutions with
office locations around the globe, including Singapore, the United Kingdom,
Australia, Mexico, Brazil, and Japan. Locate your local office at: www.
cengage.com/global.
(engage Learning products are represented in Canada by Nelson
Education, Ltd.
To learn more about (engage Learn ing Solutions, visit www.cengage.com.
Purchase any of our products at your local college store or at our preferred
online store www.cengagebrain.com.
Microsoft Access and SQL Server are either registered trademarks or trademarks of Microsoft
Corporation in the United States an d/or other countries.
Oracle is a registered trademark, and Oracle llg is a trademark of Oracle Corporation.
The programs in this book are for instructional purposes only. They have been tested with ca re, but
are not guaranteed for any particular intent beyond educational purposes. The author and the
publisher do not offer any wa rranties or representations, nor do they accept any liabilities with
respect to the programs.
Cengage Learning, reserves the right to revise this publica tion and make changes from time to
time in its content without notice.
Printed in the United States of America
Print Number: 01
Print Year: 2014
.
P1·eface
Xl
Chapter 1 Introditction to TAL Distributors, Colonial Adventiire Toiirs,
and Solrriaris Condoniinium Grotlp
1
\\That Is a Database?
The TAL Distributors Database
The Colo11ial Adventure Tours Database
The Solmaris Condominium Group Database
Chapter Summa1y
l(e)r Tenn
Exercises
T AL Distributors
Colonial Adventure Tours
Solma.ris Co11dominium Group
Chapter 2
Database Design Fttndanientals
Data.b ase Concepts
Relatio11al Databases
Entities, Attributes, and Relationships
Functional Dependence
Prima1y l(e)'S
Data.b ase Design
Design Method
Database Design Requirements
Database Design Process Example
Normalization
First Norm al Form
Seco11d Normal Form
Third Normal Form
Diagrams for Database Design
Chapter Summar)'
l(e)r Terms
Revie,v Questions
Exercises
T AL Dist1ibutors
Colonial Adventure Tours
Solma.ris Co11dominium Group
1
2
8
14
18
18
18
18
19
19
21
22
22
23
27
30
32
32
34
34
40
40
42
46
51
54
55
55
56
56
57
58
vi
Table of Contents
Chapter 3
Crea ting Tables
59
Creating and Running SQL Commands
Using the Oracle Database llg Express Edition
Ente1ing Commands
Creating a Table
Correcting Errors in SQL Commands
Dropping a Ta.b le
Using Data T)rpes
Using Nulls
Adding Ro,vs to a Table
The INSERT Comma.n d
Inserting a Ro,v that Contains Nulls
Vie,ving Table Data
Correcting Errors in a Ta.b le
Saving SQL Commands
Creating the Remaining Database Tables
Describing a Table
Chapte r Summar)'
I(e)r Terms
Revie,v Questions
Exercises
TAL Distributors
Colonial Adventure Tours
Solma.r is Co11dominium Group
74
74
76
78
81
86
88
88
88
89
90
90
93
Single-Table Queries
97
Construc ting Simple Queries
Re trieving Certain Columns and All Ro,vs
Re trieving All Columns and All Ro,vs
Using a \\THERE Clause
Using Compound Conditions
Using the BET\.VEEN Ope rator
Using Computed Columns
Using the LIKE Operator
Using the IN Operator
Sorting
Using the ORDER BY Clause
Additional Sorting Options
Using Functions
Using the COUNT Func tion
Using the SONI Func tion
Using the AVG, 11AX, and NIIN Func tions
Using the DISTINCT Ope rator
Nesting Queries
Subqueries
97
98
99
100
102
105
106
108
110
110
111
111
112
113
113
114
115
117
118
Chapter 4
59
60
63
65
68
69
70
71
72
72
Table of Contents
Grot1ping
Using the GROUP BY Clause
Using a I-IAVING Clat1se
I-IAVING vs. \\THERE
Nulls
Summary of SQL Clat1ses, Ft1nctions, and Operators
Cl1apter Sum1nary
Ke)r Terms
Revie,v Questions
Exercises
T AL Dist1ibt1tors
Colonial Adventt1re Tours
Solmatis Condominium Grot1p
120
121
122
123
125
125
127
128
128
129
129
130
131
Multiple-Table Qiteries
133
Querying Nlttltiple Tables
Joining T,vo Tables
Comparing Joins, IN, and EXISTS
Using tl1e IN Operator
Using the EXISTS Operator
Using a Subquery Within a Subquery
A Comprel1ensive Exa1nple
Using an Alias
Joining a Table to Itself
Using a Self-Join on a Primary Key Column
Joining Several Tables
Set Operations
ALL and ANY
Special Operatio11s
Inner Join
Outer Join
Product
Chapter Summa11r
Key Terms
Revie\.v Questio11s
Exercises
T AL Dist1ibutors
Colonial Adventure Tours
Solmaris Co11domini11m Group
133
134
137
138
138
140
141
142
143
145
147
150
154
157
157
158
159
161
162
162
163
163
164
165
Chapter 5
Chapter 6
Updating Datci
Creating a Ne,v Table fro1n an Existing Table
Cl1anging Existing Data in a Table
Adding Ne,v Ro,vs to an Existing Table
Autocommit, Commit, and Rollback.
167
167
169
171
173
..
VII
viii
Table of Contents
Tra11sactions
Cl1anging and Deleting Existing Ro,vs
Executing a Rollbacl{
Changing a Value in a Column to Nt11l
Cl1anging a Table's Structt1re
Nlal{ing Complex Changes
Dropping a Table
Chapter Summa ry
Key Tenns
Revie,v Questions
Exercises
T AL Dist1ibutors
Colonial Adven tt1re Tot1rs
Solrnaris Co11dominium Grot1p
Chapter 7
Database Administration
Creating and Using Vievvs
Using a Vie,v to Update Data
UpdatiI1g Ro,v-and-Column St1bset Vie,vs
Updating Vie,vs Involving Jom s
Updating Vie,vs Involving Statistics
Dropping a Vie,v
Secttrity
Indexes
Creating an Index
Droppmg an Index
Creating Uniqt1e Indexes
System Catalog
Update of the Syste1n Catalog
Integrity Constraints in SQL
Chapter Sum1nary
Key Terms
Revievv Questions
Exercises
T AL Dist1ibutors
Colonial Adventt1re Tot1rs
Solrnaris Co11don1i11ium Grot1p
Chapter 8
SQL Fiinctions and Proceclures
Using SQL in a Programming Environ1nent
Using Ft1nc tions
Cl1aracter Ft1nc tions
Nt1mber Func tions
\Vorking ,vitl1 Dates
174
174
176
177
179
185
185
187
187
187
188
188
189
190
191
191
198
199
200
203
203
204
207
210
211
212
212
214
215
219
220
220
221
221
223
225
227
227
228
229
230
231
Table of Contents
Concatenating Col11mns
Stored Procedures
Retrieving a. Single Ro,v and Column
En·or I-Iandling
Using Update Procedures
Changing Data ,vith a Procedt1re
Dele ting Data \Vith a Procedt1re
Selecting N1ultiple Ro,vs ,vith a Procedure
Using a Cursor
Opening a Cursor
Fetchi.t1g Ro,vs from a Cursor
Closing a Cursor
vVriting a Complete Procedi1re Using a Ct1rsor
Using ti1Io re Complex Cursors
Advantages of Cttrsors
Using T-SQL in SQL Server
Re t1ieving a. Single Row and Column
Chru1ging Data \Vith a Stored Procedure
Deleting Data 'vVith a Stored Procedure
Using a Cursor
Using More Complex Cursors
Using SQL in ti1icrosoft Access
Deleting Data "vvith Visi1al Basic
Running the Code
Updating Data ,vith Visual Basic
Inserting Data ,vith Visual Basic
Finding N1ultiple Ro"vvs \Vith Visual Basic
Using a Trigger
Chapter Summary
l(e)r Terms
Revie\v Questions
Exercises
T AL Dist1ibt1tors
Colonial Adventure Tours
Solmaris Co11dominh1m Group
Appendix A
SQL Reference
Aliases
ALTER TABLE
Column or Expression List (SELECT Clause)
Computed Colt1mns
Tl1e DISTINCT Operator
Functions
CONIMIT
233
235
235
238
239
239
240
241
242
243
243
245
245
247
248
248
249
249
250
250
251
252
252
253
254
255
255
257
260
261
261
262
262
264
265
267
267
267
268
268
268
269
269
.
IX
x
Table of Contents
Conditions
Simple Conditions
Compot1nd Conditions
BET\VEEN Conditions
LIKE Conditions
IN Conditions
EXISTS Conditions
ALL and ANY
CREATE INDEX
CREATE TABLE
CREATE VIE\V
Data Types
DELETE RO\,VS
DESCRIBE
DROP INDEX
DROP TABLE
DROP VIE\V
GRANT
INSERT INTO (Query)
INSERT INTO (Values)
Integrity
REVOl<E
ROLLBACK
SELECT
St1bqt1eries
UNION, INTERSECT, and MINUS
UPDATE
269
269
270
270
270
271
271
271
272
272
273
274
275
275
275
276
276
276
277
277
278
279
279
280
280
281
282
Appe11di~ B
How Do I Reference
283
Appe11di~ C
Answers to Odd-Niimberecl Review Qitestions
287
Cl1apter l-Introdt1ction to TAL Dist1ibutors, Colonial Adventt1re Tot1rs, and
Solma1is Condomi11ium Grot1p
Cl1apter 2-Database Design Ft1ndamentals
Cl1apter 3-Creatil1g Tables
Cl1apter 4-Single-Table Queries
Cl1apter 5-Nltiltiple-Table Queries
Chapter 6-Updating Data
Cl1apter 7-Database Administratio11
Cl1apter 8-SQL Fu11ctions and Procedures
287
287
289
289
290
290
291
291
Index
293
St1uctt1red Query Language (or SQL, \.vhich is pronounced "se-qt1el," or "ess-ct1e-ell")
is a popular con1pt1ter language that is used by diverse groups such as hon1e con1puter t1sers, owners of sn1all bt1sinesses, end u sers in large organizations, and progranm1ers. Although this text uses the SQL in1plen1entation in the Oracle Database
llg Ex press Edition as a vehicle for teaching SQL, its chapter n1aterial, exan1ples,
and exercises can be con1pleted using an)' SQL implen1entation.
A Guide to SQL, Ninth Edition is \Vritten for a \.Vide range of teaching levels, fron1
s tudents talting introductory con1puter science c lasses to those stt1dents in advanced
inforn1ation systen1s classes. This text can be t1sed for a standalone course on SQL
or in conjunction \.Vith a database concepts text \vhere students are reqt1ired to
learn SQL.
The chapters in this text should be covered in order. Students shot1ld con1plete
the e11d-of-chapter exercises and the examples \Vithin the chapters for n1axin1un1
learning. Becat1se the content of Chapter 8 asst1mes that the reader has had instrt1ction or experience in at least one programn1ing language , tl1e ins t1uctor should detern1ine \vhether students \vill understand its concepts. Stt1dents \.Vithout a progranmling
bacl{ground \.vill l1ave diffict1lty understanding the topic of en1bedded SQL. Instructors
can easily onlit Chapter 8 fron1 the text in situations where stt1dents are not con1fortable \.Vith progranm1ing exan1ples.
The Ninth Edition bt1ilds on the success of previous editions by presenting basic
SQL con1mands in tl1e context of a business that uses SQL to n1anage orders, iten1s,
custon1ers, and sales reps. Lil{e in previous editions, this edition uses Oracle as the
vehicle to present SQL commands. Lil{e the last edition, this edition addresses SQL in
Access™ by sho\ving the Access versions of the san1e conm1a11ds when tl1ey differ
fron1 the Oracle versions. This edition also sho\.v s SQL Server con1mands \vhen they
differ fron1 the Oracle versions. Differences for Access and SQL Server users are featured in "User" notes, \.vhich n1ake it easy for stt1dents to identify differences for the
SQL in1plementation they are using. Students can do\vnload the Oracle llg Database
Express Edition fron1 the Oracle \Veb site for free and t1se it to con1plete this text
\.Vithout having to pt1rchase or install the ft1ll Oracle progra111.
The Ninth Edition includes an entire chapter on database desig11, showing students how to create an appropriate design that satisfies a given set of reqt1iren1e11ts,
and inclt1des coverage of the in1portant topics of stored procedt1res and triggers. The
text also contains t1pdated case problen1s that feature a distributor of toys, an ot1tdoor
adventure con1pan)', and a condominiun1 n1anagen1ent con1pany.
xii
Preface
DISTINGUISHING FEATURES
Use of Examples
Each chapter contains n1ultiple exan1ples that use SQL to solve a problen1. Follo,vi11g
each exan1ple , stt1dents will read about the conm1ands that are used to solve the
stated problen1, and then they \.vill see the SQL conm1ands used to arrive at the solt1tion. For n1ost stt1dents, learning through exan1ples is the n1os t effective \.Va)7 to n1aster n1aterial. For this reason, instrt1ctors should encourage students to read the
chapters at the con1puter and input the conm1ands sho\.v n in the figures.
Case Studies
A running case s tudy-T AL Distributors-is presented in all of the examples
within tl1e cl1apters and in the first se t of exercises at tl1e end of each cl1apter.
Although tl1e database is small in order to b e manageable, the examples and exercises for tl1e TAL Distributors database s imulate what a real business can accomplisl1 u sing SQL comma11ds. Using tl1e san1e case study as examples witl1in tl1e
chapter and in tl1e end-of-cl1apter exercises ensures a l1igh level of co11tinuity to
reinforce learning.
A second case study-tl1e Colonial Adventure Tours database-is used in a second se t of exercises at the end of each chapter. A third case study-tl1e Sohnaris
Condominium Grot1p database-is u sed in a third se t of exercises at tl1e end of eacl1
chapter. The second and tllird case s tudies give students a cl1ance to venture out "on
tl1eir own" without tl1e direct gt1idance of examples from tl1e text.
Question and Answer Sections
A special type of exercise, called a Q&A, is used tl1roughout the bool{. These exercises force stt1dents to consider special issues and understa11d important qt1estions
before continuing ,vith their stt1dy. The ans\.ver to each Q&A appears after the
question. Students are encouraged to formulate their own ans\.vers before reading
tl1e ones provided in the text to ensure tl1at the)7 t1nders tand new material before
proceeding.
"User'' Notes for Access™ and SQL Server Users
When an SQL conm1and has a different use or forn1at in Access or SQL Server, it
appears in a User note. \Vhen you encounter a User note for the SQL in1plen1entation
you are using, be sure to read its contents. You n1ight also revie,v the User notes for
other SQL in1plen1entations so you are a,vare of the differences that occur fron1 one
in1plen1entation of SQL to anotl1er.
Review Material
A Sun1mary and l{ey Terms list appear at the end of each chapter, followed by
Revie\.V Questions that test students' recall of tl1e in1portant points in the cl1apter and
occasionally test their ability to apply \.Vl1at tl1ey have learned. The answers to tl1e
Preface
odd-nu1nbered Revievv Questions are provided i11 Appendi,"'{ C. Each chapter also
contains exercises related to the TAL Distributors, Colonial Adventure Tours, and
Solmaris Condominium Group databases. Critical -thinlting questions that reinforce
problem-solving a11d analytical sliills are included for review qi1estions and hands-on
•
exercises.
Appendices
Tl1ree appendices appear at the end of tllis text. Appendix A is an SQL reference tl1at
describes tl1e purpose and syntax for the major SQL commands featured in the text.
Students can use Appendix A to ide11tif)r l1ovv and when to use importa11t commands
quick.I.)'. Tl1e SQL reference appendix contains references to specific pages in the text
,vhere the command is discussed to malie it easy for students to fu1d additional
information when tl1e)7 need to refer bacl{ to tl1e section it1 tl1e bool{ ,vhere the topic
is covered.
Appendix B includes a "Hovv Do I" reference, whicl1 lets s tudents cross-reference
tl1e appropriate sectio11 it1 Appendix A b)7 searcl1ing for the ans,ver to a questio11.
Appendix C includes a11s,vers to the odd-numbered Revie,v Questions.
Relationship to Concepts of Database Management, Eighth Edition
For database cot1rses featuring SQL, this SQL text can be bu11dled with Concepts
of Dcitcibase Mcinagement, Eighth Edition by Pratt and Last ( Cengage Learning).
Tl1e data a11d pedagogy between tl1e tvvo texts is consistent, and tl1e i11structor 's
manuals for both boolis include feedbacli and suggestions for using tl1e texts
togetl1er .
Instructor Support
The Ninth Edition includes a pacliage of proven supple1nents for instructors a.n d
students. The Instructor's Resources offer a detailed e lectronic I11structor's Manual,
figure files, Microsoft®PowerPoint®presentations, and the Cognero Test Ba.n li. The
Instructor's Manual includes suggestions and strategies for u sing this text, as well as
ansvvers to Review Questions a11d solutions to the end-of-chapter exercises. Figure
files allow instructors to create their ovvn presentations t1sing figures appearing in
the text. Instructors can also talie advantage of lecture prese ntations provided on
PovverPoint slides; these presentations follow each chapter's coverage precisely,
include chapter figures, and ca11 be customized.
The I11s tructor's Resources include copies of the databases for the TAL Distributors, Colonial Adventure Tours, and Solmaris Condomi11ium Group cases in
Microsoft Access 2010/2013 format a11d script files to create the tables a11d data in
these databases i11 Oracle a.n d SQL Server. These files are provided so ins tructors
have the choice of assigning exercises in \\l'hich students create the databases used
in this text and load them vvith data, or they can provide the s tarting Access databases or Oracle or SQL Server script files to s tudents to automate and simplify
these tasl{s.
...
XII I
xiv
Preface
ORGANIZATION OF THE TEXT
Tl1e text contains eight chapters and three appendices, ,vhich are described in the
following sections.
Chapter 1: Introduction to TAL Distributors, Colonial Adventure Tours,
and Solmaris Condominium Group
Chapter 1 i11trodt1ces tl1e three database cases tl1at are u sed tl1rougl1ot1t tl1e text : T AL
Dist1ibutors, Colonial Adventure Tours, and Solmaris Condominiun1 Group. Many
Q&A exercises are provided tl1roughout the cl1apter to enst1re tl1at s tudents understand l1ow to manipulate the database on paper before tl1e)' begin ,vorlting in SQL.
Chapter 2: Database Design Fundamentals
Cl1apter 2 covers important concepts a11d terminology associated ,vitl1 relational
databases, functional dependence, and primary l{eys, follo,ved by a method for
designing a database to satisfy a given set of reqt1irements. It also illustrates the normalization process for finding and correcting a variety of potential problems in database designs. Finally, it shows how to represent database designs graphically using
entity-relationship diagrams.
Chapter 3: Creating Tables
In Chapter 3 , students begin t1sing a DBMS by creating and running SQL con1mands
to create tables, ttse data types, and add ro,vs to tables. Chapter 3 also discusses the
role of and use of nulls.
Chapter 4: Single-Table Queries
Chapter 4 is tl1e first of t,vo chapters on using SQL commands to query a database.
Tl1e queries in Cl1apter 4 all involve single tables. Included in tl1is chapter are disct1ssions of simple and compound conditions; computed columns; tl1e SQL
BETVlEEN, LIIIB, and IN operators; using SQL aggregate functions; nesting queries;
grouping data; and retrieving columns witl1 null valt1es.
Chapter 5: Multiple-Table Queries
Cl1apter 5 completes the disct1ssion of qt1erying a database by demonstrating queries
that join more tl1an one table. Included in this chapter are disct1ssions of the SQL IN
and EXISTS operators, nested subqueries, t1sing aliases, joining a table to itself, SQL
set operations, a11d the use of the ALL and ANY operators. The chapter also inclt1des
coverage of variot1s types of joins.
Chapter 6: Updating Data
In Chapter 6 , students learn how to use the SQL COMMIT, ROLLBACI<, UPDATE,
INSERT , and DELETE conm1ands to update table data. Students also learn ho,v to
Preface
create a new table from an existing table and how to change the structure of a table.
The chapter a lso includes coverage of transac tions, including both their purpose and
implementation.
Chapter 7: Database Administration
Cl1apter 7 covers the database ad1ninistration featt1res of SQL, i11cluding the use of
views; granti11g and revolting database privileges to users; creating, dropping, and
using an index; ttsing and obtai11ing information from tl1e system catalog; and usi11g
integrity constrai11ts to control data entry.
Chapter 8: SQL Functions and Procedures
Cl1apter 8 begi11s witl1 a discussion of some in1portant SQL ft1nctions that act on single ro\vs. Students will also learn 110\v to use PL/SQL and T-SQL to cover tl1e process
of embedding SQL commands in anotl1er language. Included in this cl1apter are discussions of ttsing embedded SQL to insert ne\.v rows and cl1a11ge and delete existing
rows. Also included is a discussion of how to retrie\re single ro\vs using embedded
SQL commands and ho\.V to use ct1rsors to retrieve multiple rows. Cl1apter 8 also
includes a section sho\ving some techniques for using SQL in Vist1al Basic (Access).
The cl1apter concludes \,Vith a disct1ssion of triggers.
Appendix A: SQL Reference
Appendix A includes a comn1and reference for all the major SQL clauses and operators that are featured in the chapters. Students ca.n use AppendL~ A as a quicl{
resource \vhen constructing commands. Each command includes a short description,
a table that shows the required a.n d optional clauses and operators, and a11 example
and its results. It also contains a reference to the pages in the text where the command is covered.
Appendix B: How Do I Reference
Appendix B provides students with an opportunit)7 to asl{ a question, sucl1 as "Ho\v do
I delete ro\.vs?" and to identif)7 the appropriate section in Appendix A to u se to fi11d
tl1e ans\.ver. Appendix B is extremel)7 valuable \Vl1en students kno\.v \.vhat tasl{ tl1ey
\Vant to accomplisl1 but can't re1ne1nber tl1e exact SQL command the)7 need.
Appendix C: Answers to Odd-Numbered Review Questions
Ans\,vers to the odd-numbered Revie"v Questions in eacl1 chapter appear in tl1is appendix so stude11ts can mal{e st1re tl1at they are completing the Re\riew Questions correctly.
GENERAL NOTES TO THE STUDENT
1.
Yott can download tl1e databases tised in this text from www.cengage.com.
Use your bro\vser to go to W\VW.CengageBrai11.com.
xv
xvi
Preface
2.
3.
Tl1e first time yot1 go to tl1e site, yot1 \>Vill need to register. It's free. Clicl{ on
"Sign Up" in tl1e top rigl1t co rner of tl1e page and fill out tl1e registration
information . (After yot1 l1ave signed ill once, \Vhenever yot1 re tt1r11 to
CengageBrain, yot1 \>Vill ente r the t1ser name and password yot1 have chosen
a11d yot1 will be tal{en directly to tl1e companion site for yot1r bool{.)
011ce you have registered a11d logged in fo r the fil·st time, go to tl1e "Searcl1
for Bool{s o r Materials" bar a11d e11te r tl1e autl1o r or ISBN for your textbook .
\i\Then tl1e title of your text appears, clicl{ on it a11d you will be tal{e n to the
companio11 site. The re you can cl1oose among tl1e various folders provided
on the Stude11t side of tl1e site. NOTE: If you are curre11tly usil1g 1nore tha11
one Ce11gage textbool{, tl1e san1e user na111e a11d pass\>\7ord "''ill give you access
to all tl1e compa11ion sites for your Cengage titles. After you l1ave ente red the
i11formation for each title, all tl1e titles you are using \>Vill appear listed i11 tl1e
pull-do,,,11 menu in the "Search for Bool{s o r Nlate rials" bar. ,,T11e11ever you
retur11 to CengageBrail1, you cat1 clicl{ on the title of tl1e site you ,vish to visit
and go directly tl1ere.
The script files sa,,ed i11 tl1e Oracle folder have the follo,vi11g functio11s:
OracleSolmaris.sql: Creates all tl1e tables in the Solma ris Condo n1i11iu1n Group
database a11d adds all the data. Ru11 tllis sctipt file to create tl1e Sol111aris Co11do1niniu111 Group database. (Note: This script file assumes you l1ave 11ot previously
cre ated a11y of the tables ill tl1e database. If you have c reated a11y of the
tables, you should ru11 the OracleDropSohna ris.sql script prio r to ru1111ing tl1e
OracleSolmaris.sql script.)
OracleColonial.sql: Creates all the tables ill tl1e Colonial Adventure Tours da tabase a11d adds all the data. Ru11 tlus script file to create tl1e Colonial Adventure
Tours database. (Note: Tllis script file assumes you l1ave no t previously c reated
any of tl1e tables in the database. If you have created any of tl1e tables,
you should run the OracleDropColo11ial.sql script prior to ru1111ing tl1e
Oracle Colo11ial.sql script.)
OracleTAL.sql: Creates all tl1e tables in the TAL Distributors database and adds
all tlle da ta . Ru11 this script file to c reate tl1e TAL Distributors da tabase.
(No te: This script file assu111es you l1ave not previously created ai1y of the tables
i11 the database. If you l1ave created ai1y of tl1e ta bles, you sl1ould run the
OracleDropTAL.sql script prio r to ru1u1il1g tl1e OracleTAL.sql script.)
OracleDropSolmaris.sql: Drops (dele tes) all tl1e tables and data in the So1mai·is
Co ndon1i11ium Group database.
OracleDropColonial.sql: Drops (deletes) all the ta bles and data i11 tl1e Colo11ial
Adve11ture Tours database.
OracleDropTAL.sql: Drops (deletes) all tl1e tables a11d data ill tl1e TAL Distributors
database.
Preface
The script files saved in the SQL Server folder have the following functions:
SQLServerSolmaris.sql: Creates all the tables in tl1e Solmaris Condomini11m
Grottp database and adds all tl1e data. Rttn tl1is script file to create the Solmaris
Condomi11it1m Grottp database. (Note: 'fl1is script file asst1mes yott l1ave not previottsly created any of the tables in the database. If yott have created any of tl1e
tables, yott shottld rt111 tl1e SQLServerDropSolmaris.sql script prior to n1nning tl1e
SQLServerSolmaris.sql sc1ipt.)
SQLServerColonial.sql: Creates all tl1e tables in tl1e Colonial Adve11tt1re 'fottrs
database and adds all the data. Rttn tl1is script file to c reate the Colonial
Adventttre Tottrs database. (Note: This script file assttmes yott h ave not previottsly
created any of the ta.h ies in the database. If yott have created any of the tables,
yott shottld rttn the SQLServerDropColonial.sql script prior to rttnning the
SQLServerColonial.sql script.)
SQLServerTAL.sql: Creates all tl1e tables in the TAL Distribtttors database and
adds all tl1e data. Run this script file to create the TAL Distribtttors database.
(Note: 'flus script file assttmes yott have 11ot previot1sly created any of the tables
in tl1e database. If yott l1ave created any of the tables, yott shottld rttn the
SQLServerDropTAL.sql script prior to rt1nni11g the SQLServerTAL.sql script.)
SQLServerDropSolmaris.sql: Drops (deletes) all the tables a11d data in the
Solmaris Condominittm Grottp database.
SQLServerDropColonial.sql: Drops (dele tes) all tl1e tables and data in the
Colonial Adve11tt1re 'f ottrs database.
SQLServerDropT;\L.sql: Drops (dele tes) all the tables and data in the TAL
Distribtttors database.
For details on running script files in Oracle or SQL Server, checl{ ,vith your
instructor. You ca.n also refer to Chapter 3 in the text for information about creating
and u sing scripts.
For information about downloading the Oracle Database llg Express Edition software, please visit the Oracle \Veb site. For information about SQL Server Express,
please visit the Microsoft Web site. Information about Microsoft Access is also available
at the Microsoft Web site.
Embedded Questions
In 1na11y places, )7ou'll find Q&A sectio11s to enst1re that )70u understand some crucial
material before you proceed. In some cases, the questio11s are desig11ed to give )70u
tl1e cha.n ee to consider some special concept in advance of its actual presentation.
In a ll cases, tl1e answer to eacl1 question appears immediately after the question.
You can silnpl)7 read tl1e qt1estion and its ans,ver, bttt )70u ,vill benefit from taking
time to detennine the ans,ver to tl1e question before checlti11g )7our a11s"ver agai11st
tl1e one given in the text.
..
XVII
xviii
Preface
End-of-Chapter Material
Tl1e e11d-of-cl1apter material co11sists of a Sum111ary, a l(ey Ter1ns list, Review Questions, and exercises for tl1e TAL Distributors, Colo11ial Adve11ture Tours, ru1d Solmaris
Co11do111inium Group databases. Tl1e Su111111ary briefly describes tl1e material covered
in tl1e chapter. The Review Questions require you to recall and apply tl1e in1porta11t
111aterial in tl1e cl1apter. Tl1e answers to tl1e odd-11umbered Re,,iew Questions appear
in Appendix C so you ca11 cl1ecl{ your progress. The TAL Distributors, Colonial
Adventure Tours, ru1d Solmaris Condo1ni11ium Group exercises test your lu10\-vledge of
tl1e chapter material; your i11structor \-Vill assign 011e or more of these exercises for
you to co111plete. Critical-thinking questions tl1at reinforce problem-sol,,u1g and analytical skills are i11cluded for revie,v questions and ha11ds-on exercises.
ACKNOWLEDGMENTS
\\Te ,vould lil{e to acl{nowledge several individuals for their contributions in the prep-
aration of this text. The efforts of the follo,ving m embers of the staff at Cengage
Leaming have been invaluable a.n d have made trus text possible: Joe Sabati110 , Product Director; Jason Guyler Product Manager; Wendy Langerued, Content Developer;
Arul Joseph Raj , Project Ma.n age r ; and GreenPen Qual ity Assura.n ce testers.
\\Te have once again had the great pleasure to worl{ \-Vith a.n absolutely ama.z ing
Developmental Editor, Jessica Evans, 011 several boolIB. Tha.n lIB for a.11 your efforts,
Jess. You're the best! V\Te've said it before, but it is just as true as ever!
C H A PTER
INTRODUCTION TOTAL
DISTRIBUTORS, COLONIAL
ADVENTURETOURS,AND
SOLMARIS CONDOMINIUM
GROUP
OBJECTIVES
•
Introduce TAL Distributors, a company whose database is used as the
basis for many of t he examples throughout the text
•
Introduce Colonial Adventure Tours, a company whose database is used
as a case that runs throughout the text
•
Introduce Solmaris Condominium Group, a company whose database is
used as an additional case that runs throughout the text
INTRODUCTION
In this chapter, you will examine the database requirements of TAL Distributors, a company that will
be used in the examples throughout the text. Then you will examine the database req uirements for
Colonial Adventure Tours and Solmaris Condom inium Group, whose databases are featured in the
exercises that appear at the end of each chapter.
WHAT IS A DATABASE?
Tl1r oi1ghout tllis text, yoi1 will worl{ witl1 databases for tlnee organizations: TAL Disttibutors,
Colonial Adve11ture Tours, and Solmaris Condominii1m Grot1p. A database is a strt1cture tha t
contains different categories of information and the relationsllips between these categories.
Tl1e TAL Distribt1tors database, for example, contai11s information aboi1t categories s11cl1 as
Chapter 1
sales represe11tatives (sales reps), c11stomers, orders, and items. The Colonial Adventt1re
Tot1rs d atabase contai.t1s information abo11t categories s11ch as trips, g11ides, customers, and
reservations. The Solmaris Co11domini11m Grottp database contai.t1s infor1nation abo11t categories sttch as condominittms, condo ttnits, condo o\.vners, service categories, and service
req11ests.
Eacl1 da tabase also conta ins rela tionsl1ips behveen ca tegories. For example,
tl1e TAL Distribtttors d a tab ase contains informa tion tl1at re la tes sales reps to the
c11s to me rs tl1ey represent a11d customers to tl1e orders tl1ey l1ave placed . The Colo11ial
Advent11re Tours database conta i11s informa tion tha t rela tes c11s tome rs to the
reservations they ma.l{e and g11ides to the trips they lead . 'fl1e Solmaris Condominittm
Grottp d atabase co11tains i11formation tl1at relates the condo units in eacl1 condo
loca tion to the ir O\vne rs.
As yo11 worl{ tl1rougl1 tl1e cl1apters in this text, yott \\Till learn more abo11t tl1ese databases and 110\v to v ie\.\T and ttpdate tl1e ituormation tl1ey contain. As yo11 read eacl1 c hapte r, yott \\Till see examples from tl1e TAL Distrib11tors d atabase. At the end of eacl1 cl1apter ,
your ins tr11c tor 1night assign the exe rcises for tl1e TAL Dis tributors, Colo11ial Advent11re
To11rs, or Sol1naris Condo1nini11m Group da tabases.
THE TAL DISTRIBUTORS DATABASE
Tl1e ma nagement of TAL Distributors, a wl1olesaler of finely c rafted wooden toys, games,
and puzzles, has de termi11ed tha t tl1e company's recent growtl1 no lo11ger m akes it feasible
to mait1tain c11stome r, order , and inve ntory da ta 11s i11g its ma11ual systems. \Vitl1 tl1e d ata
stored in a d atabase, ma.nagen1ent \.Vill be able to ensure that tl1e d at a is ttp to d ate a11d
1nore accttra te thai1 i11 the c11rrent 1nan11al systems. In addition , 1nanagers \\Till be able to
obtain ans\vers to tl1eit· q11esti o11s concerning tl1e dat a in the database easily a11d q1.1ickly,
with tl1e option of prod11cing a vai·ie ty of 11seft1l r epo rts.
Ma11ageme11t l1as de termined tl1at T AL Dis tribtttors m11s t maintait1 tl1e follo\.ving infor1natio11 about its sales reps, custome rs, and inventory it1 tl1e new d atabase:
•
•
•
Tl1e n111nber , last name, fu·st naine, address, to tal commission , and commission rate for eacl1 sales rep
Tl1e cus tomer 11umber , na1ne, address, current balance, and credit li1nit for
each cus ton1er , as \Veil as the n11mbe r of tl1e sales rep wl10 represe11ts the
customer
Tl1e item n11mber , description , nttmber of units on ha11d, category, nttmbe r of
tl1e s torel1011se wl1ere the item is stored, a11d ttnit price fo r each item in
inventory
TAL Dis tributors also m11s t sto re ituo rma tion abo11t orders. Figure 1-1 shows a sa1nple
o rder .
Introduction to TAL Distributors, Colon ial Adventure Tours, and Solmaris Condominium Group
INVOICE
T AL D istributors
555 Main Street
San Rita, TX 78364
Phone ( 512) 555-0 190 Fax (512) 555-0 19 1
ORDER: 5 16 10
DATE: October 12, 20 15
TO:
SALES REP: 45
Hui Tian
CUSTOMER: 334
TI1e Everything Shop
342 Magee St.
Congaree, CA 90097
ITEM
NUMBER
{ KL78
TR40
Order lines
DESCRIPTION
NUMBER
ORDERED
PRICE
TOTAL
Pick Up Sticks
25
10.95
~273. 75
Tic Tac Toe
10
13.99
~
139. 90
Extensions
Body
.TOTAL
413.65
Footing
J\1ake aU checks payable to T AL Distributors
Total due in 15 days. Overdue accounts subject to a service charge of 1% per n1onth .
Tha11k you for your bus iuess!
FIGURE 1-1
Sample order
Tl1e sample order shown i11 Fig11re 1-1 has three sectio11s:
•
•
•
Tl1e heading (top) of the orde r contains the company 11a me ; the order 1111mber and date; tl1e c11stomer 's number, name , a11d address; and tl1e sales rep's
n11mber and name .
Tl1e body of tl1e order co11tai11s 011e or more order lines, sometimes called
line items. Eacl1 orde r li11e co11tains a11 item 1111mber , an ite1n description , tl1e
number of u11its of the item orde red , a11d the q11oted price for tl1e item . Eacl1
order line also co11tains a to tal, 11sually called an extension , \.Vllicl1 is the
res11lt of m11ltiplying tl1e n11mber ordered by tl1e q11oted price.
Finally, the footing (bottom) of tl1e order contai11s the order total.
Chapter 1
TAL Distrib11tors also m11st store the follo,ving items in the database for eacl1
customer's o rder :
•
•
For each o rde r, tl1e database 1n11st store tl1e o rder n11mber, the date tl1e order
was placed, and the n11mber of tl1e c11stomer tl1at placed tl1e order . Tl1e customer's name and address and tl1e number of tl1e sales rep \vho represents
tl1e custome r are stored ,vith the c11stomer information . The name of tl1e
sales rep is sto red witl1 tl1e sales rep infor1natio11.
For eacl1 order, tl1e database must store tl1e order n11mber, tl1e item n11mber ,
tl1e n11mber of units ordered , and the q11oted price for eacl1 order line. Tl1e
ite1n description is sto red ,vitl1 the information about items. The res11lt of
m11ltiplyi11g tl1e n11mber of 1111its ordered by tl1e q11oted price is not sto red
beca11se the database can calc11late it \Vhen needed.
Tl1e overall o rder to tal is not stored . Instead, tl1e database calc11lates tl1e total ,vl1enever an orde r is pri11ted o r displayed on tl1e screen .
Fig11re 1-2 sl10\vs sample data for T AL Distri b11tors.
REP
REP_NUM
LAST_NAME
FIRST _NAME STREET
15
30
45
60
Can1pos
Gradey
Tian
Sefton
Rafael
~legan
Ilui
.laneL
CITY
724 Vi nca Dr. (1rove
632 Liatris St. Fullton
1785 Tyler Ave. Northfield
267 Oakley St. Congaree
STATE
POSTAL_CODE
CA
CA
90092
90085
90098
90097
CA
CA
COMMISSION
RATE
$23,457.5()
$41,317.00
$27,789.25
$0.00
0.06
0.08
0.06
0.06
CUSTOMER
CUSTOMER_NUM CUSTOMER_NAME STREET
CITY
STATE
POSTAL_CODE
BALANCE CREDIT_LIMIT REP _NUM
126
Toys G::ilore
28 Laketon St.
F'uUton
CA
90085
$1,210.25
$7,500.00 15
260
Brookings Direct
452 Columbus Dr. Grove
C.\
90092
$575.00
334
The Everything
Shop
342 ~la.gee St.
Congaree
CA
90097
$? ,34-'. ~.,.:,
..
$10,000.00 30
$7,500.00 ,15
386
Johnson's
Department
Store
124 }.Jain St.
Northfield CA
90098
$879.25
$7,500.00 30
440
3456 Central Ave. Pullton
CA
90085
$345.00
$5,000.00 45
167 Ilale St.
/\lesa
CA
90104
$5,025.75
$5,000.00 15
33-lS Devon Ave.
Almondton CA
90125
$3,-156.75
$15,000.00 45
665
713
796
Grove
llistorical
.illuseum Store
Cards and 11ore
Almond ton
General Store
Cricket Gift Shop
Cress Store
Unique Gifts
Grove
CA
12 Rising Sun Ave. Congayee CA
786 Passmore St. Northfield CA
90092
90097
90098
$678.90
$4,234.60
$124.75
$7,500.00 30
$10,000. (J() 15
$7,500.00 45
82-l
l B93
Kline's
~\II Season Gifts
945 Gilh:-in, St.
/\lcs:-i
382 \Vild,vood Ave. Fullton
90104
90085
$2,-175.99
$935.75
$15,000.00 ~o
$7,500.00 15
-o-,-
;:,
586
FIGURE 1-2
J 72 Oxford St.
Sample data for T AL Distributors
CA
CA
Introduction to TA L Distributors, Colonial Adventure Tours, and Solmaris Condominium Group
ORDER_LINE
ORDERS
ORDER_NUM
ORDER_DATE CUSTOMER_NUM
10/12/2015 126
10/12/2015 33-1
10/13/2015 386
51608
51610
51613
51617
51619
10/13/2015 260
10/15/2015 586
10/15/2015 126
51623
51625
10/15/2015 586
10/16/2015 796
5161-1-
ORDER _NUM
ITEM_NUM
51608
CD33
:,
$86.99
51610
l(L78
25
51610
5 16 13
'fR40
10
DL51
51614
FDll
:NL89
5
1
$10.95
$13.99
$104.95
$124.95
-1
T\,'35
3
51619
5]623
FDll
DR67
2
51623
5]623
FI-124
1(034
12
1()
51625
~•1T03
8
51617
51617
NUM_ORDERED QUOTED_PRICE
-
-
::,
$115.99
$116.95
$121.95
$29.95
$36.95
$13.10
$45.79
ITEM
ITEM_NUM
DESCRIPTION
All74
Patience
BR23
CD33
STOREHOUSE
PRICE
9 Gi\1E
3
$22.99
Skittles
21 G.l\1E
2
$29.99
36 TOY
]
$89.49
DL51
'''ood Block Set ( 48 piece)
Classic Raihvay Set
12 TOY
3
$107.95
DR67
Giant Star Brain 1'easer
24 PZL
2
$31.95
D\V23
11ancala
40 Gl\lE
3
$50.00
FDl l
Rocking Ilorse
B TOY
3
$124.95
Fil2-I-
Puzzle Gift Set
65 PZL
1
$38.95
Jv\12
Cribbage Set
56 G1lE
3
$75.00
I<DJ4
J(L78
Pcnto1n inocs Brain Teaser
60 PZL
2
$14.95
Pick Up Sticks
110 GJ\i1E
l
$10.95
J\i1T03
Zauberkasten Brain Teaser
1
$45.79
NL89
" 'ood Block Set (62 piece)
45 PZL
32 1'0Y
3
$1 19.75
'l'R.40
1'ic 'lac 'l'oc
75 GivIE
2
$13.99
T\V35
Fire Engine
30 TOY
2
$118.95
FIGURE 1-2
ON_HAND CATEGORY
Sample data for TAL Distributors (continued)
l11 tl1e REP table, yo1.1 see tl1at there are fo1.1r reps, wl1ose 111.1mbers are 15, 30, 45, and
60. The 11ame of sales rep 15 is Rafael Campos. His s treet address is 724 Vinca Dr. He
lives i11 Grove, C~\ , and l1is postal code is 90092. His total con1missio11 is $23,457.50, and
his comn1issio11 rate is 0.06 (six percent).
l11 tl1e CUSTONIER table, 12 TAL Distributors customers are identified \.Vitl1 tl1e n1.1mbers 126, 260, 334, 386, 440, 502, 586, 665, 713, 796, 824, and 893. The name of ct1stomer nun1ber 126 is Toys Galore. This c1.1sto1ner's address is 28 Lalleto11 St. in Ft1llto11,
CA, vvith a postal code of 90085. The customer's cu rrent balance is $ 1,2 10.25, and its
credit litnit is $ 7,500.00. Tl1e n1.1mber 15 iI1 the REP_NUM col1.11nn i11dicates that Toys
Galore is represented by sales rep 15 (Rafael Campos).
Chapter 1
Sl<.ipping to the table named ITENI, yo11 see that there are 15 items, whose item n11mbers are AH74, BR23, CD33, DL51, DR67, D\¥23, FDll, FH24, Iv\12, Iill34, l(L78, MT03,
NL89, TR40, and T\\T35. Item AH74 is Patie11ce, and TAL Distrib11tors l1as nine 11nits of
tl1is item on hand. The Patience iten1 is in the G11E (games) category, and is located in
storel1011se 3. Tl1e price of tl1e Patience game is $22.99. Otl1er categories are PZL (pt1zzles) and TOY (toys).
Nloving bacl<. to tl1e table named ORDERS, yo11 see that tl1ere are eigl1t orders, which
are identified \Vitl1 tl1e numbers 51608, 51610, 51613, 51614, 51617, 51619, 51623, ai1d
51625. Order number 51608 \Vas placed on October 12 , 2015, by c11ston1er 126 (Toys
Galore).
NOTE
In some database systems, the word order has a special purpose. Having a table named ORDER could
cause problems in such systems. For this reason, TAL Distributors uses the table name ORDERS
instead of ORDER.
Tl1e table named ORDER_LINE might seem strange at first glance. vVhy do yo11 need a
separate table for the order lines? Co11ld they be included in the ORDERS table? The
answer is technically yes. Yott co11ld str11cture the table named ORDERS as shown in
Fig11re 1-3 . Notice that this table contains the same orders as sho\vn in Fig11re 1-2, with
tl1e same dates and c11sto1ner n11mbers. In addition, each table row in Fig11re 1-3 contains
all the order lines for a given order. Examining tl1e second row, for example, yo11 see that
order 51610 has two order lines. One of the order lines is for 25 units of item l(L 78 at
$ 10.95 each, and the otl1er order line is for 10 11nits of item TR40 at $ 13.99 each.
ORDERS
ORDER_NUM
ORDER_DATE CUSTOMER_NUM
ITEM_NUM
NUM_ORDERED
QUOTED_ PRICE
51608
10/12/2015 126
CD33
5
$86.99
51610
10/12/2015 33-!
I<L78
TR40
25
10
$10.95
$13.99
51613
10/13/2015 386
DL51
5
$104.95
51614
10/13/2015 260
FDl l
l
$124.95
51617
10/15/2015 586
NL89
T~'35
4
3
$115.99
$116.95
51619
10/15/2015 126
FDll
2
$121.95
51623
10/15/2015 586
DR67
FH24
1(1)34
s
12
10
$29.95
$36.95
$13.10
!v1T03
8
$45. 79
51625
10/16/2015 796
-
FIGURE 1-3
Alternative ORDERS table structure
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condominium Group
Qt1estion: How is the information from Figure 1-2 represented in Figure 1-3?
Answer: Examine the ORDER_LINE table sho,vn in Figure 1-2 and note the second
and third rows. The second ro,v indicates that there is an order line on order 51610 for
25 units of item KL78 at $10.95 each. The third row indicates that there is an order line
on order 51610 for 10 units of item TR40 at $13.99 each . Thus, tl1e information that
)rou find in Figure 1-3 is represented in Figure 1-2 in t\vo separate rows rather than in
one row.
It migl1t seem i11efficient to 11se tvvo ro\vs to store information that could be represe11ted
i11 one ro\V. Tl1ere is a problem, 110\,,ever, with the arrangement sl10\vn in Figure 1-3-the
table is more co1nplicated. In Fig11re 1-2, there is a single entry at each location in tl1e table.
111 Figure 1-3, some of the individt1al positio11s \Vitllin the table contain multiple entries,
malti11g it difficult to track the informatio11 betvveen col11mns. In tl1e ro\v for order 111rmber
51610, for example, it is c11.1cial to kno\v that tl1e ICL78 corresponds to tl1e 25 i11 tl1e
NUNI_ORDERED column (not to tl1e 10) and tl1at it corresponds to tl1e $ 10.95 in the
QUOTED_PRICE colirmn (11ot to the $ 13. 99). In addition, a more co1nplex table raises
practical iss11es, sucl1 as:
•
•
•
Hov.r 1nuch room do yot.1 allow for tl1ese 1nultiple e11tries?
,\T11at happens \Vl1en an order l1as more order li11es than yot.1 l1ave allov.red
room for?
For a give11 item, 110\v do you deter1nine \Vhicl1 orders contain order lines for
tl1at item?
Altl1011gl1 no11e of these proble1ns is unsolvable, tl1ey do add a level of complexity
tl1at is not present in tl1e arrangeme11t sho\vn in Fig11re 1-2. In Fig11re 1-2, there are 110
multiple entries to \Vorry abo11t, it does not matter 110\v many order lines exist for any
order, and findi11g every order that contains an order line for a give11 item is easy
(j11st lool{ for all order lines \Vitl1 tl1e given item 11umber in the ITEM_NUM column).
In general, tl1is simpler struct11re is preferable, a11d tl1at is \vhy order lin es appear in
a separate table.
To test yo11r 11nderstanding of the TAL Distribt1tors data, 11se Fig11re 1-2 to ai1s\ver the
follo\ving q11estions.
Question: What are the numbers of the customers represented by Rafael Campos?
~-\ns,ver: 126, 502, 713, and 893. (Looi{ up the REP_NU~I value of Rafael Campos in the
REP table and obtain the number 15. Then find all customers in the CUSTOMER table
that l1ave the number 15 in the REP_NUM column.)
Chapter 1
Question: \Vhat is the name of the customer that placed order 51613, and what is the
name of the rep who represents this customer?
Answer: Johnson's Department Store is the customer, and Megan Gradey is the rep.
(Look up the CUSTOMER_NUM value in the ORDERS table for order number 51613
and obtain the number 386. Then find the customer in the CUSTOMER table witl1 the
CUSTOMER_NUM value of 386. Using the REP_NUM value, \Vhich is 30, find the name
of the rep in the REP table.)
Question: List all items that appear in order 51617. For each item, give the description,
number ordered, and quoted price.
At1swer: Item number: NL89; description: \Vood Block Set (62 piece), number ordered: 4;
and quoted price: $115.99. Also, item number: TW35; description: Fire Engine; number
ordered: 3; and quoted price: $116.95. (Look up each ORDER_LINE table row on ,vhich
the order number is 51617. Each of these rows contains an item number, the number
ordered, and the quoted price. Use the item number to look up the corresponding item
description in the ITEM table.)
Question: Why is the QUOTED_PRICE column in the ORDER_LINE table? Can't you just
use the item number and look up the price in the ITEM table?
Answer: If the QUOTED_PRICE column did not appear in the ORDER_LINE table, you
would need to obtain the price for an item on an order line by looking up the price in the
ITEM table. Although this approach is reasonable, it prevents TAL Distributors from
charging different prices to different customers for the same item. Because TAL
Distributors wants the flexibility to quote and charge different prices to different customers, the QUOTED_PRICE column is included in the ORDER_LINE table. If you examine
the ORDER_LINE table, you ,vill see cases in which the quoted price matches the actual
price in the ITEM table and cases in which it differs. For example, in order number
51608, Toys Galore bought five Wood Blocl{ Sets (48 piece), and TAL Distributors
charged only $86.99 per set, and not the regular price of $89 .49 .
THE COLONIAL ADVENTURE TOURS DATABASE
Colonial Advent1.1re To1.1rs is a s1nall b1.1si11ess tl1at orga11izes day-long, g1.1ided trips to New
E11gland. Lil{e tl1e management of T AL Dis trib1.1tors, Colo11ial Adventure Tours l1as decided
to store its data in a database. Tl1e compa11y \.Vants to achieve tl1e same benefits; tl1at is, it
wa.n ts to ensure that its data is c1.1rrent and acc1.1rate. 111 additio11, the 1nanage ment of
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condominium Group
Colonial Adve11ti1re Tot1rs \.Vants to be able to asl{ questions concerning tl1e data and to
obtain a11swers to tl1ese qi1estio11s easily and qi1icltly.
In n1nning tl1e gi1ided tours, ma11agement gathers and organizes information aboi1t
gi1ides, trips, ci1stomers, and reservations. Figi1re 1-4 sl10\.vs sample guide data for Colonial
Adventi1re Tot1rs. Eacl1 gi1ide l1as a number tl1at tiniquely identifies tl1e gi1ide. In addition,
Colonial Adventi1re Tot1rs records the gi1ide's last name, first name, address, city, state,
postal code, telepl1one 11i1mber, and l1ire date.
GU IDE
GUIDE_NUM
LAST_NAME
FIRST_NAME
ADDRESS
CITY
STATE
POSTAL_CODE
PHONE_NUM
HIRE_DATE
A.MOl
Abran1s
wfiles
54 Quest Ave.
\ViUi~unsburg
MA
01096
617-555-6032
6/3/2012
BRO]
Boyers
Rjca
140 ()akton Rd.
Jaffrey
Nll
03452
603-555-2134
3/4/2012
D1101
Devon
llarley
25 Old Ranch Rel.
Sunderland
l\·IA
01375
781 -555-776 7
1/8/2012
GZ01
Gregory
Zach
7 !\loose Jleacl Rd.
Dumn1er
Nll
03588
603-55:i-8765
11/4/2012
I<SOl
Kiley
Susan
943 Oakton Rd.
Jaffrey
NH
03452
60.1-555-1230
4/8/2013
r<S02
Kcllv
-
Sam
9 Gongaree Ave.
Fraconia
NH
03580
603-5SS-000.1
6/10/201.1
l\ffi01
11,rars1on
Ray
24 Shenandoah Rd . Springfield
MA
01101
781 -555-2.123
9/l4/2015
RH01
Rowan
Ha l
12 HcaLher Rd.
l\lou n t Dcscn
l\JE
04660
207-55:i-9009
6/2/2014
SLOl
Stevens
Lori
1.5 Riverton Rd.
Coventry
VT
05825
802-555-.1.139
9/5/2014
UG01
Unser
Glory
342 Pinc,·icw St.
Danbury
CT
06810
20.1-55:i-85.14
2/2/2015
FIGURE 1-4
Sample guide data for Colonial Adventure Tours
Figure 1-5 sl1ows sa1nple trip data for Colonial Adve11ture Tours. Eacl1 trip l1as a
number tl1at uniquely identifies tl1e trip. In addition, 111anage1nent tracl{s tl1e trip nai11e,
tl1e trip's starti11g location, the state in \.Vllich the trip originates, tl1e trip's total distance
(i11111iles), the trip's maximum group size, tl1e trip's type , at1d tl1e trip's season.
•
Chapter 1
TRIP
TRIP_ID TRIP_NAME
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
L
START _LOCATION
STATE
1 1\retbusa !?alls
2 !\It Ascutney - North Peak
J !\It AscuLney - \Vest Peak
4 Bradbttry l\1ounrain Ride
::, Bald pate !\,f ountain
I lart~ LocaUon
\Veathersfield
\\Ieathersficld
Le1viston-1\ubu1·n
North Ne,vry
6 Blueberry l\foun tain
7 Bloomlield - l\faidstone
8 Black Pond
9 Big Rock Cave
10 !\It. Cardigan - Fircscrew
11 Chocorua Lake Tour
12 Cadillac !\fountain Ride
13 CadJJlac !\Joun tain
14 Cannon ~ltn
15 Cra,vford Path Presidentials llil1e
16 Cherry Pond
Batchelders Gr.tat
Bloomlield
Lincoln
Tamworth
:-S 11
VT
VT
l\l.E
J\fE
l\fE
~
l i Huguenot llellcl Hike
18 Lo1v Bald Spot Hike
19 l\'111son's F11rn1
20 L:1ke !l.[ephren,agog Tour
21 Long Pond
22 Long Pond Tow·
23 Lo,vcr Pond Tour
2-1 !\•It Adan1s
25 l\lount Battie Ride
.26 l\ lount Cardig11n I like
27 1\IL Chocorua
28 !l.lotuit Garfield Hike
29 J\letacorue1-1'Ionadnock Trail llike
30 !1.lcLen11a11 Reservation JW,e
31 l\lissisquoi River - VT
32 Northern Forest Canoe Trail
33 Park Loop Ride
34 Pontook Reservoir Tour
JS Pisgah State Park Ride
36 Pondicberry Trilli Ride
37 Seal Beach liarbor
38 Sa,vyer River Ride
39 \Velch and Dickey l\1ountains TTike
-10 \\fachusett !\fountain
41 \Vcst:field River Loop
FIGURE 1-5
Orange
Tam,vorth
Bar II11rbor
Bar Harbor
Franconia
Cra,vford Notch
\Vhi tefi cl d
Bar Jlllrbor
Pin k11m Notch
North Str11tforcl
Newporl
Rutland
Greenvi ll e
Poland
Randolph
Can1den
Cardigan
1\Jbany
\Voodstock
Pelham
Tyringham
Lo,vell
Stark
l\lount Desert Island
Dummer
Northborou.e.b
\\'hite l\Jountains
Bar Tllu·bor
11ount CarrigairJ
Thorton
Princeton
Fort Fairfield
DISTANCE
MAX_GRP _SIZE TYPE
5
1() I li lting
6 I liking
10 !liking
~
::,
6
?~
_::,
6
8
CT
10
:-.1r
1'11
~H
l-.'11
l\1E
l\1E
;'\lJ
8
:-.rir
;l(li
l\1E
:--11
6
7
12
8
7
6
16
6
5
8 Biking
10 !Ii.lung
8 Iliking
6 Paddling
12 IJiking
10 llilting
8 Iii.king
15
16
8
6
4
16
10
s
6
12
8
8
12
7
12
10
!\'IE
;,.; II
8
15
9
6
1\11~
.'.'i II
NI I
20
8
4
:--'11
5
1\'11\
10
6
12
15
16
10
10
12
16
10
10
27
8
XH
15
12
15
l\'1E
::,
:-.11 I
10
5
8
20
14
10
16
16
18
10
8
10
CT
VT
l\f,\
!\fl~
!\'1\
\'T
~II
l\1E
l\11
NH
:-.11
l\L\
l\1E
6
-
JS
Paddling
Biking
Jlildng
Hiking
llikin_!!.
Hiking
Hiking
Hiking
Paddling
Paddling
llikin,ll.
Pad<lling
Pad<lling
II iking
Biking
II iking
I liking
Ililtin~
I liking
£liking
Paddling
Paddling
Biking
l'addlin_!!.
Biking
Bihlng
llili.ing
Biking
TJiking
I Ti king
Biking
SEASON
8urnn1er
Late 8prinl!
ffiarly Fall
Ea1·ly Fall
Late Spring
E1u·ly Fall
Late Spring
Stm1n1er
Su1nn1er
Summer
Summer
Early Fall
Late Spring
Early Fall
Surn1ncr
I
Sp1ing
Early Fall
Early F111\
L11te Spring
Late Spring
S1.1n1mer
Sun1n1er
Late Spring
Sun1mer
Early Fall
I
Late VaJJ
Spring
Early Fall
Late Spring
StLlllOler
Su111111er
I
Summer
Late Spring
Late Sp~
Su111111er
Late Spring
Early Spring
E11rly Fall
SuJll1-uer
Early Spring
l,ate Spring
Sample trip data for Colonial Adventure Tours
Fig1.1re 1-6 sl10\vs sample c1.1sto1ner data for Colonial Advent1.1re To1.1rs. Eacl1
c1.1stomer is identified by a 1.1niq1.1e c1.1stomer n1.1mber. In addition, 1nanagement stores
eacl1 customer's last 11ame, first na1ne, address, city, state, postal code, and telephone
number.
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condominium Group
CUSTOMER
CUSTOMER_NUM
LAST_NAME
FIRST_NAME
ADDRESS
CITY
STATE
POSTAL_CODE
PHONE
101
102
103
l 0-!
105
106
107
108
109
110
112
JJ 5
116
119
120
121
122
123
12-1
1.,_;,
Liam
Arnold
Sujata
Ryan
9 Old 11ill Rd.
23.32 South St. Ape .3
132 l\.1ain St. #1
16-lA South Bend Rd.
345 Lower Ave.
156 Scholar St.
76 Cross Rd.
32 Sheep Stop St.
10 Greenfield St.
65 G ran ite St.
373 I lil\hlancl Ave.
J 282 Ocean \\'all,
7 Cherry Blossom St.
18 ,\rk Ledte Ln.
24 Stump Rd.
10 Old }.!lain St.
132 South St. Apt 27
25 Stag Rd.
12 Foster St.
51 l?redrick St.
154 Central St.
Londonderry
Springfield
Ease IIartford
Lo,vell
\Volcon
Johnston
Bath
Edinboro
Rome
York
S0111ervi lie
Ocean Citv•
\Vcyn1outh
Londonderry
Athens
Cambridl\e
!\Ion chester
~'airfield
Soul h Windsor
Albion
Vernon
NH
03053
01101
06108
0185-!
1-!590
02919
03740
16412
04963
14592
02L4J
08226
02188
05148
04912
126
Northfold
()eean
I<asuma
Goff
l\leLean
t.-lorontoi;i
Nl.archand
Rulf
Caron
Bers
Jones
7
\ oceari
l\furakami
Chau
Gerno,vski
Bretton-Boral,
llefferson
Barnett
Busa
Peterson
Bro,vo
60J-5S5-7563
413-555-3212
860-555-0703
781-555-8423
585-555-5321
-!01-555--!8-!8
60.3-555-0456
8]-!-555-5521
207-555-9643
585-555-0 l 11
857-555-6258
609-555-523)
61 7-555-6665
802-555-3096
207-555-4507
802-555-3443
603-555-3476
860-555-9876
857-555-55:12
585-555-0900
860-555-.3234
FIGURE 1-6
Sample customer data for Colonial Adventure Tours
Ky le
Joseph
Quinn
Uschi
Jean Luc
l\.lartha
Laura
Adam
Iris
Clement
Sadie
Siam
Orlauh
Larry
Karen
Becca
Brianne
!\.IA
C'r
l\l_,\
NY
RI
]\TJJ
P~\
NIE
NY
!\.IA
NJ
l\'1\
VT
!\.IE
VT
Nll
CT
CT
NY
CT
OS444
03101
0682-1
0607-1
14411
06066
Fig11re 1- 7 s l10\vs sa1nple reservations data for Colonial Adve11ture To11rs. Eacl1 reservatio11 is identified by a 11nique reservation n111nber that 11ses the las t t\vo digits of the
current year follov,red by a five-digit n111nbe r tl1at is i11cremented seq11e11tially as each reservation is received. Tl1e table also s tores the trip n11mber , tl1e trip date, the n11mber of
persons, the trip price per per so11, any additional fees for transportatio11 and eq1.1ipment
re11tals, ru1d tl1e customer n11n1ber.
Chapter 1
RESERVATION
RESERVATION_ID TRIP_ID TRIP_DATE
1600001
1600002
1600003
] 600004
1600005
1600006
1 600007
1600008
1600009
1600010
1600011
1600012
1600013
160001-1
1600015
160001 6
1600017
1600018
16000] 9
1600020
1600021
1600022
1600024
1600025
1600026
1600029
1600030
FIGURE 1-7
40 3/26/20]6
21
6/8/2016
28 9/12/2016
26 l 0/16/2016
39 6/25/2016
32 6/18/2016
22
7/9/2016
28 9/12/2016
38 9/11/2016
2 5/14/2016
3 9/15/2016
1 6/12/2016
8
7/9/2016
12 10/1/2016
10 7/23/2016
11
7/23/2016
39 6/18/2016
38 9/18/2016
25 8/29/2016
28 8/27/2016
32 6/11/2016
21
6/8/20] 6
38 9/] 1/2016
38 9/11/2016
12 10/1/2016
4 9/19/2016
15 7/25/2016
NUM_PERSONS TRIP_PRICE
2
2
1
4
,-
;)
1
8
2
2
3
3
4
1
2
1
6
3
4
2
2
3
]
1
2
2
4
6
OTHER_FEES CUSTOMER_NUM
$55 .00
$95.00
$35.00
$45.00
$55.00
$80.00
$75.00
$35 .00
$90.00
$25.00
$25 .00
$15.00
$20.00
$-10.00
$20.00
$75 .00
$20.00
$85.00
$110.00
$35.00
$90.00
$95.00
$70.00
$70.00
$40.00
$105.00
$60.00
$0.00
$0.00
$0.00
$1 5.00
$0.00
$20.00
$] 0.00
$0.00
$40.00
$0.00
$0.00
$0.00
$5.00
$5.00
$0.00
$15.00
$5.00
$15.00
$25.00
$10.00
$20.00
$25.00
$30.00
$45 .00
$0.00
$25.00
$15.00
101
101
103
] 04
105
106
107
108
109
102
102
115
116
119
120
121
122
126
) 24
124
112
] 19
121
125
126
120
104
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
Sample reservations data for Colonial Adventure Tours
T o cl1eclr yo1..1r t1nderstanding of the relation sl1ip b etween ctistomers and reservation s,
answer tl1e followi11g questio11s.
Question: Which customer made reserva tion 1600010? For which trip date(s) does
Karen Busa have reservations?
Answer: Arnold Ocean made reservation 1600010. Find the row in the RESERVATION
table with the reservation ID 1600010 (see Figure 1-7), and then find the customer
number 102. Next, review the CUSTOMER table (see Figure 1-6), and determine tha t the
custom er name with the custom er number 102 is Arnold Ocean . Karen Busa h as r eservations for trips on August 27, 2016 an d August 29, 2016 . To find the trip da tes for
Karen Busa, find her custome r number (124) in the CUSTOMER table. Next, find all ro,vs
in the RESERVATION table tha t con tain the custom er number 124 .
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condominium Group
Tl1e table 11amed TRIP_GUIDES sl1ov,,11 i11 Figt1re 1-8 is t1sed to relate trips a11d gt1ides.
It i11clt1des tl1e trip 11t1mber ai1d the gt1ide 11tu11ber . Tl1e trip 11t1111ber il1 tl1e TRIP_GUIDES
table 1na tc l1es a trip 11u1nber ill tl1e TRIP ta.b le, ai1d tl1e gttlde 11t1mber ill tl1e TRIP_GUIDES
table 1na tcl1es a gttlde nu1nber il1 tl1e GUIDE table.
TRIP _GUIDES
TRIP_GUIDES (CONTINUED)
TRIP _ID GUIDE_NUM
]
GZOl
1 Rl!Ol
2 Aiv!Ol
2 S101
3 S101
-l BROl
4 GZOl
TRIP_ID GU IDE_NUM
'
19 DIIOJ
20 S101
21 1\NJOl
22 UGOl
23 D1101
23 S101
2-l BR.OJ
5 l<SOl
25 BROl
:,
26 GZOl
6 IlifOl
7 SLOl
27 GZOl
8
BROl
29 DI-IOI
9 BROl
GZOl
30 1-\ MOl
J] SLOJ
11 DITO!
32 l(S01
11 KSOI
33 UGOl
11 UGOl
12 BROl
34 I<.801
- UGOl
]()
13 RJIOl
14 I<S02
15 GZOl
16 KS02
I
28 BROl
35 GZOl
36 1(802
37 RIIOl
38 l(S02
39 Bl~Ol
17 RJIOl
40 DHOl
18 KS02
41 BROl
FIGURE 1-8
I
Table used to relate trips and guides
To c h ecl{ yot1r t1nde rstanding of the relatio11sllip be tween trips and gt1ides, ansvver tl1e
followin g qt1es tions .
Question: \Vhich trips are led by Glory Unser? \Vhich guides lead the Lower Pond Tour
trt. p.?
At1swer: Glory Unser leads the Baldpate Mountain, Chocorua Lake Tour, Long Pond
Tour, and Park Loop Ride trips. To determine \Vhich trips Glory Unser leads, first examine the GUIDE table (see Figure 1-4) to find h er guide number (UGOl). Next, look for all
rows in the TRIP_GUIDES table that contain her guide number (UGOl), and find that
these rows contain the trip numbe rs 5, 11, 22, and 33. Then examine the TRIP table to
Chapter 1
determ ine the trip names for the trips ,vith the trip numbers 5, 11, 22, and 33 to learn
the corresponding trip names: Baldpate Mountain, Chocorua Lake Tour, Long Pond Tour,
and Park Loop Ride.
I-larley Devon and Lori Stevens lead the Lower Pond Tour trips. To find the guides
,vh o lead the Long Pond Tour trip, use the TRIP table to identify the trip numbe r for this
tour and determine that it has the trip number 23, and then look for all ro,vs in the
TRIP_GUIDES table that contain the trip number 23. There are two such rows, which
contain the guide numbe rs DHOl and SLOl. Finally, find the rows with these guide numbers in the GUIDE table, and then determine that I-larley Devon and Lori Stevens lead the
Lower Pond Tour trips.
Q11estion: One of Jean Luc Caron's friends called the tour office to reserve the same trip
as Jean Luc, but he can' t remember the trip name. Which trip did J ean Luc Caron
reserve?
Answer: J ean Luc has a reservation for the Sawyer River Ride trip . First, find the
customer number for J ean Luc Caron in the CUSTOMER table to determine that his custome r number is 109. Then review the RESERVATION table and find all rows ,vith the
custom e r number 109, and determine the t rip number for that trip, which is trip number
38. Finally, review the TRIP table to identify that trip number 38 is the Sawyer River
Ride trip.
Question: Which guides lead paddling trips in the summer season ?
Answer: Harley Devon , Susan Kiley, Lori Stevens, and Glory Unser are leading paddling
trips in the summer . To identify paddling trips that are offered in the summer , look for
rows in the TRIP table tl1at have Paddling in the Type column and Summer in the Season
column. The re are four such rows with the trip numbers 11, 22, 31, and 32. Locate these
trip numbers in the TRIP_GUIDES table, and then determine that the guide numbers
DHOl, KSOl, SLOl, and UGOl are associated with these trip numbers. Finally, find the
guide numbers DHOl, KSOl, SLOl, and UGOl in the GUIDE table, and then identify the
corresponding guides as Harley Devon , Susan Kiley, Lori Stevens, and Glory Unser.
THE SOLMARIS CONDOMINIUM GROUP DATABASE
Solmaris Co11don1inium Grot.1p manages two condo1ni11it.1m co1nplexes, Solmaris Ocea11 and
Solmaris Bayside, wl1ich are located in Florida. l11 additio11 to mai11tainil1g the common
areas, Solmaris also provides a variety of mait1tenance services for a fee. Solmaris s tores
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condominium Group
tl1e data it needs to manage its operations in a database contai11ing tl1e tables described
in tl1e following section.
In tl1e LOCATION table sho\\'n in Figi1re 1-9, Soln1aris stores information aboi1t its
two locations. Eacl1 location is identified by a i1niqi1e nt1mber. The table also includes the
location name, address, city, state, and postal code.
LOCATION
'
LOCATION_ NUM
LOCATION_NAME
1 Solmaris Ocean
2 Solmaris J~aysidc
•
.
I
FIGURE 1-9
ADDRESS
CITY
STATE
POSTAL_CODE
100 Ocean 1\ve.
-l05 Bayside Blvd.
Bo\vton
Glander Bay
FL
31313
310-l-!
FL
Sample location data for Solmaris Condominium Group
Solmaris stores information about tl1e owners of eacl1 co11do ttnit in tl1e O\\TNER table
sl1ow11 in Figure 1-10. Each o\v11er is identified by a uniqtte o\vner ni1mber that consists of
two ttppercase letters follo\ved by a three-digit number. For each owner, tl1e table also
incli1des tl1e last name , first na1ne , address, city, state, and postal code. Yot1'll 11otice that
only so1ne of the o\v11ers actt1ally live in tl1e Solmaris condos tl1at they o\v11.
OWNER
OWNER_NUM
LAST_NAME
FIRST_NAME
ADDRESS
CITY
STATE
POSTAL_CODE
J\D057
AN175
81720
EL025
1\dney
Bruce and .Jean
Bill
100 Ocean J\ve.
18 \Vilcox St.
26 72 Condor St.
100 Ocean 1\ve.
7822 Coventry Dr.
Bo\vton
FL
Brttnswick
11ills
80\VtOn
Rivard
l(alcva
G1\
31313
31522
29707
t\n derson
Blal<e
Elend
Feenstra
Juarez
I(elly
FE182
JU092
I<E122
N0225
Norlo11
Robinson
Smeltz
R.0123
81·1072
1'R.222
\\TS032
Trent
\Vilson
Jack
Bill and Sandy
Daniel
~laria
1\lyssa
•
Peter and Caitlin
Mike and Jane
Jin, and Cathy
1'1ichae l
Ilenry and I<aren
892 Oak St.
527 \Vacers St.
Norton
281 Lake,vood 1\ve. La,vndaJe
900 Spr ing Lake Dr. Springs
922 Garland Dr.
Lc,viston
405 Bayside Blvd.
Glander Bay
25 Nichols St.
Le\vislon
~
FIGURE 1-10
SC
FL
FL
l?I,
NII
P1\
lvll
31313
31062
31521
49-l:-l:1
19111
49-!56
[?L
32765
FL
31044
32765
-
FL
I
I
Sample owner data for Solmaris Condominium Group
Eacl1 i1nit at each locatio11 is identified by a t111it 11t1mber. Locatio11 1 (Sol1naris
Ocea11) t1ses a tlrree-digit t111it 11u111ber to ide11tify each condo i111it. Tl1e first digit identifies
tl1e floor and the last two digits indicate tl1e unit on tl1e floor. Location 2 (Solmaris
Bayside) t1ses tl1e letters A, B, a11d C to identify tl1e tl1ree levels of tl1e co1nplex, follo\\red
by tl1e t111it 11t11nber 011 tl1e level.
Information aboi1t tl1e condo units at eacl1 location is stored in tl1e CONDO UNIT
table show11 i11 Figi1re 1-11 . Tl1e table co11tai11s tl1e condo ID 111.1111ber, locatio11 nt11nber,
t111it 111.1mber, sqi1are footage of tl1e i111it, 111.1mber of bedroo111s, 11t1111ber of batl1rooms,
monthly condo association fee , and the o\vn er 111.1 mber.
Chapter 1
CONDO_UNIT
CONDO_ID
•
LOCATION_NUM UNIT_NUM
SQR_FT BDRMS
102
201
J()6
204
405
401
502
503
2 ~i\03
2 AOl
2 J30J
2 COI
2 CO2
2 C06
1
1
1
1
1
1
1
1
1
2
3
4
5
6
7
8
9
10
]]
12
13
14
675
1,030
l ,575
1,164
1,575
1 ,030
745
1,680
725
1,084
J ,084
750
1,245
1,540
1
-?
J
2
3
2
]
J
1
2
2
1
2
3 '~
BATHS
1
1
2
2
2
2
1
3
1
1
2
1
2
2
CONDO_FEE OWNER_NUM
$475
$550
$625
$575
$625
$550
$490
$670
$190
$235
$250
$190
$250
$300
t\D057
EL025
1\Nl 75
BL720
FE182
ICE122
JU092
R0123
TR222
N0225
S.NJ072
r\Nl 75
\VS032
R012J
'
Sample data about condo units for Solmaris Condominium Group
FIGURE 1-11
Solmaris provides maintenance services at its two locations. The types of service provided are stored i11 tl1e SERVICE_CATEGORY table sl1own in Figi1re 1-12. A category
11umber u11iqi1ely identifies each service that Sohnaris provides. The table also contains a
description of the category.
SERVICE_CATEGORY
CATEGORY _NUM CATEGORY _DESCRIPTION
I
I
I
I
I
I
FIGURE 1-12
1
2
3
4
Pl tlnl b. itlg
IIeating/1\ir Conditioning
Painting
Electr ical Syste111s
s Carpe ntry
6 Janitorial
Sample data about service categories at Solmaris Condominium Group
Information aboi1t tl1e services reqi1ested by o\.v11ers is stored in the SERVICE_ REQUEST
table sl10\.vn in Figure 1-13. Eacl1 ro\.v in tl1e table co11tains a service ID ni1mber tl1at u11iqi1ely
identifies eacl1 service reqi1est. Tl1e condo ID number identifies \.Vhicl1 condo reqitires service. For example, the condo \.Vitl1 the ID number 5 on the second rov.r represents tl1e condo
in location 1 and u11it ni1mber 405 (as foi1nd by examining ro\.v 5 in tl1e CONDO_Ul\TJT table).
Tl1e SERVICE_ REQUEST table also stores tl1e category number of tl1e service to be performed, a descriptio11 of the specific service to be performed, tl1e ci1rrent stati1s of tl1e service,
ai1d tl1e estin1ated ni1mber of hoi1rs reqi1ired to complete the service. For completed jobs,
tl1e table contai11s tl1e actual ni1mber of l1oi1rs reqi1ired to complete the service. If another
appoint1nent is reqi1ired to con1plete additional service, tl1e appointn1ent date appears i11 the
NEXT- SERVICE- DATE coli11nn.
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condomin ium Group
SERVICE_REOUEST
SERVICEID
CONDO ID
CATEGORY - DESCRIPTION
NUM
1
2
1 Back wall in pantry has
mold indicating \Vntcr
seepage. Diagnose and
repair.
2
5
2 Air conditioning
doesn't cool.
STATUS
ESTHOURS
SPENTHOURS
NEXT_
SERVICE_DATE
Service rep has verified the
problcrn. Plu1nbing
contractor has been called.
4
2
10/12/2015
Service rep has verified
problen1. Air conditioning
contractor has been called.
3
I
10/12/2015
3
4
6 Ilarthvoo<l floors
n1ust be refinished.
Service call has been
scheduled.
8
0
10/16/2015
"
1
4 8'vitches in kitchen and
acl_ioining dilling room
a re rcversetl.
Open
I
0
10/13/2015
:,
-
2
:, ~Iolding in pan rry musr
be replaced.
Cannot schedule until
\Vater leak is corrected.
2
0
6
14
3 Unit needs to be repainted
due to previous tenant
dan1agc.
Scheduled
7
0
7
11
4 Tenant complained that
using m.icro,vave cnused
short circuits on t\VO
occasions.
Service rep unable to
duplicate problem.
Tenant to notify condo
n1anagen1ent if problem
recurs.
1
1
8
9
3 Kitchen muse be repainted. Scheduled
\\'alls discolored due ro
kitchen lire.
5
0
10/16/2015 I
9
7
6 Sha1npoo ::ill carpets.
Open
5
0
10/]9/2015
10
C)
5 Repair \Vi.ndo1v sills.
Scheduled
4
0
l 0/20/2015
FIGURE 1-13
10/19/2015
I
Sample data about service requests for Solmaris Condominium Group
Tl1e Soh11aris Co11domi11it11n Grot1p exercises at tl1e e11d of tl1is cl1a.p te r \.Vill give yot1 a
chance to checl{ yot1r t111ders tanding of tl1e data in tllis database.
Chapter 1
Chapter Summary
•
TAL Distributors is an organization whose information requirements include sales
reps, customers, items, orders, and order lines.
•
Colonial Adventure Tours is a company whose requirements include information about
the following entities: guides, trips, customers, reservations, and trip guides.
•
Solmaris Condominium Group is a company whose requirements include information
about the following entities: condo locations, owners, condo units, service categories,
and service requests.
Key Term
database
Exercises
T AL Distributors
Answer each of the fallowing questions using the TAL Distributors data shown in Figure 1-2. No
computer work is required.
1. List the names of all customers that have a credit limit of $7,500 or less.
2. List the order numbers for orders placed by customer number 586 on 10/15/2015.
3. List the item number, item description, and on-hand value for each item in category TOY.
(Hint: On-hand value is the result of multiplying the number of units on hand by the price .)
4. List the item number and item description of all items that are in category PZL.
5. How many customers have a balance that exceeds their credit limit?
6. What is the item number, description, and price of the least expensive item in the
database?
7. For each order, list the order number, order date, customer number, and customer name.
8. For each order placed on October 13, 2015, list the order number, customer number, and
customer name.
9. List the sales rep number and name for every sales rep who represents at least one customer with a credit limit of $1 O,000.
10. For each order placed on October 12, 2015, list the order number, item number, item
description, and category for each item ordered.
C RITICAL
THINKING
11 . TAL Distributors needs to be able to contact customers when problems arise concerning an
order. What other types of data could TAL include in the CUSTOMER table to assist in
contacting customers?
Introduction to TAL Distributors, Colonial Adventure Tours, and Solmaris Condomin ium Group
Colonial Adventure Tours
Answer each of the following questions using the Colonial Adventure Tours data shown in
Figures 1-4 through 1-8. No computer work is required.
1. List the first and last name of each guide that lives in Maine (ME).
2. List the trip name of each trip that has a maximum group size of greater than 16.
3. List the trip ID and trip name of each trip that has the type Paddling.
4. List the trip ID and trip name of each trip that has the type Biking and that has the season
Early Fall.
5. List the trip ID and trip name of each trip that is in the state of Vermont (VT) or that has the
type Paddling.
6. How many trips have the type Hiking?
7. List the trip name of each trip that has Hal Rowan as a guide.
8. Find the name of each trip containing the word Loop.
9. List the first and last name of each guide who lives in Maine (ME), Vermont (VT), or
Connecticut (CT).
10. How many reservations are for trips that occur during July 2016?
11 . For each customer that has more than one reservation, list the customer's first and last
names, the trip name, and the trip type .
12. List the last name of each customer that has a reservation for a trip in Massachusetts (MA).
13. How many reservations have a trip price that is greater than $15.00 and less than $40.00?
C RITICAL
THI NKING
14. Currently, trip cost is determined by the number of people taking the trip and the type of
trip. If trip cost were based only on the type of trip, in which table would you place the trip
cost fie Id? Why?
Solmaris Condominium Group
Answer each of the following questions using the Solmaris Condominium Group data shown in
Figures 1-9 through 1-13. No computer work is required .
1. List the owner number, last name, and first name of every condominium owner.
2. List the last name and first name of every owner located in Bowton.
3. List the condo ID number for each condo that is smaller than 1,084 square feet.
4. List the last name, f irst name, and city of every owner who owns more than one condo.
5. List the last name, first name, and city of every owner with a condo that has a condo fee of
less than $250 per month.
6. List the unit number of each condo at the Solmaris Ocean location.
7. How many condos have two bedrooms and two bathrooms?
8. How many owners live in Florida (FL), Georgia (GA), or South Carolina (SC)?
Chapter 1
9. List the owner's last and first names and the unit number for each condo that has a scheduled or open service request.
10. List the condo ID number and square footage for each condo that has a janitorial service
request.
11 . List the condo ID number and location name for all service requests for which the estimated
number of hours is greater than 5.
12. What is the average condo fee for all three-bedroom condos?
C RITICAL
THINKING
13. The Solmaris database does not include a column for service fees. In which table would
you place the information for service fees? Why?
CHAPTER
DATABASE DESIGN
FUNDAMENTALS
OBJECTIVES
•
Understand the terms entity, attribute, and relationship
•
Understand the terms relation and relational database
•
Understand functional dependence and identify when one column is
functionally dependent on another
•
Understand the term primary key and identify primary keys in tables
•
Design a database to satisfy a set of requirements
•
Convert an unnormalized relation to first normal form
•
Convert tables from first normal form to second normal form
•
Convert tables from second normal form to third normal form
•
Create an entity-relationship diagram to represent the design of a
database
INTRODUCTION
In Chapter 1, you reviewed the tables and columns in the TAL Distributors, Colonial Adventure Tours,
and Solmaris Condom inium Group databases that you will use to complete the rest of this text. The
process of determining the particular tables and columns that will comprise a database is known as
database design. In this chapter, you will learn a method for designing a database to satisfy a set
of requirements. In the process, you will learn how to identify the tables and columns in the database.
You also will learn how to identify the relationships between the tables.
This chapter begins by examining some important concepts related to databases. It also presents the design method using the set of requirements that TAL Distributors identified to produce the
appropriate database design. The chapter then examines the process of normalization, in which you
identify and fix potential problems in database designs. Finally, you will learn a way of visually representing the design of a database.
Chapter 2
DATABASE CONCEPTS
Before learning 110\v to design a database, you need to be familiar \Vitl1 some important
database co11cepts related to relatio11al databases, \Vhicl1 are tl1e types of databases yot.1
exa.mi11ed in Cl1apter 1 a11d that yot.1 \\rill i1se tl1roi1gl1oi1t the rest of this text. Tl1e ter1ns
e11tity, attribute, and relationship are important to i1nderstand Y.rl1en designing a database;
tl1e concepts of fu11ctional dependence a11d prin1ary lteys are critical \Vl1en learning aboi1t
tl1e database desigi1 process .
Relational Databases
A relational database is a collectio11 of tables like tl1e 011es yot.1 exarniI1ed for TAL
Distribt.1tors i11 Cl1apter 1 a11d tl1at appear i11 Figi1re 2-1. For111ally , tl1ese tables are called
relatio11s , a11d this is l10Y.' tl1is type of database gets its 11ru11e.
REP
REP_NUM
LAST_NAME
FIRST_NAME STREET
15
JO
45
60
Campos
Gradey
Tian
Sefton
Rafael
t.le,!!an
Hui
Janet
CITY
Grove
724 Vinca Dr.
632 Liatris St. Pull ton
1785 Tyler Ave. Northfield
267 Oakley Sr. Congaree
STATE
POSTAL_CODE
CA
90092
90085
90098
90097
CA
CA
CA
CUSTOMER
-
COMMISSION
RATE
$23,457.50
$-1-1,Jl 7 .00
$27,789.25
$0.00
0.06
0.08
0.06
0.06
CUSTOMER_NUM
CUSTOMER_NAME
STREET
CITY
STATE
POSTAL_CODE
BALANCE CRED IT _LIM IT
126
Toys Galore
28 Laketon St.
Full ton
CA
90085
$1,210.25
260
Brookings Dfrect
452 Colun1bus Dr.
Grove
CA
90092
$575.00
33-1-
The E"erything
Shop
3421'lagee St.
Oon,l!aree
C,\
90097
$2,345.75
$7,500.00 45
.386
.Johnson's
Department
Store
12-1- t..la in St.
Northfield
C1\
90098
$879.25
$7,500.00 30
440
Grove
Hisrorical
1•1uscum Store
3456 Ce11 tral Ave. Full ton
CA
90085
$345.00
$5,000.00 45
I so2
Cartls and t,.lore
167 Hale St.
t..lesa
CA
90104
$5,025.75
$5,000.00 15
586
Aln1ondto11
General St·ore
3345 Devon Ave.
Almond con CA
90125
$3,456.75
$15,000.00 45
$678.90
$4,234.60
$12-1-. 7 5
$7 .500.00 JO
$10,000.00 15
$7,500.00 45
$2.475.99
$935.75
$15.000.00 30
$7 .500.00 15
665
7)3
796
Cricket Gift Shop
824
l89J
FIGURE 2-1
CA
Unique Gifts
J 72 Oxford St.
Grove
12 Rising Sun Ave. Con~:-tree
786 Passmore St. Northfield
C,\
90092
90097
90098
Kline's
All Season Gifts
945 Gilham St.
t..lesa
382 \Vild,vood ,\ve. Fullton
C,\
90104
C,\
9008S
C ress Store
Sample data for T AL Distributors
CA
REP _NUM
$7,500.00 15
$10.000.00
JO
Database Design Fundamentals
ORDERS
ORDER_LINE
ORDER_NUM
ORDER_DAT E CUSTOMER_NUM
5]608
Sl610
10/12/2()1 S 126
51613
5]614
10/13/2015 386
]0/]3/2015 260
51617
51619
10/15/2015 586
10/J 5/2015 126
10/15/2015 586
10/16/201:i 796
51608
51610
10/12/2()15 334
51623
-16-:,:,
_;:,
S1610
51613
516]4
'
51617
51617
S1619
5)623
51623
51623
:,-1 6"
_..::,-
~-
l(L, 78
_;:,
TR40
DLSl
10
FDll
Nl,89
J
4
T\V35
3
FDll
DR67
1,1124
-12
T<D34
10
MT03
8
-
;:,
')
;:,
$13.99
$]0-1.95
$124.95
$115.99
$116.95
$121.95
$29.95
$36.95
$13.10
$45. 79
ITEM
ITEM_NUM
DESCRIPTION
AlI74
Patience
IBR2.1
Skittles
CIJ33
" rood Block Set ( 48 piece)
IDL51
DR67
Classic Railwity Set
I D\V23
FDl l
Mrincaln
I Fll24
l(i\ 12
Puzide Gift Set
Gianr St:1r Brain Te:iser
Rocking llorse
ON_HAND CATEGORY
STOREHOUSE
PRICE
3
$22.99
-
$29.99
l
$89.<19
3
$]07.95 j
2
$31.95
40 OJ.IE
8 TC>Y
65 PZI,
3
$50.00
3
$12-1.95
l
$38.95
3
$75.00
$1-1.95
9 GlilE
21 GliIB
36 TOY
12 TOY
24 PZL
,.,
I 1<D34
l(L78
Pencon1inoe.:; Brain Teaser
56 GM~:
60 PZL
Pick Up Sticks
11 0 GME
-J
1~1'1'03
Nl,89
Za uberl,asten Brain Teaser
45 PZL
l
$-IS. 79
\\Tood Block Bet ( 62 piece)
32 TOY
3
$119.75
I TR-10
Tic Tac Toe
75 G~IB
2
$13.99
T\V35
Fire Engine
30 TOY
2
$118.9:i
Cribbage Set
FIGURE 2-1
')
$10.95
Sample data for TAL Distributors (continued)
NOTE
The names of columns and tables in this text follow a common naming convention in which column
names use uppercase letters and replace spaces between words with underscores (J. For example,
TAL Distributors uses the column named LAST NAME to store last names and the column named
CRED IT LIMIT to store credit limits.
Entities, Attributes, and Relationships
Tl1ere are so1ne te rms and concepts tl1a t are very important for you to k110\.\' wl1en
worlti11g in the database e11vironment. Tl1e terms entity, attribu te, and relationship are
fu11da1nental when disc11ssing databases. An entity is like a 11011n; it is a person , place,
tl1i11g, or eve11t. Tl1e entities of i11te rest to TAL Distribt1tors, for exa1nple, are such
tllings as c11ston1ers, orders, and sales re ps. The e11tities tl1at are of interest to a school
include st11dents, fac11lty, and classes; a real estate agency is iI1terested in clients,
l1ouses, and agents; and a 11sed car deale r is interested i11 vehicles, c11stomers, and
1nanufactt1rers.
Chapter 2
An attribute is a property of an entity. Tl1e term is t1sed here exactly as it is used
in eve ryday Englisl1. For tl1e enti ty person, for example, tl1e list of a ttribtites migl1t
in cltide stich tl1ings as eye color and height. For TAL Distribtitors, tl1e a ttribtites of
inte rest for tl1e e11tity customer are st1ch things as n ame, a.d dress, city, and so on . For
tl1e e nti ty faciilty at a sch ool , the a ttribtites \Votild be st1cl1 thi11gs as faculty 11t1mbe r ,
na1n e, office numbe r , pl1on e, a nd so on . For the entity vehicle a t a car dealersl1ip, tl1e
attribt1tes are st1cl1 tl1ings as tl1e vel1icle ide ntifica tion ntimber , mode l, color , year , and
so on .
A relationship is tl1e associa tion between entities. There is an associa tion between
ct1stom ers and sales reps, for example, a t TAL Distribt1tors. A sales rep is associated \Vitl1
all of l1is or l1er ctistome rs, and a ct1sto1ner is associa ted \Vitl1 l1is or l1er sales rep . Tecl1nically, yot1 say tha t a sales rep is relatecl to all of llis or l1er ct1stomers, and a ct1sto1n e r is
relatecl to llis or l1er sales rep .
Tl1e rela tio11ship bet\\reen sales reps and ct1stomers is an example of a one-to-many
relationship becatise one sales rep is associated witl1 m any ctistomers, btit each customer
is associa ted vvitl1 011ly one sales rep . (In this type of relationsl1ip, the \.\'Ord many is tised
in a \Vay tl1at is different fro1n everyday Englisl1; it migl1t not alv,,ays mean a large nt1n1ber .
In tl1is context, for example, the te rm many means tl1at a sales rep 111igl1t be associated
with any nt1mber of custome rs. Tl1at is, one sales rep can be associa ted \Vitl1 zero, 011e, or
more customers.)
Ho\v does a relational database handle entities, attribtites of entities, and rela tionsl1ips
be t\veen entities? En tities and attribtites are fa irly simple. Each entity has its ow11 table. In
tl1e TAL Distribtitors database, the re is one table for sales reps, 011e table for ctistome rs,
ai1d so on . The attribt1tes of an e11tity become tl1e colt1mns i11 the table. In tl1e table for
sales reps, for example, tl1ere is a coltimn for tl1e sales rep 11t1mbe r, a colt1m11 for tl1e sales
rep's first name, and so on .
Wl1a t about rela tionships? At TAL Distribtitors, tl1ere is a 011e -to-many re lationsl1ip
be t\veen sales reps and ctistome rs ( eacl1 sales rep is related to tl1e many ct1stom e rs
tl1at l1e or sl1e represents, and eacl1 ct1stome r is rela ted to tl1e 011,e sales rep wl10
represents the ct1sto1n e r). Ho\v is this re la tion ship imple me11ted in a relational
da tabase?
Con side r Figt1re 2 -1 again. If yot1 want to de termine tl1e 11ame of the sales re p
who represents Broolrings Direct (ct1sto1n e r ntimber 260), yot1 wotild locate tl1e row
for Broolrings Direct in tl1e CUSTONIER table a11d de termi11e tl1a t tl1e value for
REP_:t\TlJM is 30 . Then yot1 \VOtild loolr for tl1e rov,, i11 the REP table on whicl1 tl1e
REP_:t\TlJM is 30 . The one rep v\rith REP_Nill1I 3 0 is Mega11 Gradey, who represents
Broolti11gs Direct.
On tl1e otl1er hand, if yot1 \Vant to de te rmine the names of all the customers of tl1e
rep 11amed Rafael Campos, yot1 \Vottld locate tl1e row for Rafael Campos in the REP
table and de te rmine tha t tl1e value in the REP_NUM colt1m11 is 15 . Then yot1 \Vould loolr
for all the ro\vs in tl1e CUSTOMER ta ble on v,,l1icl1 tl1e REP_NUNI is 15. Afte r identifyi11g
Rafael Campos's rep 11t1mbe r , yot1 find tl1at tl1e ma1iy ct1stomers l1e represents are
Database Design Fundamentals
nttmbe red 126 (Toys Galo re), 502 (Cards and More), 713 (Cress Sto re), and 893
(All Season Gifts).
Yott impleme11t tl1ese rela tionsl1ips by h aving common col11mns in t\.vo or more tables.
Tl1e REP NUNI col11mn in the REP table and tl1e REP NUNI colttmn in the CUST OMER
table are ttsed to imple1n e nt tl1e rela tionsl1ip betwee11 sales reps and c11stome rs. Given a
sales rep , you cru1 11se these col11m ns to de termine all the custon1ers that l1e o r she repre sents; given a c11stome r, yott can ttse these col11mns to find tl1e sales rep wl10 represents
tl1e c11stomer .
In tl1is context , a re la tion is esse11tially a hvo-ditnen sion al table. If yott conside r the
tables sl10\.vn in Fig11re 2-1 , h oweve r, yott can see tl1at certa in restric ti ons are pla.c ed on
re la tions. Eacl1 col11mn l1as a 1111iq11e 11ame, and entries \Vitl1in eacl1 column sl1011ld
match, tl1is col11mn 11ame. For example, if tl1e col11mn n ame is CREDIT_LIMIT , all
entries in tl1at col11m11 m11st be credit lim its. In addition, eacl1 ro\.V sho11ld be ttniquewhe n t\.vo ro\\'S a re identical, the seco11d ro\.v does no t provide any ne\v i1uor 1n a tion .
Fo r m axim11m flexibility, the o rder of tl1e col11mns and rows sl1011ld be itnma te rial .
Finally, tl1e table's design sho11ld be as simple as possible by restricting each position to
a single entry a11d by preve11ting 1n 11ltiple entries (also called repeating groups) in a11
individ11al location in tl1e ta ble. Fig11re 2-2 sho\.vs a table d esign tha t incl11des rep eatil1g
groups.
ORDERS
ITEM_
NUM
NUM_
ORDERED
QUOTED_
PRICE
10/12/2015 126
CD33
5
$86.99
51610
10/12/2015 334
KL78
TR40
25
10
$10.95
$13.99
51613
10/13/2015 386
DL51
5
$104.95
51614
10/13/2015
260
FDll
1
$12-l.95
51617
10/15/2015 586
NL89
T\V35
4
3
$115.99
$116.95
51619
10/15/2015 126
FDll
2
$121.95
51623
10/15/2015 586
DR67
FH24
fill34
5
12
10
$29.95
$36.95
$13.10
51625
10/16/2015 796
tv1T03
8
$45. 79
ORDER
NUM
ORDER
DATE
51608
FIGURE 2-2
CUSTOMER_
NUM
Table with repeating groups
Fig11re 2-3 sho\\rs a better way to represent the sa1ne infor1natio11 sl1own i11 Figure 2-2.
111 Fig11re 2-3, every position in tl1e table conta ins a single valtte.
Chapter 2
ORDERS
ORDER_
NUM
ORDER_
DATE
CUSTOMER
NUM
ITEM
NUM
NUM_ QUOTED_
ORDERED
PRICE
51608
10/12/2015
126
CD33
5
$86.99
51610
10/12/2015
33-1
ICL78
25
$10.95
51610
10/12/2015
334
TR40
10
$13.99
51613
10/13/2015
386
DL51
5
$104.95
51614
10/13/2015
260
FDll
1
$124.95
51617
10/15/2015
586
NL89
4
$115.99
516]7
l 0/15/20] 5
586
T\\735
3
$])6.95
51619
10/15/2015
126
FDl 1
2
$]21.95
51623
10/15/2015
586
Dll67
:-,
~
$29.95
51623
10/15/2015
586
FH24
12
$36.95
51623
10/15/2015
586
I<D34
10
$13.10
51625
10/16/2015
796
1·IT03
8
$45.79
FIGURE 2-3
ORDERS table without repeating groups
vVl1en yot.1 re1nove the repeating grot1ps from Figt1re 2 -2, all of the rows in
Figt1re 2 -3 are single -valt1ed. Tl1is structt1re is formally called a relation. A relation
is a t\,,o-dimensional table in wl1ich the e11tries in tl1e table are single-valt1ed (eacl1
location i11 tl1e table contains a single entry), eacl1 colt1mn l1as a distinct name, all
valt1es in tl1e colt11nn match this name, the order of tl1e ro\vs and colt1mns is
immaterial, and each ro\v contains t1niqt1e valt1es. A relational database is a collectio11
of relations.
NOTE
Rows in a table (relation) are also called records or tuples. Columns in a table (relation) are also called
fields or attributes. This text uses the terms tables, columns, and rows unless the more formal terms of
relation, attributes, and tuples are necessary for clarity.
Tl1ere is a commonly accepted sl1ortl1and representation to sho\V the tables ru1d col111n11s in a relational database: for eacl1 table, yot1 \Vrite the 11ame of the table at1d tl1en
withi.11 pare11tl1eses list all of tl1e columns in the table. In this representation, eacl1 table
Database Design Fundamentals
appear s on its O\.Vn line. Using tl1is m ethod , yot1 represent tl1e TAL Distribt1tors d ata.base as
follows:
REP (REP NUM, LAST NAME I FI RST NAME I STREET I CI TY I STAT E I
POSTAL CODE , COMM I SSION , RATE )
CUSTOMER (CUSTOMER NUM , CUSTOMER NAME , STREET, CITY, STATE ,
POSTAL CODE , BALANCE , CREDI T L IM IT, REP NUM)
ORDERS (ORDER NUM, ORDER DATE , CUSTOMER NUM)
ORDER L I NE (ORDER NUM, I T EM NUM, NUM ORDERED, QUOTED PR ICE )
ITE M ( I T EM NUM, DESCR I PT I ON, ON HAND, CAT EGORY, STOREHOUSE , PRICE )
Notice tl1at som e tables co11tain colt1m11s witl1 dt1plicate names. For exrunple, tl1e
REP_NUM colt1mn appears in bo tl1 tl1e REP table and tl1e CUSTOMER ta ble . St1ppose a
sitt1ation existed \.Vl1erein som eon e (or the DBMS) migl1t conft1se the t,vo colt1mns. For
example , if yot1 "''rite REP_NUM, it is 11ot clear which REP_l\TlJM colt1mn yot1 want to t1se.
Yot1 n eed a mecl1anisn1 for indicating tl1e REP_NUM colt1m11 to wl1icl1 yot1 are refe rring.
One common approach to solving tl1is problem is to write both tl1e table name and tl1e
column 11ame, separated by a period . Tl1t1s , you wot1ld r efer e11ce the REP_NUi\11 coltimn in
tl1e CUSTOMER ta ble as CUSTOMER REP_NUM, ru1d the REP_l\TlJM coltimn iI1 tl1e REP
table as REP.REP_NUNI. Teclu1ically , "''hen yot1 refe ren ce colt1mns in tllis format ; yot1 s ay
tl1a t you qt1alify the nrunes. It is always acceptable to qt1alify colt1mn names, even wl1e11
tl1e re is n o potential for conft1sion . If conftisio n migl1t arise, ho\.vever , it is essentia l to
qualify colt11nn names.
FUNCTIONAL DEPENDENCE
Tl1e co11cept of ft111ction al de penden ce is c1ucial to u nders tanding the r est of the m aterial
in this chapter . Functional de p ende11ce is a formal 11ame for wl1a t is basically a siI11ple
id ea. To illt1s trate fun ctio11al dependence, st1ppose t11at tl1e REP table for TAL Dis tribt1tors
is strt1c tt1red as sl1ow11 in Figi1re 2-4. Tl1e only differ en ce be tween tl1e REP table shown i11
Figt1re 2-4 a11d tl1e 011e sh own in Figure 2-1 is the addition of a11 extra colt1n1n named
PAY CLASS.
REP
REP
NUM
LAST_
NAME
15
STREET
CITY
STATE
POSTAL_
CODE
Campos Rafael
724 \Tinca Dr.
Grove
CA
90092
$23,457.50 1
0.06
30
Gradey
1'fegru1
632 Liatris St.
Fullton
CA
90085
$41 ,317.00 2
0.08
45
'fia11
IIui
1785 'fyler Ave. Nortl1field CA
90098
$27,789.25 1
0.06
60
Sefto11
Janet
267 OakJey St.
90097
$0.00 1
0.06
FIGURE 2-4
FIRST_
NAME
Conga ree
CA
REP table with a PAY CLASS column
COMMISSION PAY
CLASS
RATE
Chapter 2
Sttppose that one of tl1e p olicies at 'f AL Dis tribtttors is that all sales reps in any given
pay class earn tl1eir co1nmission s at tl1e same r ate. To describe tllis sitt1ation, yott cot1ld say
tl1at a s ales rep 's pay class cletermines llis or l1er co1nmission rate. Alter11atively, you cot1ld
say that a sales rep 's commission rate depencls on his or h er pa.y class. 'fhis phrasing ttses
tl1e \Vords determines and clepends on in the same \Vay tl1a t you describe ft1nc tional de pendency. If yott \Vanted to be formal, yott wot1ld precede either expression witl1 tl1e \Vord
fi,1,nctiona lly . For example, yott might say, "A sales rep 's pay classfenctio·n ally determines
llis or l1er commission rate," and "A sales re p's commissio11 ratefe1ictionally clepends on
llis or l1er pay class." Yott can also defit1e fttnc tional dep ende 11cy by saying tl1at wl1en yott
lrnow a sales rep 's pay class, yott can determine l1is or h er commission rate.
In a relatio11al database, colttmn B is functionally dependent on anotl1er coltttnn ( or a
collection of colttmns), A, if at any point in titne a value fo r A de termines a single valtte
for B. Yott ca11 tl1inl{ of tl1is as follo\vs: wl1en yott are give11 a valtte for A, do you lrnow
tl1at you can fi11d a si11gle valt1e for B? If so, Bis fttnctionally dep e11dent on A (often written as A ➔ B). If B is fttnc tio11ally de pende11t on A, yott also can say that A functionally
determines B.
At TAL Dis tribt1tors, is tl1e LAST_NAME colttmn in tl1e REP table fttnc tionally dependent on tl1e REP_NUM colttmn? Yes, it is. If you are given a valtte for REP_NUNI, sttcl1 as
30, tl1ere is a single LAST_NAME , Gradey, associated \Vitl1 it. 'fhis is represented as:
REP- NUM ➔ LAST- NAME
Question: In the CUSTOMER table, is CUSTOMER_NAME functionally dependent on
REP NUM?
Ans,ver: No. Given the REP_NUM 30, for example, you ,vould not be able to find a single
customer name, because 30 appears on more tl1an one row in the table.
Question: In the ORDER_LINE table, is NUM_ORDERED functionally dependent on
ORDER NUM?
Answer: No. An ORDER_NUM might be associated with several items in an order, so
having just an ORDER_NUM does not provide enough information.
Qt.1estion: Is NUM_ORDERED functionally dependent on ITEM_NUM?
Answer: No. Again, just as with ORDER_NU?vl, an item number might be associated with
several lines in an order, so ITEM_Nillvl does not provide enough information.
Database Design Fundamentals
•
Question: On which columns in the ORDER_LINE table is NUM_ORDERED functionally
dependent?
Answer: To determine a value for NUM_ORDERED, you need both an order number
and an item number. In other words, NUNI_ORDERED is functionally dependent on the
combination (formally called the concatenation) of ORDER_NUM and ITEM_NUM.
That is, given an order number and an item number, you can find a single value for
NUM ORDERED.
At this poi11t, a question naturally arises: 110\.\' do yot.1 dete rmit1e functional dependencies? Can you d etermi11e the m by loolring a t sample data , for example ? Tl1e answer is 110.
Consider tl1e REP table in Figi1re 2-5 , in whicl1 last names are uniqt1e. It is very
tempting to say tl1at LAST_NAME ft1nctionally dete rmines STREET, CITY, STATE, and
POSTAL_ CODE (or equivale11tly that STREET, CITY, STATE, a11d POSTAL_CODE are all
ft1nc tionally depende11t on LAST_NAME) . After all, give11 tl1e last name of a re p , yot1 ca.n
find tl1e single address.
REP
REP
NUM
LAST_
NAME
15
STREET
CITY
STATE
POSTAL_
CODE
Can1pos Rafael
724 Vinca Dr.
Grove
CA
30
G radey
Megan
632 Liatris St.
Fu.J] ton
45
Tian
60
Sefton
FIGURE 2-5
FIRST_
NAME
COMMISSION
RATE
90092
$23,457.50
0.06
CA
90085
$41,317.00
0.08
Ilui
1 785 Tyler Ave. Northfield Ci\
90098
$27,789.25
0.06
Janet
26 7 OaWey St.
90097
$0.00
0 .06
Congaree
CA
REP table
\\'11at \\'Ot1ld happen if the last 11ame of rep 60 \.Vere also Campos? You \.Vould l1ave the
sitt1ation illustrated in Figi1re 2 -6. Because there are no\.v t\.vo reps \.vith the last name of
Campos, yot1 can 110 longer find a single address t1sing a re p's last name-yot1 \.Vere misled by
tl1e original data. The only "''ay to dete rmine ft1nctional dependencies is to exrunine tl1e
user's policies. Tllis process can involve discussions witl1 t1sers, an examinatio11 of t1ser doct1mentatio11, and so on . For exan1ple, if 1nanagers at TAL Distribt1tors l1ave a policy n ot to lure
two reps witl1 tl1e san1e last name, then LAST_NAME wot1ld indeed de termine tl1e otl1er
colt1mns. Witl1ot1t st1cl1 a policy, ho\.,,ever , LAST_NAME wot1ld n ot determine the other
colt1mns.
Chapter 2
REP
REP_ LAST_
NUM NAME
FIRST_
NAME
STREET
CITY
STATE
POSTAL_
CODE
COMMISSION
RATE
15
Campos Rafael
724 Vinca Dr.
Grove
CA
90092
$23,457.50
0.06
30
Gradey
11egan
632 Liatris St.
Fullton
CA
90085
$41,317.00
0.08
45
'firu1
Hui
1785 Tyler Ave. Northfield CA
90098
$27,789.25
0.06
60
Can,pos Janet
267 Oakley St.
90097
$0 .00
0.06
FIGURE 2-6
Congaree
CA
REP table with two reps named Campos
PRIMARY KEYS
Ai1other importa nt d atabase design concept is the prima ry l{ey. In the simplest terms, the
primary key is the 11nique identifier for a table. For example, the REP_NUM col11mn is the
unique identifier fo r the REP table . Given a rep number in the table, s11ch as 30, tl1ere will
only be one row on \Vllich that rep n t1mber occ11rs. Tl1us , tl1e rep numbe r 30 uniq11ely
identifies a ro\v (i11 tl1is case, the seco11d ro\v).
111 tl1is text, the definition of primary key needs to be more precise than j11s t a un ique
identifier fo r a table. Specifically, column A ( or a collection of col11mns) is tl1e primary
l{ey for a table if:
Proper ty 1 . All colum11s in tl1e table are f11nctionally dependent on A.
Proper ty 2 . No subcollectio11 of the colu11111s in A (ass111ning A is a collectio11 of
col11mns and not j11st a si11gle colum11) also has prope rty 1 .
Question: Is tlie CATEGORY column the primary key for th e ITEM table?
Ans,ver: No, because the other columns are not func tionally dependent on CATEGORY.
Given the category GME, for example, you cannot de termine an item number , description, or anything else, because there are seve ral rows on which the category is GME.
Q11estion: Is tlie CUSTOMER_NUM column the primary l{ey for the CUSTOMER table?
At1swer: Yes, because TAL Distributors assigns unique customer numbers. A specific
customer number cannot appear on more than one row. Thus, all columns in the
CUSTOMER table are func tionally dependent on CUSTOMER_NUM.
Database Design Fundamentals
Question: Is the ORDER_Nl.Th1 column the primary key for the ORDER_LINE table?
Ans,ver: No, because it does not functionally determine either NlThtI_ORDERED or
QUOTED_PRICE.
Question: Is the combination of the ORDER_Nfil/1 and ITEM_NUM columns the primary
l{ey for the ORDER_LINE table?
Ans,ver: Yes, because you can determine all columns by this combination of columns,
and, further, neither the ORDER_NUM nor the ITEM_NUM alone has this property.
Question: Is the combination of the ITE~I_NUM and DESCRIPTION columns the primary
l{ey for the ITEM table?
Answer: No. Although it is true that you can determine all columns in the ITEM table by
this combination, ITE~I_Nl.Thil alone also has this property.
Yott can indicate a table's primary liey with a sl1ortl1and representation of a database
by t1nderli11ing the colt1tn11 or collection of coli1mns that comprise the primary l{ey. Tl1e
comple te shortl1and representation for the TAL Distribt1tors database is:
REP (REP NUM, LAST NAME, FIRST NAME, STREET, CITY, STATE,
POSTAL CODE, COMMISSION, RATE)
CUSTOMER (CUSTOMER NUM, CUSTOMER NAME, STREET, CITY, STATE,
POSTAL CODE, BALANCE, CRE DIT LIMIT, REP NUM)
ORDERS ( ORDER NUM, ORDER DATE , CUSTOMER NUM)
ORDER LINE (ORDER NUM, ITEM NUM, NUM ORDERED, QUOTED PRICE)
ITEM (ITEM NUM, DESCRIPTION, ON HAND,CATEGORY, STOREHOUSE , PRICE)
NOTE
Sometimes you might identify one or more columns that you can use as a table's primary key. For
example, if the TAL Distributors database also included an EMPLOYEE table that contains employee
numbers and Social Security numbers, either the employee number or the Social Security number could
serve as the table's primary key. In this case, both columns are referred to as candidate keys. Like a
primary key, a candidate key is a column or collection of columns on which all columns in the table are
functionally dependent-the definition for primary key really defines candidate key as well. From all the
candidate keys, you would choose one to be the primary key.
Chapter 2
NOTE
According to the definition of a candidate key, a Social Security number is a legitimate primary key.
Many databases, such as those that store data about students at a college or university or those that
store data about employees at a company, store a person's Social Security number as a primary key.
However, many institutions and organizations are moving away from using Social Security numbers as
primary keys because of privacy issues. Instead of using Social Security numbers, many institutions and
organizations use unique student numbers or employee numbers as primary keys.
NOTE
Some institutions prefer to assign values to use as primary keys for items such as customer numbers,
item numbers, and student numbers. Others simply let the computer generate the values. In this case,
the DBMS simply assigns the next available value. For example, if the database has already assigned
customer numbers 1000 through 1436, it assigns the next new customer added to the database the
customer number 1437.
DATABASE DESIGN
Tl1is sectio11 prese11ts a specific 1netl1od yott ca11 folio"'' to desig11 a database wl1e11 give11
a set of reqt1ire111e11ts that tl1e database 1nt1st sttpport. Tl1e determi11ation of tl1e reqt1ire1nents is part of tl1e process know11 as syste111s a11alysis. A syste1ns a11alyst it1tervie"''S
users , exa111it1es existi11g a11d proposed docttments, a11d exami11es orga11izational policies to
determi11e exactly tl1e type of data 11eeds tl1e database mt1st sttpport. Tl1is text does 11ot
cover tllis a11alysis. Ratl1er, it focuses 011 l1ow to talce tl1e set of reqt1ire1ne11ts tl1at tl1is
process prodt1ces a11d deter1nit1e tl1e appropriate database desig11.
After prese11ting tl1e database desig11 n1etl1od , this sectio11 presents a sru11ple set of
reqt1ire1ne11ts and illt1strates tl1e desigi1 1netl1od by desigili11g a database to satisfy tl1ese
reqt1ire1ne11ts.
Design Method
To design a database for a set of reqt1ire1nents, co1nplete the follo\ving steps:
1.
2.
Read tl1e requirements, identify tl1e entities (objects) involved, and name the
e11tities. For exa1nple, \Vl1en the design i11volves departme11ts and employees,
you might ttse tl1e entity 11runes DEPARTMENT and EMPLOYEE. \\Tl1en the
desig11 involves ct1stomers a11d sales reps, you migl1t t1se tl1e entity names
CUSTONIER and REP .
Identify tl1e ttnique identifiers for the e11tities you identified in Step 1. For
example , wl1en 011e of the entities is ITEM, determi11e \.Vl1at inforn1atio11 is
reqt1it·ed to uniquely identify each individt1al item. In other words, what
Database Design Fundamentals
3.
4.
5.
6.
information does the organiza tion 11se to dis tinguish on e item from an other ?
Fo r tl1e ITEM entity, tl1e 11nique identifier for each item migl1t be ITEM_NUM;
for a CUSTOMER e11tity, tl1e 1111ique identifier 1nigl1t be CUST 011ER_l\TUM.
\\T11en n o 11niq11e identifier is ava ila ble from the d ata yo11 lu10\>v ab o11t tl1e
e11tity, yo11 need to create 011e. For exa1nple, yo11 migl1t use a 11nique numbe r
to identify item s \.Vh en n o item numbers exist.
Identify tl1e attributes fo r all the e11tities. These attributes beco1n e the colu11111s in the tables. It is possible for two or 1nor e e11tities to co11tai11 the sam e
attrib11tes. At TAL Distributors, fo r example, re ps and cus to1ner s both h ave
addresses, cities, sta tes, and postal codes. To cla rify tl1is duplicatio11 of attributes, follo\>v tl1e n am e of tl1e attribute \Vitl1 tl1e correspo11ding e11tity il1
p are11tl1eses. Tl1us, ADDRESS (CUSTOMER) is a cus tom er address and
ADDRESS (REP) is a sales re p address.
Identify tl1e f11nctional d ependencies tl1at exist among tl1e attributes. Aslr
yourself the followi11g q11estion : if yo11 know a uniq11e val11e for an attribute,
do you also kt1ow tl1e 11nique val11es for o tl1er attrib11tes? Fo r example, wl1en
you l1ave tlle three a ttrib11tes REP_NUNI, LAST_NAME, a11d FIRST_NANIE and
you lu1ow a 11nique val11e fo r REP_NUM, do you also know a 11niqu e val11e for
LAST_NANIE and FIRST_NANIE? If so, then LAST_NAME and FIRST_NANIE
ar e f11nc tion ally d ependent 011 REP_NUNI (REP_NUM ➔ LAST_NAME ,
FIRST_NANIE).
Use tl1e f11nc tio11al de penden cies to identify tl1e tables by placing eacl1 attrib11te witl1 the attribute or 1ninim11m co1nbin a tion of attrib11tes on \.Vhicl1 it is
f11nc tion ally depende11t . Tl1e attribute or attrib11tes fo r ai1 entity 011 whicl1 all
otl1er attributes are de p ende 11t \.Vill be tl1e primary l{ey of tl1e table. Tl1e
re mai11ing attrib11tes \.\Till be the other col11mns in the ta ble. O nce yo11 l1ave
d etermined all the col11mns in tl1e ta ble, you can give tl1e table an appropriate n am e. Us11ally the nam e \.Vill b e tl1e sam e as the 11am e yo11 identified fo r
tl1e entity in Ste p 1 .
Identify any relatio11sl1ips betwee11 ta bles. 1I1 som e cases, you migl1t b e able
to de tern1ine tl1e relation sl1ips diI·ectly from the r equirem ents. It 111igl1t be
clear, for example, tha t o ne rep is rela ted to 111aI1y c11s tom e rs a11d tl1a t eacl1
cu stom er is related to exactly 011e re p . \\Tllen it is n ot, look fo r m atchi11g colu11111s in the ta bles you c reated . For example, if botl1 tl1e REP table aI1d tl1e
CUSTONIER ta ble contain a REP NUNI colum11 a11d the val11es il1 tl1ese colu11111s mus t m a tcl1, you lmo\.\T tha t re ps aI1d cus to1ner s are rela ted . Tl1e fact
tl1a t the REP_NUM colu11111 is the prilnary key in the REP ta ble tells you tl1at
tl1e REP ta ble is tl1e one p art of tl1e relation ship a11d tl1e CUST OMER ta ble is
tl1e many p art of tl1e relatio nsl1ip.
I11 tl1e n ext section , you \.\Till apply this process to produce tl1e d esig11 fo r tl1e TAL
Dis tributors d ata base 11si11g tl1e collectio11 of require1nents tha t tllis d a ta b ase must
support.
Chapter 2
Database Design Requirements
Tl1e a11alyst has i11tervie\\red users and exan1ined documents at TAL Distributors. I11 tl1e
process, the analyst l1as deter111i11ed tl1at the database must support tl1e follo\.vi11g
require111ents:
1.
2.
3.
4.
5.
For a sales rep , s tore the sales rep's 11umber, last name, firs t 11ame, s treet
address, city, state, postal code, total c o111111ission, and con1111ission rate.
For a cus tomer , s to re the customer's ntimber , name, s treet address, city,
s tate, postal code, balance, ru1d credit li111it In additio11, s tore the ntimber ,
last name, and first name of tl1e sales rep \.vho represents tllis cus tom er . Tl1e
analyst l1as also de te rmined tha t a sales rep can represent many cus tomers,
bt1t a ctis tomer mtist have exac tly 011e sales rep (in o tl1e r \.Vords, a sales rep
must represent a ct1stom er; a ct1s to1ne r ca1111ot be represented by zero or
mo re ilian one sales reps).
For an item , s to re tl1e item 's 11t1mbe r, descriptio11, tinits on l1a11d , category ,
tl1e 11t1mber of tl1e storel1ot1se in ,vhicl1 tl1e ite m is loca ted, and tl1e price. All
t1nits of a partictilar ite m are stored in tl1e same s torel1ot1se.
For an order , sto re tl1e order number , o rde r date, number and 11ame of tl1e
customer that placed tl1e order , as \Veil as 11umber of the sales rep \\'110
represe11ts tha t cus ton1er .
For each line item \\rithin ru1 order , s to re the item n1.11nber a11d description ,
tl1e ntimber ordered, and tl1e quoted price. Tl1e analyst also obtained the follo\., ,ing i11formatio11 co11cemi11g orders:
a . There is 011ly one c1.1s tomer per o rder .
b . On a given o rder , tl1ere is at most one line ite1n for a given item . For
exa1nple, item AH74 cannot appear on several lines within tl1e sanie
order .
c. The quoted price 111igl1t differ from the actual price \\'l1en the sales rep
discounts a ce rtain item 011 a specific order .
Database Design Process Example
Tl1e follo\.ving s teps apply tl1e design process to tl1e requireme11ts for TAL Distrib1.1tors to
prod1.1ce the appropriate d atabase design :
Step 1: Tl1ere appear to be fotir entities: reps, ctistomers, ite111s, and orde rs. Tl1e
11a mes assigned to tl1ese e11tities are REP, CUSTOMER, ITEM, and ORDERS, respectively.
Step 2: Fro1n tl1e collectio11 of entities, review the d ata and de termine the 1.1niqt1e
identifier for each e11tity. For the REP, CUSTOMER, ITEM, a11d ORDERS entities, ilie
1.111iq1.1e ide11tifiers are the rep ntimber, c1.1sto1ner 11umber , item 11umber, and order 11umber , respectively. Tl1ese 1.1niq1.1e identifiers are named REP_NUM, CUSTOMER_NUM,
ITEM_NUM, and ORDER_NUM, respectively.
Step 3: Tl1e attribtites me ntioned in the first requi1·ement all refer to sales reps. Tl1e
specific attrib1.1tes 111e11tio11ed in tl1e req1.1ireme11t are tl1e sales rep's nt11nber , last name,
Database Design Fundamentals
first name, street a.d dress, city, sta te, postal code, total commission , and commission ra te.
Assigning appropriate 11ames to tl1ese attribt1tes prodt1ces the follo\.ving list:
REP NUM
LAST NAME
FIRST NAME
STREET
CITY
STATE
POSTAL CODE
COMMISSION
RATE
Tl1e attribt1tes mentioned in tl1e second reqt1irement refe r to ct1stomers. Tl1e specific
attribt1tes are tl1e ct1stome r's nt1mber, na me, street address, city, sta te, postal code, balan ce, and credit limit. The reqt1irement also me11tions tl1e 11t1mber, last nan1e, and first
nam e of the sales rep who represents tl1is ct1stome r. Assign ing appropriate names to these
attribt1tes prodt1ces the following list:
CUSTOMER NUM
CUSTOMER NAME
STREET
CITY
STATE
POSTAL CODE
BALANCE
CREDIT LIMIT
REP NUM
LAST NAME
FIRST NAME
Tl1ere are attributes n amed STREET, CITY, STATE, a11d POSTAL_CODE for sales
reps as well as att1ibt1tes n amed STREE'f , CITY, S'f A'f E, and POSTAL_CODE for
ct1stomers. To distingt1ish these a ttributes in the fit1al collection , follow tl1e n ame of tl1e
attribt1te by tl1e na me of the corresponding entity. For exa mple, tl1e street for a sales rep is
S'f REET (REP) and the street for a. ct1stomer is STREET (CUS'f OMER).
Tl1e attribt1tes mentioned i11 tl1e third reqt1irement refer to items. Tl1e specific attribt1tes are tl1e item 's nt1mber, description , tinits on l1and, category, number of tl1e storel1ot1se in which the item is located, and price. Assigning appropria te names to these
attribt1tes prodt1ces the following list:
ITEM NUM
DESCRI PTION
ON HAND
CATEGORY
STOREHOUSE
PRI CE
Chapter 2
Tl1e attribt1tes mentioned in the fot1rth reqt1irement refer to orders. 'fl1e specific attribt1tes i11clt1de tl1e order nt1mber, order date, nt1n1ber and name of the customer tl1at
placed tl1e order , and nt1mber of tl1e sales rep who represents the customer . Assigning
appropriate names to these attributes prodt1ces the follo\>ving list:
ORDER NUM
ORDER DATE
CUSTOMER NUM
CUSTOMER NAME
REP NUM
Tl1e specific attributes associated \\rith the state1ne11t i11 tl1e reqt1irements concerning
line items are tl1e order nt1mber (to de termine the order to \Vhicl1 tl1e line iten1 corresponds) , item nt1mbe r, description , nt1mber orde red, and qt1oted price. If the qt1oted price
n1t1st be the sam e as tl1e price, you cot1ld simply call it PRICE. According to reqt1irem ent
Sc, l1owever, tl1e qt1oted price migl1t differ from the price, so yot1 mt1st add the qt1oted
price to tl1e list. Assigning appropriate names to these attribt1tes prodt1ces tl1e follo\ving
list:
ORDER NUM
ITEM NUM
DESCRIPTION
NUM ORDERED
QUOTED PRI CE
Tl1e comple te list grouped by entity is as follo\.\rs:
REP
REP NUM
LAST NAME
FIRST NAME
STREET (REP )
CITY (REP )
STATE (REP )
POSTAL CODE (REP )
COMMISSION
RATE
CUSTOMER
CUSTOMER NUM
CUSTOMER NAME
STREET (CUSTOMER)
CITY ( CUSTOMER)
STATE (CUSTOMER )
POSTAL CODE (CUSTOMER)
BALANCE
Database Design Fundamentals
CRE DIT LIMIT
REP NUM
LAST NAME
FIR ST NAME
ITEM
ITEM NUM
DE SCRIPTION
ON HAND
CATEGORY
STOREHOUSE
PRI CE
ORDER
ORDER NUM
ORDER DATE
CUSTOMER NUM
CUSTOMER NAME
REP NUM
For line items \.Vitl1in an order :
ORDER NUM
ITEM NUM
DE SCR I P TION
NUM ORDERED
QUOTE D PRI CE
Step 4: The fact tl1at the unique ide11tifier for sales reps is tl1e rep number gives tl1e
followiI1g fi1nctional dependencies:
REP NUM ➔ LAST NAME , FIRST NAME , STREET (REP ) , CITY (REP ), STATE (REP ),
POSTAL CODE (REP ), COMM I SS I ON, RATE
Tl1is notation indicates that the LAST_NA11E, FIRST_NANIE, STREET (REP), CITY
(REP), STATE (REP), POSTAL_CODE (REP), COi\tIMISSION, and RATE are all functionally dependent on REP_NUM.
Tl1e fact that the uniqt1e identifier for customers is the ct1stomer ni1mber gives tl1e
followiI1g fi1nctional dependencies:
CUSTOMER NUM ➔ CUSTOMER NAME, STREET (CUSTOMER ), CITY (CUSTOMER ),
STATE (CUSTOMER ), P OSTAL CODE (CUSTOMER ), BALANCE , CREDIT L IMIT,
REP NUM, LAST NAME, F IRST NAME
Chapter 2
Question: Do you really n eed to include the last name and first name of a sales rep in
the list of attributes de termined by tl1e customer number?
Answer: There is no need to include them in this list, because they both can be de termined from the sales rep number and are already included in the list of attributes determined by REP_NUM.
Tl1us , tl1e fu11c tion al de pende ncies for tl1e CUSTOMER e11tity are as follo\\7S:
CUSTOMER NUM ➔ CUSTOMER NAME , STREET (CUSTOMER ), CI TY (CUSTOMER ), STATE
( CUSTOMER ), P OSTAL CODE ( CUSTOMER ), BALANCE , CREDIT L I MIT, REP NUM
Tl1e fact tl1a t tl1e u11ique identifie r for item s is the item 11u1nber gives the follo,vi11g
func tion al de pe11de11cies:
I TEM NUM ➔ DE SCR I PTION, ON HAND, CATE GORY, STOREHOUSE , PRICE
Tl1e fact tl1a t tl1e u11ique ide11tifie r for order s is tl1e orde r 11umber gives tl1e following
func tion al de pe11de11cies:
ORDER NUM ➔ ORDER DATE , CUSTOMER NUM, CUSTOMER NAME , REP NUM
Question: Do you really need to include the name of a customer and the number of the
custome r's rep in the list of attributes de termined by the order number ?
Ans,ver: There is no need to include the customer name and the rep number in this list,
because you can determine them from the customer number and they are already
included in the list of attributes determined by CUSTOMER_NUM.
Tl1e ft111c tional de pe nde11cies for tl1e ORDERS e11tity are as follows:
ORDER NUM ➔ ORDER DATE , CUSTOMER NUM
Tl1e fi11al a ttribt1tes to be exa1ni11ed are tl1ose associa ted \Vith tl1e li11e ite1ns \Vitl1i11 tl1e
orde r : ITEM_l\TUNI, DESCRIPTION, NUM_ORDERED, a11d QUOTED_PRICE .
Question: Why are NUM_ORDERED and QUOTED_PRICE not included in the list of
attributes determined by the order numbe r?
Al1s,ver: To uniquely identify a particular value for NUM_ORDERED or QUOTED_PRICE,
ORDER_NUM alone is not sufficient. It requires the combination of ORDER_NUM and
ITEM NUM.
Database Design Fundamentals
Tl1e following sho rthand representa tion indicates tl1at the combina.tion of ORDER_NUM
a11d ITENI_NUM fttnc tion ally dete rmines NUM_ORDERED a11d QUOTED_PRICE:
•
ORDER NUM, I T EM NUM ➔ NUM ORDERED, QUOTE D PRI CE
Question: Does DESCRIPTION need to be included in this list?
Ans,ver: No, because DESCRIPTION can be determined by the ITEM_NUM alone, and it
already appears in the list of attributes dependent on the ITEM_NUM.
Tl1e complete lis t of fu11ctional d ependencies is as follo\vs:
REP NUM ➔ LAST NAME , FI RST NAME , STREET (RE P), CITY (REP ), STATE (REP ),
POSTAL CODE (REP ), COMM I SS I ON, RATE
CUSTOMER NUM ➔ CUSTOMER NAME , STREET (CUSTOMER ), CITY (CUSTOMER ), STATE
(CUSTOMER ), POSTAL CODE (CUSTOMER ), BALANCE , CREDIT LIMIT, REP NUM
ITE M NUM ➔ DE SCRI PTION, ON HAND, CATE GORY, STOREHOUSE , PRI CE
ORDER- NUM ➔ ORDER- DATE , CUSTOMER- NUM
ORDER NUM, ITEM NUM ➔ NUM ORDERED, QUOTE D PR I CE
Step 5: Using tl1e ft1nc tio11al depende ncies, yot1 cai1 create tables v.rith the attribt1te(s)
to tl1e left of the arrov., being the prim ary lrey ai1d the a ttribt1te(s) to tl1e rigl1t of the arro\V
being the o tl1er colt1mns. For r ela tions correspondi11g to tl1ose entities ide11tified i11 Step 1 ,
yott can use tl1e n atne you already de termined . Becattse you did not ide11tify an y entity
tl1at had a t1niqt1e identifier tl1a t vvas tl1e combination of ORDER_NUM a11d ITE11_NUM,
yott need to assign a na me to the table whose primary Irey consis ts of tl1ese two colt1mns.
Because this table represen ts tl1e individt1al lines vvithin a11 order, tl1e naine ORDER_LINE
is a good cl1oice. The final collectio11 of ta bles is as follovvs:
REP (REP NUM, LAST NAME, FI RST NAME , STREET, CITY, STATE , P OSTAL CODE ,
COMMI SSION, RAT E )
CUSTOMER (CUSTOMER NUM, CUSTOMER NAME , STREET, CITY, STATE , P OSTAL CODE ,
BALANCE , CR EDIT LIMI T, REP NUM)
ITE M (ITEM NUM, DESCR I P TION, ON HAND, CAT EGORY, STOREHOUSE , PRICE )
ORDERS ( ORDER NUM, ORDER DATE , CUSTOMER NUM)
ORDER LINE (ORDER NUM, I T EM NUM, NUM ORDERED, QUOTED PR ICE )
Step 6: Examining the tables and ide ntifying common colt1mns gives the following list
of rela tionsllips be tvveen the tables:
•
Tl1e CUSTONIER and REP tables are rela ted usit1g the REP_J\TUM colt1n1ns.
Becat1se the REP_NUM column is the pritnar y key for the REP table, tllis
indicates a 011e-to-many r ela tionship between REP and CUST OMER ( 011e r ep
to m an y ct1s tom ers).
Chapter 2
•
•
•
Tl1e ORDERS a11d CUSTOMER tables are related ttsing tl1e CUS'fOMER_NUNI
colt1mns. Because the CUSTOMER_NUM colu1nn is the primary l{ey for
tl1e CUSTOMER table, tl1is indicates a one-to-many rela tionship betwee11
CUSTOMER and ORDERS (one cttstomer to many orders).
Tl1e ORDER_LINE and ORDERS tables are related using the ORDER_NUNI
colt1mns. Becat1se the ORDER_l\TUNI colt1mn is the primary l{ey for the
ORDERS table, this indicates a one-to-many relationship behveen ORDERS
a11d ORDER_LINE (one orde r to many order lines).
Tl1e ORDER_LINE and ITEM tables are related usi11g the ITEM_NUNI
colttmns. Becat1se the ITEM_NUM colttmn is tl1e p1imary l{ey for tl1e
ITEM table, tl1is indicates a one-to-many relationsl1ip beh,reen ITENI and
ORDER_LINE (one item to many order lines).
NORMALIZATION
After c reatil1g the database design, you mt1st a11alyze it to make st1re it is free of potential
problems. To do so, you follo\v a process called normalization, ill whicl1 you identify tl1e
existen ce of potential problems, sucl1 as data dt1plicatio11 and redttndancy, and implement
ways to correct tl1ese problems.
Tl1e goal of 11ormalization is to co11vert unnormalized relations (tables tl1at satisfy the
definitio n of a relation except tl1at they might contain repeati11g grottps) i11to variotts types
of normal forms . A table ill a particular norn1al form possesses a certain desil·able collection of properties. Although the re are several 11ormal forms, tl1e most com111011 are first
11ormal form, seco11d norn1al form , and third norn1al form. Norn1alizatio11 is a process in
which a table tl1at is i11 first normal form is be tte r than a table that is not ill fil·st normal
form, a table tl1a t is in seco11d 11ormal form is better than one tl1at is in first normal form ,
and so 011. Tl1e goal of tllis process is to allow you to take a table or collection of tables
and prodt1ce a ne\v collectio11 of tables tl1at represents the same illlormation but is free of
problems.
First Normal Form
According to the definition of a relation, a relation (table) cannot contain a repea ting
grottp in which mi1ltiple entries exist on a single ro\v. Ho\vever, in tl1e database design
process, yott migl1t crea te a table tl1at has all tl1e o ther properties of a relation, bttt contains a repeating grottp. Removing repeating grot1ps is the starting p oint \Vl1en converting
an t1nnormalized collection of data into a table that is in first normal form. A table (relation) is in first normal form (lNF) \Vl1en it does not contain a repeating grot1p.
For example, in the design process yott might create tl1e following ORDERS table, in
which the re is a repea ting grottp consisting of ITEM_NUNI and NUNI_ORDERED. The
no tation fo r tl1is table is as follows:
ORDERS (ORDER NUM, ORDER DATE ,
(ITEM NUM, NUM ORDERED))
Database Design Fundamentals
Tl1is n otation desc1ibes a ta ble n am ed ORDERS tl1at con sists of a primary l{ey,
ORDER_l\Tl.Th1, and a col11mn 11amed ORDER_DATE. Tl1e in11er pare11tl1eses iI1dica te a
repeating group that contai11s two col11m11s , ITENI_NUM and NUM_ORDERED. Tl1is table
contains one row pe r order \Vitl1 val11es i11 tl1e ITEM_NUNI and Nill1_ 0RDERED col11mns
for each o rde r \Vith the nu1nber ORDER_NUM and placed on ORDER_ DATE. Fig11re 2 -7
sl1ows a single order \Vitl1 m11ltiple combinations of an item number and a corresponding
n11mber of 11nits orde red .
ORDERS
ORDER
NUM
ORDER_
DATE
ITEM
NUM
NUM_
ORDERED
51608
10/12/2015 CD33
:)
5] 6 ) 0
J 0/]2/2015 JU,78
TR40
25
10
51613
10/13/2015 DJ_,51
:,
51614
10/13/2015 FDl l
1
51617
10/15/2015 t-.TL89
'l'vV35
4
3
51 619
10/] 5/2015 l<'D11
2
51623
10/15/2015 DR67
FII24
l<D34
:,
12
10
10/16/2015 M'f 03
8
51625
FIGURE 2-7
-
-
-
Unnormalized order data
To co11vert tl1e table to first n ormal form , yo11 remove the re peating group as follows:
ORDERS (ORDER NUM, ORDER DATE , ITEM NUM, NUM ORDERED)
Fig11re 2-8 sl1ows tl1e table in first n ormal form.
Chapter 2
ORDERS
ORDER
NUM
ORDER_
DATE
ITEM
NUM
NUM_
ORDERED
51608
10/12/2015 CD33
:)
5)6]0
] ()/] 2/2015 JGJ78
25
51610
10/12/2015 TJl40
10
51613
10/13/2015 DJJ51
5
51614
10/13/2015 FDll
1
51617
10/15/2015 l\11,89
4
51617
10/15/2015 1'W35
3
51619
10/15/2015 FDll
2
51623
10/15/2015 DR67
5
51623
10/15/2015 FII2-l
12
51623
10/15/2015 1(1)34
10
51625
10/16/2015 M1'03
8
FIGURE 2-8
-
Order data converted to first normal form
In Figt1re 2-7 , the second rovv indicat es that item I<L78 and item TR40 are both
inclttded in order 51610. In Figt1re 2-8, this information is represented by two ro\.vs, the
second and tl1ird. 'fl1e primary Irey for the t1ru1ormalized ORDERS table vvas the
ORDER_NUM colttmn alone. The primary Irey for the normalized table is no\.v tl1e combination of tl1e ORDER- NUM and I'fEM- NUM colt1mns.
Wl1en yott con vert an ttnnormalized table to a table in first normal form , the primary
Irey of tl1e table in firs t normal form is usttally the primary Irey of the ttnnormalized table
concatenated with tl1e Irey for the repeating grottp. The Irey for tl1e repea ting grot1p is tl1e
colt1mn in the repeating grot1p that disti11gt1isl1es one occt1rrence of the repeating grot1p
from anotl1er. In tl1e ORDERS table, I'fEM_NUM was tl1e Irey to the repea ting grot1p and
ORDER_NUM was the primary Irey fo r the table. \\Then converting the t1nnor1nalized data
to first normal form, the primary Irey becomes tl1e concatenation of tl1e ORDER_NUNI and
ITEM NUM colttmns.
Second Normal Form
Tl1e follov\7ing ORDERS table is in first norn1al form, because it d oes not contai11 a repeating grot1p:
ORDERS (ORDER NUM, ORDER DATE , ITEM NUM, DESCRIPTION,
NUM ORDERED, QUOTED PRI CE)
Database Design Fundamentals
Tl1e table contains the following f11nctional dependencies:
ORDER NUM ➔ ORDER DATE
ITEM NUM ➔ DE S CRIPTION
ORDER NUM, ITEM NUM ➔ NUM ORDERED, QUOTE D PRI CE
Tl1is notati on indicates tha t ORDER_NUM alone determines ORDER_DATE, and
ITEM_NUM alone dete rmines DESCRIPrf ION, b11t it req11ires botli ORDER_NUM and
ITENI_NUM to de termine eitl1er NUM_ORDERED o r QUOTED_PRICE. Consider tl1e sa mple of tl1is table sl1own in Fig11re 2-9.
ORDERS
ORDER
NUM
ORDER_
DATE
NUM_
ORDERED
QUOTED_
PRICE
51608
10/12/2015 CD33
\Vood Bloclc Set (48 piece)
~
;)
$86.99
51610
10/12/2015 I<L78
Pick Up Sticks
25
$10.95
51610
10/12/2015 TR40
Tic Tac Toe
10
$13.99
51613
10/13/2015 DLSl
Classic Railv; av• Set
;)
~
$104.95
51614
10/13/2015 l;,Dl l
Roclting Horse
1
$124.95
51617
10/15/20] 5 NL89
\\'ood Block Set (62 piece)
4
$115.99
51617
10/15/2015 T\¥35
Fire Engine
3
$116.95
51619
10/15/20]5 l<'D1 J
Rocking Horse
2
$121.95
5] 623
10/15/2015 DR67
Giant Star Brain Teaser
5
$29 .95
5]623
J ()/] 5/2015 FH24
Puzzle Gift Set
12
$36.95
51623
10/15/2015 I<D34
Pentom inoes Brain 'feaser
10
$13.10
51625
10/16/2015 NITOJ
Zaubc rkasten Brain Teaser
8
$45 .79
FIGURE 2-9
ITEM_
NUM
DESCRIPTION
Sample ORDERS table
Altl1011gl1 tl1e ORDERS table is in first normal fo rm (beca11se it contains 110 repeating
gro11ps), problems exis t within tl1e table that req11ire yo11 to restr11c ture it.
Tl1e description of a specific item , FDll for example, occ11rs twice in the table. rfhis
d11plication (fo rmally called redundancy) ca11ses several problems. It is certainly wastefttl
of space, bttt that is not nea rly as serio11s as some of the other problems. These o the r proble ms are called update anomalies and they fall into four ca tegories:
1.
Updates: If yo11 11eed to cl1ange to the description of item FDll , yott mus t
cl1ange it t\vice-once in eacl1 row on which item FDll appears. Updating
tl1e item desc1iption m ore tha11 once malres the 11pdate process m11ch mo re
c11mbersome a11d time cons11ming.
Chapter 2
2 . Inconsistent data: There is no tl1ing abottt the design tl1at prohibits item FDll
from having t\\ro di:,{ferent descriptions in the database. In fact , if item FDll
occurs on 20 rows in tl1e table, it is possible for tl1is item to l1ave 20 different
descriptio11s in tl1e database.
3. 1\dditions: V\The11 you try to add a 11e\\' item a11d its descriptio11 to tl1e database, you "''ill face a real proble1n. Because the primary lrey for the ORDERS
table co11sists of botl1 ORDER_NUM and ITE1'.1l_NUM, you 11eed values for bo tl1
of these colu1m1s to add a ne\\' ro\\' to the table. If you add a11 item to the
table tl1at does 11ot yet l1ave ai1y o rders, "''l1at do you use for ORDER_NUM?
Tl1e only solutio11 is to create a du11uny ORDER_NUM and tl1en replace it
,,vitl1 a real ORDER_NU11 once a11 order for this item is actually received .
Certainly, tl1is is no t an a cceptable solutio11.
4 . Deletions: If you delete orde r 51608 from the database and it is the only
orde r tha t contai11s item CD33, deleting the order also deletes all information
about item CD33. For example, yott \Vould no longer know tha t item CD33 is
a 48-piece wood blocl{ set .
Tl1ese problems occur because the DESCRIPTION col111nn is depe11dent on only a
portion of tl1e p1ima ry key (ITEM_NUNI), and not on the complete primai·y key. Tl1is situation leads to tl1e definition of seco11d normal form. Second normal form represe nts an
improvement over first normal form beca11se it elin1inates ttpda te anomalies in tl1ese
sitt1atio ns. A table (rela tion) is in second normal form (2NF) wl1en it is in first normal
form and no nonkey column (that is, a col111nn that is not part of the primary key) is
depe ndent on 011ly a portion of the primary key.
NOTE
When the primary key of a table contains only a single column, the table is automatically in second
normal form.
You can identify the fu11dame11tal problem with the ORDERS table: it is 11o t in second
11ormal fo rm. Altho11gh it is importa nt to identify the problem , what you really need is a
1nethod to correct it; yott want to be able to conve rt tables to second normal form. First ,
ta ke eacl1 subset of the set of col11mns that malre up the primary l{ey, and begit1 a new
table witl1 tllis st1bset as its primary key. For the ORDERS table, the 11e\\' desig11 is:
(ORDER NUM,
( I T EM NUM,
(ORDER NUM, I TEM NUM,
Next, place each of tl1e otl1e r colt11nns witl1 tl1e appropriate primary key; tl1at is, place
eacl1 one \Vitl1 tl1e 1n i11imal collectio11 of col11rm1s 011 wl1ich it depends. For tl1e ORDERS
table, add the new colu1m1s as follows:
(ORDER NUM, ORDER DATE )
( I T EM NUM, DE SCR I PT I ON)
(ORDER NUM, I TEM NUM, NUM ORDERED, QUOTE D PRI CE )
Database Design Fundamentals
Each of tl1ese ne\.,, tables is given a descriptive name based on the mea11i11g and contents of tl1e table, stich as ORDERS , ITEM, and ORDER_LINE. Figi1re 2-10 sl10\.vs samples
of these tables.
ORDERS
ORDER_ ORDER_
NUM
DATE
'
JO/] 2/2015
-
ITEM_
NUM
DESCRIPTION
NUM_
ORDERED
QUOTED_
PRICE
- - -----------
\Vood Block Set (48 piece)
51610
10/]2/2015 I<JJ78
Pick Up 8ticks
25
$10.95
51610
10/12/2015 TR40
1()/13/20 15 D[,51
Tic Tac Toe
10
Classic Raihvay Set
:)
-
$13.99
$104.95
Roc.:king
,. HQrse
1
$124.95
51617
10/13/2015 FDll
10/15/2015 NL89
\Vood Block Set (62 piece)
-l:
$115.99
51617
10/15/2015 1' \V35
Fire Engine
3
$116.95
51619
10/15/2015 FD11
Rocking IIorse
2
$121.95
51623
10/1 5/2015 DR67
Giant Star Brain Teaser
:)
$29.95
51623
10/15/2015 FTl24
Pu1,zle Gift Set
12
$36.95
51623
10/15/2015 I<DJ4
Pentorninoes Brain Teaser
10
$13.10
51625
10/16/2015 1IT03
Zaubcrkasten Brain Teaser
8
$45.79
51613
5161-l:
-
',
.
.
'
ORDERS
ORDER_
NUM
ITEM
ORDER_
DATE
51610
10/12/2015
51613
51614
51617
51619
10/13/2015
10/]3/2015
51623
51623
ORDER_LINE
10/15/2015
10/15/2015
10/J 5/2015
10/16/2015
CD33
DL51
DR67
D\\T23
FDll
FII2-l:
l<Al2
l<D3-I-
ITEM NUM
NUMORDERED
QUOTED PRICE
CD33
5
Skittles
i\7ood Block Set (48 piece)
Classic Raihvay Set
Giant Star Brain Teaser
51608
51610
51610
51613
516]4
KL78
?_:)
TR40
10
Dl,51
s
FDll
]
$86.99
$10.95
$13.99
$104.95
$12-1-.95
l\1ancala
Rocking IIorse
51617
51617
l\rJ,89
Puzzle Gift Set
Cribbage Set
Pento1ninoes 81-~lin Teaser
51619
-l:
3
2
l\·fT03
l\11,89
Pick Up Sticks
Zauherkasten Brain Teaser
\Vood Block Set (62 piece)
TR-1-0
TW35
Tic Tac Toe
Fire Engine
KL78
FIGURE 2-10
ORDERNUM
51623
5162.3
5 1623
51625
ORDERS table converted to second normal form
T\\'35
FD11
Dllo7
FI12-1
I\D34
11T03
~
:)
12
10
8
$115.99
$116.95
$121.95
$29.95
$36.95
$13.10
$45.79
Chapter 2
In Figi1re 2-10, con verting tl1e origi11al ORDERS table to a ne\.v ORDERS table,
a11 ITEM table, and an ORDER_LINE table elimi11ates tl1e ttpdate anomalies. A descriptio n appears ortly once for eacl1 item, so yott do not l1ave tl1e redttnd ancy tl1at exis ted
in tl1e original t.'lble d esign . Changing tl1e description of item FDll from Roclting
Ho rse to Deli1xe Roclting Ho rse, fo r example, is novv a simple process involving a
single cl1ange. Becai1se tl1e d escription for an item occi1rs in a single place, it is not
possible to have mi1ltiple description s for a single item in tl1e database at tl1e sam e
time.
To add a 11evv item and its description , yott c rea te a nev,, r o"'' in the ITEM table,
rega rdless of vvhe the r that item has pending or acti1al orders. I11 addition, deleting o rder
51608 does not delete item ni1mber CD33 fro1n the database becai1se it still exis ts i11 tl1e
ITEM table. Finally, yott l1ave 11ot lost any il1formation by co11verting tl1e ORDERS table to
second nor1nal form. Yott ca11 reco11st1uct tl1e data in tl1e o riginal table from the d ata i11
tl1e 11ew tables.
Third Normal Form
Problems cai1 still exist vvitl1 tables tl1at are i11 second 11ormal form. For example, suppose
tl1at you create the follov,,ing CUSTOMER table:
CUSTOMER (CUSTOMER NUM, CUSTOMER NAME , BALANCE, CREDIT LIMIT, REP NUM,
LAST NAME, FIRST NAME )
Tl1is table l1as the follov,ring functional depende11cies:
CUSTOMER NUM ➔ CUSTOMER NAME , BALANCE, CREDIT LIMIT, REP NUM, LAST NAME,
FIRST NAME
REP NUM ➔ LAST NAME , FI RST NAME
CUSTOMER_NUM detern1i11es all the o tl1er colu11111s. In additio11, REP_NUM de ter1nines LAST- NAlvIE and FIRST - NAlvIE.
\\Then a table's pril11ary l~ey is a sil1gle column, the table is automatically il1
seco11d normal form . (If the table vvere 11o t it1 second 11or1nal for1n, some colu1nn
would be dependent on o nly a po-rtion of tl1e pritnary key, vvl1icl1 is impossible vvhe11
tl1e primary key is just 011e colum11.) Tl1us, tl1e CUST011ER table is il1 seco11d normal
for1n .
Altl1ough tllis table is il1 seco11d normal form , Figi1re 2-11 sl1ov\'S tl1at it still possesses
update problems silnilar to tl1ose ide11tified for tl1e ORDERS table shovv11 il1 Figure 2-9.
I11 Figure 2-11, tl1e sales rep 11ame occttrs 111any ti1nes in the table.
Database Design Fundamentals
CUSTOMER
CUSTOMER
NUM
CUSTOMER_NAME
BALANCE
CREDIT_ REP_ LAST_
LIMIT NUM NAME
126
'l'oys Galore
$1,210.25
$7,500.00 15
Campos Rafael
502
Cards and More
$5,025.75
$5,000.00 15
Ca n1pos Rafael
7)3
Cress Store
$4,234.60 $10,000.00 15
Ca1npos Rafael
893
All Season (1ifts
$ 935.75
260
Brooltings Direct
$ 575.00 $1 0,000.00 30
G radey
Megan
386
J olmson 's Department Store
$879.25
$7,500.00 30
Gradey
,\,fegan
665
Cricket Gift Shop
$ 678.90
$7,500.00 30
G radey
wi egan
824
Kline's
$ 2,475.99 $15,000.00 30
Gradey
wi egan
334
'l' he Everything Sh op
$2,345.75
$7,500.00 45
'L'ian
11 ui
440
Grove llistorical Mt1seum Store
$ 345.00
$5,000.00 45
'f ian
I-Jui
586
1\ln1ondton Gen eral Store
$3,456.75 $15,000.00 45
Tian
Ilui
796
Unique Gifts
Tian
Hui
FIGURE 2-11
$124.75
$7,500.00 15
$7,500.00 45
FIRST_
NAME
Can1pos Rafael
Sample CUSTOMER table
Tl1e redunda11cy of inclt1ding a sales rep n11mber and name in tl1e CUSTOMER table
results in tl1e same set of problems that existed for tl1e ORDERS table. In additio11 to the
proble1n of \\7asted space, yo11 have the following ttpdate anomalies:
1.
2.
3.
4.
Updates: Changing tl1e sales rep name reqt1ires changes to m11ltiple rows in
tl1e table.
Inconsistent data: Tl1e design does no t prol1ibit m11ltiple iterations of sales
rep names in tl1e data.base. For example, a sales rep might represe11t 20 c11stomers and l1is or h er name migl1t be entered 20 diffe rent ways i11 tl1e table.
Additions: To add sales rep 85 (Nlarily11 Perry) to tl1e database, sl1e must
represent at least one customer. If Ma1ilyn does no t yet represe11t any
c11stomers, yo11 eitl1er caru1ot record tl1e fact tl1at l1er name is Nlarilyn Perry
or yo11 must crea te a ficti tious customer fo r l1er to represent 11ntil she represents ai1 act11al custo1ner . Neitl1er of these solutions is desirable.
Deletions: If yott delete all tl1e custo1ners of sales rep 15 from the database,
you will also lose all information about sales rep 15.
Tl1ese ttpdate anomalies are d11e to tl1e fact that REP_NUM de termines LAST_NAME
and FIRST_NA1\1E, bttt REP_NUM is not the primary l{ey. As a result, tl1e same REP_Nl.Thtl
and conseq11ently tl1e same LAST_NANIE and FIRST_NAME can appear 011 many different
rows.
Chapter 2
Yott h ave seen tl1at tables in second n ormal form re present an improvem ent over
tables in firs t normal form , b11t to eliminate problem s witl1 ta bles in seco11d n o rmal fo rm ,
yo11 n eed an even be tter s trategy for cr eating tables. Tl1ird 11orm al form provides tl1at
strategy. Befor e lool{ing at tl1ird n ormal fo rm , 110\.vever , yo11 n eed to becom e familiar
with the sp ecial n ame tl1at is give11 to any column that d e ter1nines anotl1er col11mn (lil{e
REP_l\TUiVI i11 tl1e CUSTOMER ta ble). An y colt1mn (or collection of col111nns) tl1at d ete rmines anotl1er col11mn is called a determinant. A table's primary l{ey is a de termil1ant.
In fact , by definition , any candida te l{ey is a de terminant. (Re me mber that a candidate
l{ey is a col11m11 o r collection of col11m11s tl1at co11ld f11nc tion as the prin1ary l{ey.) In
Fig11re 2-11 , REP_NU1vI is a d e terminant, but it is n ot a candidate l{ey, and tl1a t is tl1e
problem .
A table is in third normal form (3NF) "'rl1e 11 it is in second n o r1nal fo rm and the 0 11ly
determinants it co11ta ins are candidate l{eys.
NOTE
This text's definition of third normal form is not the original definition. This more recent definition,
which is preferable to the original, is often referred to as Boyce-Codd normal form (BCNF) when it
is important to make a distinction between this definition and the original definition. This text does not
make such a distinction but will take this to be the definition of third normal form.
No\.v yo11 l1ave identified the proble111 \.Vitl1 tl1e CUSTOMER table: it is 11o t i11 tl1ird
11o rmal fo r1n . Tl1ere are sever al ste ps fo r co11verti11g tables to third 11o r1nal for111 .
Firs t , for eacl1 de tern1ina11t tl1at is 11ot a ca11didate l{ey, re1nove fron1 tl1e ta ble
tl1e colu1ru1s tl1a t de pend 011 tl1is de termi11a11t (but d o 11o t r e1nove tl1e de te rn1i11a11t).
Next, create a 11e\.v table contai11i11g all tl1e col111n11s from tl1e origi11al table tl1a t
de pe11d 011 tl1is d e ter1ni11a11t. Fi11ally, n1al{e tl1e de ter111ina11t tl1e prilnary l{ey of tl1is
11e\.v ta ble.
I11 tl1e CUSTOMER table, for example, r e1nove LAST_N1\NIE and FIRST_NAME
beca11se tl1ey depe11d on fue de te r111i11a11t REP_NUM, \.\7hicl1 is 11ot a ca11didate l{ey. A ne\.v
table, REP, is formed , con sis ting of REP_l\TUM as tl1e pri111a ry key, a11d tl1e col1111111s
LAST_NAME a11d FIRST_NAME, as follo'v\7s:
CUSTOMER (CUSTOMER NUM, CUSTOMER NAME , BALANCE , CREDIT L I MIT, REP NUM)
and
REP (REP NUM, LAST NAME , FI RST NAME )
Figt1re 2-12 sh ows tl1e origm al CUSTOMER table a.11d tl1e tables c reated \.\7l1en converting tl1e origil1al ta ble to tllird 11ormal for1n .
Database Design Fundamentals
CUSTOMER
CUSTOMERNUM
CUSTOMER_NAME
126
502
713
893
260
386
665
824
334
440
586
796
Toys Galo1·e
Cards and N[ore
Cress Store
All Season Gifts
Brookings Direct
Johnson 's Department Store
Cricket Gift Shop
!Gine's
The Everything Shop
Grove 1-Iistorical 1"1useum Store
i-\ln1ondton General Store
Unique Gifts
BALANCE
CREDIT_
LIMIT
REPNUM
$1,210.25 $7,500.00
$5,025.75 $5,000.00
$4,234.60 $10,000.00
15
15
15
$7,500.00 15
$10,000.00 30
$7,500.00 30
$7,500.00 JO
LAST_ FIRST_
NAME NAME
Campo
Campo
Campo
Campo
Gradey
Gradey
Gradey
Gradey
Tian
Tian
Tian
Tian
$935.75
$575.00
$879.25
$678.90
$2,475.99 $15,000.00 30
$2 ..3-15.75 $7,500.00 45
$345.00 $5,000.00 45
$3,456.75 $15,000.00 45
$124.75
$7,500.00 45
Rafael
Rafael
Rafael
Rafael
1"Iegan
1[egan
?.[egan
lvlegan
llu.i
Hui
llui
Hui
,
•
I
I
'
CUSTOMER
CUSTOMER_
NUM
CUSTOMER_NAME
BALANCE CREDIT_LIMIT REP _NUM
126
260
334
386
440
502
586
665
713
796
Toys Galore
Brookings Direct
The Everything Shop
Johnson's Departn1ent Store
Grove Ilistorical 1luseurn Store
Cards and 1lore
Almondton General Store
Cricket Gift Shop
Cress Store
Unique Gifts
$1,210.25
$575.00
$2,345.75
$879.25
$345.00
$5,025.75
$3,456.75
$678.90
824
893
JUine's
AU Season Gifts
$4,234.60
$124.75
$2,475.99
$7.500.00 15
$10,000.00 JO
$7,500.00 45
$7,500.00 30
$5,000.00 45
$5,000.00 15
$15,000.00 45
$7,500.00 30
$10,000.00 15
$7,500.00 45
$15,000.00 JO
$935.75
$7,500.00 15
REP
45
60
FIGURE 2-12
Gradey
Tian
Sefton
N[egan
llui
Janet
CUSTOMER table converted to th ird normal form
Has tllis new desig11 for tl1e CUSTOMER table corrected all of the previously identified
problems? A sales rep's name appears only 011ce, tl1us avoidi11g redu11dai1cy and simplifying tl1e process of storing a sales rep's name. This design prollibits a sales rep from having
.
Chapter 2
different names in the database. 'f o add a n e\v sales rep to the database, yo11 add a ro\v to
tl1e REP table; it is not necessary for a new rep to represent a ct1stomer. Finally, deleting
all customers of a give11 sales rep will 11ot remove tl1e sales rep's record from tl1e REP
table, retaining the sales rep's name in tl1e database. Yo11 can reconstr11ct all tl1e data in
tl1e original table from tl1e data in the ne\\' collection of tables. 1\ll previo11sly 1nentioned
problems l1ave it1deed bee11 solved.
Question: Conver t the following table to third normal form. In this table, STUDENT_NUM
determines STUDENT_NAME, NlTh1_CREDITS, ADVISOR_Nm,,I, and ADVISOR_NAME.
ADVISOR- NUNI determines ADVISOR- NANIE. COURSE- NUM determines DESCRIPTION.
The combination of a STUDENT- NUM and a COURSE- NUM determines GRADE.
STUDENT (STUDENT NUM, STUDENT NAME, NUM CREDITS, ADVISOR NUM,
ADVISOR NAME, (COURSE NUM, DESCRIPTION, GRADE))
Answer: Comp le te the following steps:
Step 1: Remove the repeating group to convert the table to first normal form, as follows:
STUDENT (STUDENT NUM, STUDENT NAME, NUM CREDITS, ADVISOR NUM,
ADVISOR NAME, COURSE NUM, DESCRIPTION, GRADE)
The STUDENT table is n ow in first normal form because it has no repeating groups.
It is not, however , in second normal form because STUDENT_NAME is dependent only
on STUDENT_NUM, which is only a portion of the primary l{ey.
Step 2: Convert the STUDENT table to second normal form. First, for each subset of
the primary key, start a table with that subset as its l{ey yielding the following:
(STUDENT NUM,
(COURSE NUM,
( STUDENT NUM, COURSE NUM,
Next, place the rest of the columns with the smallest collection of columns on ,vhich
they depend, as follo,vs:
(STUDENT NUM, STUDENT NAME, NUM CREDITS, ADVISOR NUM, ADVISOR NAME)
(COURSE NUM, DESCRIPTION)
(STUDENT NUM, COURSE NUM, GRADE)
Finally, assign na.m es to each of the ne,v tables:
STUDENT (STUDENT NUM, STUDENT NAME, NUM CREDITS, ADVISOR NUM,
ADVISOR NAME)
COURSE (COURSE NUM, DESCRIPTION)
STUDENT COURSE (STUDENT NUM, COURSE NUM, GRADE)
Although these tables are all in second normal form, the COURSE and GRADE tables
are also in third normal form. The STUDENT table is not in third normal form, however,
because it contains a determinant (ADVISOR_NUM) that is not a candidate key.
Database Design Fundamentals
Step 3 : Convert the STUDENT table to third normal form by removing the column
that depends on the determinant ADVISOR_NmI and placing it in a separate table, as
follows:
(STUDENT NUM, STUDENT NAME, NUM CREDITS, ADVISOR NUM)
(ADVISOR NUM, ADVISOR NAME )
Step 4 : Name the tables and put the entire collection together, as follows:
STUDENT (STUDENT NUM, STUDE NT NAME , NUM CREDITS, ADVISOR NUM)
ADVISOR (ADVISOR NUM, ADVISOR NAME )
COURS E (COURS E NUM, DESCR IPTION)
STUDENT COURSE (STUDENT NUM, COURSE NUM, GRADE )
DIAGRAMS FOR DATABASE DESIGN
For m any people , an illus tratio11 of a database's s trt1c ture is quite t1seful. A popt1lar type of
illt1s tration used to represent the s trt1c ture of a da tabase is tl1e entity-relationship (E-R)
diagra1n. In an E-R diagra1n, a rectangle represents an entity (table). One-to-man y relationsl1ips bet\,reen e ntities are dra,,,n as lines bet,veen tl1e correspo11d i11g rectangles.
Several different styles of E-R diagrams are t1sed to diagram a d atabase design . In tl1e
version sho,vn in Figt1re 2-13, an arro\\rl1ead i11dicates tl1e many side of tl1e relatio nsl1ip
bet\veen tables. In tl1e rela tio nship bet\veen tl1e REP a nd CUST OMER tables, for example ,
tl1e arrow points fr on1 tl1e REP table to tl1e CUSTOMER table, indica ti11g tl1at one sales rep
is related to m any ct1stome rs. Tl1e ORDER_LINE table l1as two one-to-ma11y rela tionsl1ips,
as indicated by tl1e line from the ORDERS table to tl1e ORDER_LINE table and tl1e line
from tl1e ITEM table to tl1e ORDER LINE table.
Rectangle
represents an
entity
REP
CUSTOMER
ORDERS
FIGURE 2-13
Arrow represents
a one-to-many
relationship
Arrowhead points
to the many part of
the relationship
I - - - -~
ORDER_LINE l◄,C------1
IT EM
E-R diagram for the TAL Distributors database with rectangles and arrows
Chapter 2
NOTE
In this style of E-R diagram, you can put the rectangles in any position to represent the entities and
relationships. The important thing is that the arrows connect the appropriate rectangles.
A11other style of E-R diagram is to represe11t tl1e many side of a relationsl1ip bet\.veen
tables with a crow's foot, as shown in Figure 2-14.
REP
CUSTOl'v'lEI~
ORDERS
FIGURE 2-14
Crow's foot
represents the many
part of the relationship
ORDER LINE
)
ITEM
E-R diagram for the TAL Distributors database with a crow's foot
Tl1e E-R diagra1n shov.rn i11 Figt1re 2-15 represe11ts tl1e origi11al style of E-R diagra1ns.
111 tl1is style , relatio11sl1ips are iI1dicated in dia111011ds tl1at describe tl1e relatio11sl1ip.
Tl1e relatio11ship betwee11 tl1e REP and CUSTOMER tables, for exa1nple , is 11a1ned
REPRESENTS , reflectiI1g tl1e fact tl1at a sales rep represe11ts a ct1sto1ner. Tl1e relatio11sl1ip
bet\.vee11 tl1e CUSTOMER a11d ORDERS table is 11amed PLACED, reflecti11g tl1e fact tl1at
ct1stomers place orders. Tl1e relationsllip behvee11 tl1e ORDERS a11d ORDER_LINE tables
is 11a1ned CONTAINS, reflectiI1g tl1e fact tl1at ai1 order co11taiI1s order li11es. Tl1e relatio11ship bet\.vee11 tl1e ITEM a11d ORDER_LI:t\TE tables is 11a1ned IS_ ON, retlecti11g tl1e fact tl1at a
give11 ite111 is 011 ma11y orders. 111 tl1is style of E-R diagra111 , the 11t1mber 1 iI1dicates the one
side of the relatio11sl1ip a11d tl1e letter n represe11ts tl1e many side of tl1e relatio11sl1ip.
Database Design Fundamentals
REP
One part of
a relationship
Diamond rep resents
and describes a
relationship
Many part of
a relationship
CUSTOMER
l
11
ORDERS
FIGURE 2-15
1
n
n
--,QRDER_LINEI--<
1
ITEM
E-R diagram for the TAL Distributors database with named relationships
Chapter 2
Chapter Summary
•
An entity is a person, place, thing, or event. An attribute is a property of an entity.
A relationship is an association between entities.
•
A relation is a two-dimensional table in which the entries in the table contain only single values, each column has a distinct name, all values in a column match this name,
the order of the rows and columns is immaterial, and each row contains unique
values. A relational database is a collection of relations.
•
Column B is functionally dependent on another column, A (or possibly a collection of
columns), when a value for A determines a single value for B at any one time.
•
Column A (or a collection of columns) is the primary key for a relation (table), R, if a//
columns in R are functionally dependent on A and no subcollection of the columns in A
(assuming A is a collection of columns and not just a single column) also has property 1.
•
To design a database to satisfy a particular set of requirements, first read the requirements and identify the entities (objects) involved. Give names to the entities and identify the unique identifiers for these entities. Next, identify the attributes for all the
entities and the functional dependencies that exist among the attributes, and then use
the functional dependencies to identify the tables and columns. Finally, identify any
relationships between tables by looking at matching columns.
•
A table (relation) is in first normal form (1 NF) when it does not contain a repeating
group. To convert an unnormalized table to first normal form, remove the repeating
group and expand the primary key to include the original primary key along with the
key to the repeating group.
•
A table (relation) is in second normal form (2NF) when it is in first normal form and no
nonkey column (that is, a column that is not part of the primary key) is dependent on
only a portion of the primary key. To convert a table in first normal form to a collection
of tables in second normal form, take each subset of the set of columns that make up
the primary key, and begin a new table with this subset as its primary key. Next, place
each of the other columns with the appropriate primary key; that is, place each one
with the minimal collection of columns on which it depends. Finally, give each of these
new tables a name that is descriptive of the meaning and contents of the table.
•
A table is in third normal form (3NF) when it is in second normal form and the only
determinants (columns on which at least one other column depends) it contains are
candidate keys (columns that could function as the primary key). To convert a table in
second normal form to a collection of tables in third normal form, first, for each determinant that is not a candidate key, remove from the table the columns that depend on
this determinant (but do not remove the determinant). Next, create a new table containing all the columns from the original table that depend on this determinant. Finally,
make the determinant the primary key of this new table.
•
An entity-relationship (E-R) diagram is an illustration that represents the design of a
database. There are several common styles of illustrating database design that use
shapes to represent entities and connectors to illustrate the relationships between
those entities.
Database Design Fundamentals
Key Terms
one-to-many
relationship
attribute
Boyce-Codd normal
form (BCNF)
field
candidate key
qualify
concatenation
function ally
dependent
record
third normal form
(3NF)
database design
functionally determine
redundancy
tuple
determinant
nonkey column
relation
unnormalized relation
entity
entity-relationship
(E-R) diagram
normal form
relational database
update anomaly
normalization
relationship
first normal form
(1 NF)
primary key
repeating group
second normal form
(2NF)
Review Questions
1. What is an entity?
2. What is an attribute?
3. What is a relationship ? What is a one-to-many relationship?
4. What is a repeating group?
5. What is a relation?
6. What is a relational database?
7. Describe the shorthand representation of the structure of a relational database. Illustrate
this technique by representing the database for Colonial Adventure Tours as shown in
Figures 1-4 through 1-8 in Chapter 1.
8. How do you qualify the name of a field, and when do you need to do this?
9. What does it mean for a column to be functionally dependent on another column?
10. What is a primary key? What is the primary key for each of the tables in the Colonial
Adventure Tours database shown in Chapter 1?
11. A database at a college must support the following requirements:
a.
b.
For a department, store its number and name.
For an advisor, store his or her number, last name, first name, and the department
number to which the advisor is assigned.
c. For a course, store its code and description (for example, MTH110, Algebra).
d. For a student, store his or her number, first name, and last name. For each course
the student takes, store the course code, course description, and grade earned.
Also, store the number and name of the student's advisor. Assume that an advisor
might advise any number of students but that each student has just one advisor.
Design the database for the preceding set of requirements. Use your own experience as a student to determine any functional dependencies. List the tables, columns, and relationships. In addition, represent your design with an E-R diagram.
Chapter 2
12. Define first normal form.
13. Define second normal form. What types of problems might you encounter using tables that
are not in second normal form?
14. Define third normal form. What types of problems might you encounter using tables that are
not in third normal form?
15. Using the functional dependencies you determined in Question 11 , convert the following
table to an equivalent collection of tables that are in third normal form.
STUDENT (STUDENT NUM, STUDENT LAST NAME , STUDENT FI RST NAME ,
ADVISOR NUM, ADVISOR LAST NAME , ADVISOR FIRST NAME , (COURSE CODE ,
DESCR I P TION, GRADE ))
CRITICAL
TH INKING
C RITICAL
TH INKING
16. List the changes you would need to make to your answer for Question 11 if the requirements change so that a student can have more than one advisor.
17. List the changes you would need to make to your answer for Question 11 if the requirements change so that you must store the year and the semester in which a student took a
course and received a grade.
Exercises
T AL Distributors
Answer each of the following questions using the TAL Distributors data shown in Figure 2-1 . No
computer work is required .
1. Indicate the changes (using the shorthand representation) that you would need to make to
the original TAL Distributors database design (see Figure 2-1) to support the following
requirements. A customer is not necessarily represented by a single sales rep, but can be
represented by several sales reps. When a customer places an order, the sales rep who
gets the commission on the order must be in the collection of sales reps who represent the
customer.
2. Indicate the changes (using the shorthand representation) that you would need to make to
the original TAL Distributors database design to support the following requirements. There
is no relationship between customers and sales reps. When a customer places an order,
any sales rep can process the order. On the order, you need to identify both the customer
placing the order and the sales rep responsible for the order. Draw an E-R diagram for the
new design.
3. Indicate the changes (using the shorthand representation) that you would need to make to
the original TAL Distributors database design in the event that the original Requirement 3 is
changed as follows. For an item, store the item's number, description, category, and price.
In addition, for each storehouse in which the item is located, store the number of the storehouse, the description of the storehouse, and the number of units of the item stored in the
storehouse. Draw an E-R diagram for the new design.
Database Design Fundamentals
4. Using your knowledge of TAL Distributors, determine the functional dependencies that exist
in the following table. After determining the functional dependencies, convert this table to an
equivalent collection of tables that are in third normal form.
ITE M (ITE M NUM, DESCRIPTION, ON HAND, CATEGORY, STOREHOUSE , PR ICE ,
(ORDER NUM, ORDER DATE , CUSTOMER NUM, CUSTOMER NAME , NUM ORDERED,
QUOTE D PRICE ) )
C RITICAL
THINKING
5. Indicate the changes you need to make to the TAL Distributors database to support the following additional requirement. Each storehouse has a manager who is identified by a manager number, a manager last name, and a manager first name.
Colonial Adventure Tours
Answer each of the following questions using the Colonial Adventure Tours data shown in
Figures 1-4 through 1-8 in Chapter 1. No computer work is required.
1. Using the types of entities found in the Colonial Adventure Tours database (trips, guides,
customers, and reservations), create an example of a table that is in first normal form but
not in second normal form, and an example of a table that is in second normal form but not
in third normal form. In each case, justify your answers and show how to convert to the
higher forms.
2. Identify the functional dependencies in the following unnormalized table. Convert the table
to third normal form.
TRIP (TRI P ID, TRIP NAME , STATE ABBREVIATION, STATE NAME ,
(GUIDE NUM,
GUI DE LAST, GUIDE FI RST) )
C RITICAL
THINKING
3. Colonial Adventure Tours is considering offering outdoor adventure classes to prepare
people to participate in hiking, biking, and paddling adventures. Only one class is taught on
any given day. Participants can enroll in one or more classes. Classes are taught by the
guides that Colonial Adventure employs. Participants do not know who the instructor for a
particular class will be until the day of the class. Colonial Adventure Tours needs your help
with the database design for this new venture. In each step, represent your answer using
the shorthand representation and a diagram. You may use any of the styles presented in
this chapter for the diagram.
a. For each participant, list his or her number, last name, first name, address, city,
state, postal code, telephone number, and date of birth.
b. For each adventure class, list the class number, class description, maximum number
of people in the class, and class fee .
c. For each participant, list his or her number, last name, first name, and the class
number, class description, and date of the class for each class in which the participant is enrol led.
d. For each class, list the class date, class number, and class description; and the
number, last name, and first name of each participant in the class.
Chapter 2
Solmaris Condominium Group
Answer each of the following questions using the Solmaris Condominium Group data shown in
Figures 1-9 through 1-13 in Chapter 1. No computer work is required .
1. Determine the functional dependencies that exist in the following table , and then convert
this table to an equivalent collection of tables that are in third normal form.
LOCAT I ON (LOCATION NUM, LOCAT I ON NAME,
(UNIT NUM, SQR FT , BDRMS,
BAT HS, CONDO FEE ))
2. Determine the functional dependencies that exist in the following table , and then convert
this table to an equivalent collection of tables that are in third normal form.
----
CONDO UNI T ( CONDO ID, LOCAT I ON NUM, UN I T NUM, SQR FT, BDRMS, BAT HS ,
CONDO F EE , OWNER NUM, LAST NAME , F IRST NAME )
C RITICAL
TH INKING
3. Solmaris Condominium Group has many condos that are available as weekly vacation rentals. Design a database to meet the following requirements, using the shorthand representation and a diagram of your choice.
a. For each renter, list his or her number, first name, middle initial, last name, address,
city, state, postal code, telephone number, and email address.
b. For each property, list the condo location number, condo location name, address,
city, state, postal code, condo unit number, square footage, number of bedrooms,
number of bathrooms, maximum number of persons that can sleep in the unit, and
the base weekly rate.
c. For each rental agreement, list the renter number, first name, middle initial, last
name, address, city, state, postal code, telephone number, start date of the rental,
end date of the rental, and the weekly rental amount. The rental period is one or
more weeks.
C H A PTER
CREATING TABLES
OBJECTIVES
•
Create and run SOL commands
•
Create tables
•
Identify and use data types to define columns in tables
•
Understand and use nulls
•
Add rows to tables
•
View table data
•
Correct errors in a table
•
Save SOL commands to a file
•
Describe a table's layout using SOL
INTRODUCTION
You already might be an experienced user of a database management system (DBMS). You might find a
DBMS at your school's library, at a site on the Internet, or in any other place where you retrieve data using
a computer. In this chapter, you will begin your study of Structured Query Language (SOL), which is one
of the most popular and widely used languages for retrieving and manipulating database data.
In the mid-1970s, SOL was developed as the data manipulation language for IBM's prototype
relational model DBMS, System R, under the name SEQ UEL at IBM's San Jose research facilities. In
1980, the language was renamed SOL (but still pronounced sequel although the equally popular pronunciation of S-Q-L [ess-cue-e/1] is used in this text) to avoid confusion with an unrelated hardware
product named SEQUEL. Most DBMSs use a version of SOL as their data manipulation language.
In this chapter, you will learn the basics of working in SOL. You will learn how to create tables
and assign data types to columns. You also will learn about a special type of value, called a null
value, and learn how to manage these values in tables . You will learn how to insert data into your
tables after you create them . Finally, you will learn how to describe a table's layout using SOL.
CREATING AND RUNNING SQL COMMANDS
You accomplish tasks in SQL by creating and rt1nning conunands 1.1sing a DBMS tl1at
s1.1pports SQL. Tllis text 1.1ses Oracle as the DENIS in \.VWcl1 to create and rt1n SQL
conunands. The text also indicates differences yo1.1 \.Vill fi11d if yo1.1 are 1.1sing Microsoft
Access or Nlicrosoft SQL Server.
Altl1ougl1 the versio11 of Oracle used in this text is the Oracle Database llg Express
Edition, tl1e com111a11ds used in tWs text should work in a11y other version of Oracle.
Chapter 3
Yott can do\\rn load and install tl1e Oracle Da tabase llg Express Edition for free from the
Oracle \Veb site (www.oracle.com).
Using the Oracle Database 11 g Express Edition
After i11stalling the Oracle Database llg Express Editio11, run it u sing wl1atever metl1od
you prefer for ru1111i11g a11 app. Yo11r browser will ope11 tl1e I-Iom e page for tl1e Express
Editio11, as shov.r11 i11 Figure 3-1 .
ORACLE" Oracle Database XE 11 .2
Sessions
- - Ston,ge
Storage
View curreotty used storage.
Parameters
Application
Express
Application Express
Storage>
- -
Sessions
View curreol database sessions
Sessions>
Parameters
Voew lnlbaliZalion paramete,s
Parametei s >
Appliution Express
Gel started with Oraele Application Express
FIGURE 3-1
Li nks
to additional
resources
Links
> Online Help
> Leaming UtJrary
> Oraele Tecnnotogy Network
> oraele SOL Developer
> Oraele Express Ed1Uon
> Oracle Appllcallon Express
> Oraele JOevetoper 11g
> Pre-l>ullt Developer VMS
A11plic11tio11 Express >
Oracle Database 11 g Express Edition home page
On tl1e Home page for tl1e Express Editio n , cliclr Application Express. Figure 3-2 sl10\\'S
tl1e page tl1at opens next , \.\rl1icl1 req11ests yo11 to e11ter the 11sername and password given to
yo11 by the OBA (database ad1ninistrator) database r ole. (Aslr yo11r instn1c tor \Vhicl1 11sername
a11d password to 11se, or 11se tl1e on e you specified \Vhen yo11 installed the soft\vare.)
Enter username for
user-granted DBA
\.
"---.__database role her~
)
Login
Usemame
Login J
- j
Password
Login
button
)
Logln as a da abase user which has been granted the DBA database role (for example, SYSTEM).
- Enter password for "\
user-granted DBA
database role here
FIGURE 3-2
Entering the usemame and password for a OBA user
After entering your OBA database role username and p assword, cliclr tl1e Login
b11tton. Fig11re 3-3 sho\VS the page that op ens next, \Vhich le ts yo11 create a new workspace ,
a work area that allows 1n1tltiple 11sers to worli witl1 tl1e same installation of Oracle \Vhile
lieeping tl1eir objects and data private.
Creating Tables
Application Express
selected
I ORACLE' Oracle Database XE 11 .2
Storage
Sessions
Welcome SYSTEM logout
Username of;~- - --l---'f-~
Parameters
DBA user
Home
Click to log in to an
existing workspace
Oracle Application Express
Create Application Express Workspace
Creates a new
workspace
[ Cancel
Database User ® Create New
0 Use Existing
Getting Started
Create Workspace
Create
Workspace
button
~ Password
1----
--..i( Already have an account? Login Here
J
To get started with Oracle Application Express, create a
workspace. You will need to specify:
• Database Usemarne • Name of the database user to
be aea1ed
.-+Cl · Apptlcallon Express Us&maine • Your logtn name for
the Application Express Workspace
• Password • Password ot both your database user
and Application Express user
Once aeated, you will be able to login to your
Application Express workspace uslng these aeden5als
Conlinm Password
Enter the database
username, Application
Express username, and
passwords here
FIGURE 3-3
Logout
button
Information on
creating and using
a workspace
Creating a new workspace
To create a new worlIBp ace, enter a worl{space 11sername and a database 11sernam e. (Yott
c an 11se the same 11sernan1e for botl1 to l{eep things simple.) 'fhen yo11 \.vill enter a11d confitm
a pass\.vord, \.Vl1icl1 will apply to both tl1e worl{sp ace and da tabase. 'fhe combination of a
worlIBpace 11se111ame, da tabase 11se111ame , and a password is called c redentials. Afte r clicldng
tl1e Login button , clicl{ tl1e Create Worl{space bt1tton , a11d the n clicl{ tl1e click here linl{ to log
it1 to tl1e worl{space. After creating the \.Vorl{space, yo11 can log bacl{ in by cliclting tl1e "Already
l1ave a11 accotmt? Login Here" b11tton sho\.vn it1 Figt1re 3 -3 , and entering the worlIBpace
c redentials. Fig11re 3-4 sh o\.vs the page t1Sed to log in to an Application Express \.VorlIBpace.
Workspace name
in this example is
PRATT/LAST
Enter Appllcauon Expre s workSpace and credentials
worl<Space t'RATT/LAST
Login button
>--- ( Login ) ' - - - - -- -~
-
X
--,
Olde here to le.am how to get 5buted
Link to additional
information on
getting started
FIGURE 3-4
Username in
t his example is also
PRATT/LAST
Logging in to an Application Express workspace
Enter the
password here
Chapter 3
Afte r logging in to the vvorh.space, yo11 will see the Or acle Application Express hom e
page shovv11 in Fig11r e 3 -5. Yo11 cliclr tl1e ico11s on the l1om e page to access tl1e var io11s
tools. lt1 tl1is text, yo11 vvill 11se tl1e SQL Vlorl{sl1op tool. (The o tl1er tools are beyond tl1e
scope of this bool{.)
Currently logged in
as PRATT/LAST
Logout link
ORACLE' Application Express
•
Welcome PRATT/LAST ( Logouj l
"
•
Icons for
availab le t o ols
Help button
Learn more
l\jljJ6calion Express is a rapid Web
application development tool lhat
lets you share data and create
appUcaliOns. Using onry a Web
browser and llmlte<I programming
experience. you can develop and
deploy appications lhat are fast
and secure.
Appllcabon Buildef
SOL Woll<shop
Team Development
Admlnostration
News I
ftlF>'
SOL Workshop
icon
FIGURE 3-5
Oracte APEX 4.2 ls avallallle fMore
lnlormabonJ
Oracle Application Express home page
'f o 11se SQL \\Torl{shop, clicl{ the SQL \1/orl{shop icon to open the page sh ovvn in
Fig11re 3 -6. T o 11se an SQL \1/orl{shop tool, cliclr tl1e icon for the desired tool.
ORACLE" Application Express
Welc<lme PRATT/I.AST ( Logoyt l
,_
Icons for
ava ilable t ools
l
Tile SOL Workshop provides tools
to view and manage database
objeds. To create new database
objeds clldt on Ille Object
Browser icon Ulen didt lhe Create
button
Learn more
Objed Browser
SOL Commands
SOL Scripts
SOL Command s
,con
FIGURE 3-6
Query Bwlder
SOL Script s
.
icon
Utililies
Links t o
add it ional
resources
SOL Workshop page
Fig11re 3 -7 sl1ovvs tl1e SQL Scripts page, wl1ich opens after yot1 clicl{ the SQL Scripts
icon . 'f l1e SQL Scripts page shovvn i11 Fig11re 3-7 does not yet display any scripts. (A script
is a file that contains a saved con1mand , "' 'hicl1 yo11 can rttn late r. Y011 vvill lea rn m ore
abot1t scripts later in tl1is chapter .)
Creating Tables
ORACLE' Applica tion Express
Welcome PRATT/LAST ( LogoUI J
Breadcrumbs
"
Home
SOL Workshop
SQL Scnpts
SOL Scripts page
is t he current page
( Delete Checked )
Upload >
Create >
Manage Resuns
}! ~-----~<Go) (:: @ ( Actions • )
No data found.
ShowOUotas
ExpQ,tt.-- - -
Creates a script
that you upload
from a file containing
t he commands
FIGURE 3-7
Click to creat e
a new script by
entering its
commands
SOL Scripts page
Notice tl1e "Home> SQL Worlrshop > SQL Scripts" text tha t is displayed near tl1e top
of the SQL Scripts page sl10\\711 in Fig11re 3-7. Tllis referen ce is called a breadcrumb. Yott
can clicl{ the text in the breadc1umb to quicltly display the pages. For example, to retur11
to tl1e home page, cliclr I-fame in the breadcr11mb. To move baclr to the SQL Workshop
page, clicl{ SQL Worksliop in the breadcr11mb.
Tl1e SQL Scripts page sl10\.vn in Figure 3-8 shows two existing scripts, named Drop
TAL Database and Create TAL Database. Tl1e p e11cil icon in tl1e Edit col11mn le ts you edit
tl1e selected script; tl1e button in the R11n colum11 le ts yo11 run the selected script. \\T11en
you n1n a script, Oracle exec11tes the commands saved in the file.
ORACLE' Application Express
Welcome PRATT/LAST ( Loqou, )
"'
..
Melp
selected script
Search box
to locate an
exist ing script
c_
Script uploaded. You may cfte1k on die. script l;O edit or run it.
I
( Delete Checked )( Upload> )( Creal~> )
Manaoe Resulls
Ir~ ~[-----~'(
Go )
Show Quotas
( :: @ ( Actions• )
U- t · C
ExPort
■·
Edit
0
../
PRATT/I.AST
O,op TAL Database
PRATT/LAST
5 seconds ago
101
0
/
PRATT/I.AST
Cteate TAL Database
PRATT/I.AST
64 seconds ago
5,125
_
N41111!
iJ
att!d
~
esulls
Ruo
lmPort
Runs the
selected scrip t
N ame of
exist ing script
Click to edit the
selected script
Click the check
box to select
a script
FIGURE 3-8
Two scripts displayed on the SOL Scripts page
Entering Commands
To enter and 11.1n SQL commands, yo11 11se tl1e SQL Com1nands tool. If tl1e SQL
Commands ico11 is visible on tl1e screen , as shown in Fig11re 3-6, yo11 ca11 click the
ico11 to open tl1e SQL Com1nands page. From any otl1e r page, click tl1e SQL \Vorkshop
Chapter 3
arrow to display tl1e SQL \1/orl{sl1op m enu, and tl1en clicl{ the SQL Comma11ds option on
tl1e 1neni1, as sl10\,,11 in Figi1re 3 -9.
SOL Workshop
arrow
SOL
Commands
option
ORACLE' Application Express
Home
Home
WelcomePRATT/LAST ( Logout)
.,..I
Applica11on Builder•
SOL Worl<shop
SQL Scnpts
01,Ject B10wser
SOL commands~ - - --;::::::====='--- - - - - - - ~
X
SOLScnpts - - - ~ ScnpUtl deleled.
[
SOL Workshop'-- menu
aue,y Builder
( Delete Cnecked )( Upload> ) ( Create> )
u11mies
• Data Wol1<shop
• Object Reporls
• User Interlace Defaults
No data found.
FIGURE 3-9
I ,._
-----Manage Resubs
Showouolas
SOL Scripts
opt ion
Expon
1mpor1
SOL Workshop menu
Tl1e page tl1at opens 11ext is called the SQL Commands page, as shown in Figi1re 3-10.
You e11ter a co1111na11d in the SQL editor pa11e, and then click the Run button to exect1te
tl1e com111and ru1d display its r est1lts in tl1e Restilts pa11e.
SOL editor pane
SOL
Commands page
WelcOme PRATT/LAST I Loqool) "'
ORACLE" Application Express
,rr===r========.---+-------.. is displayed r==========,,,===========--
0Autoconunil
Rows
I••
Iv I Q I/
( Save )( Run )~--< Run button
Help button
"
Results
r p-
Oo~c
SJv
soi
!11 -.,-,.
Enter SOL statement or PUSOL command and dick Run to see lhe results.
Results pane
FIGURE 3-10
SOL Commands page
Now tl1at yot1 t111de rstand so1ne basic feattires of Oracle, yot1 ca11 create tl1e tables il1
tl1e database. If yot1 n eed additional l1elp as yot1 are \Vorl{ing, ttse tl1e Help btttton n ear the
top of a11y page to access tl1e Help syste1n.
Creating Tables
CREATING A TABLE
Tl1e firs t s tep in cr eating a table is to d escribe tl1e layoi1t of tl1e table to tl1e DBMS.
EXAMPLE 1
Describe the layout of the REP table to the DBMS.
Yot1 t1se tl1e CREATE TABLE com1na11d to describe tl1e layot1t of a table. The \Vord
'f ABLE is follo\ved by the 11ame of the table to be creat ed and then by the names and d ata
types of the coli1mns that the table contains. 'fhe data. type indicates tl1e type of data that
tl1e colt11n11 can contai11 (for exa111ple , cl1aracte rs, nt1111bers, or dates) as \\7ell as tl1e n1aximi1m nt1mber of cl1aracters or digits that the coli1mn can stor e.
Tl1e restric tions placed on table and coli1mn names are as follows:
1.
2.
3.
4.
Tl1e names canno t exceed 30 cha.r acters.
Tl1e 11ames mt.1st start with a le tter .
The names can co11tai11 le tte rs, 11t.1mbers, and unde rscores (_).
Tl1e names canno t contain spaces.
Tl1e SQL co111n1a11d tl1at creates tl1e REP table is sl1ow11 i11 Figt1re 3-11 .
, - - - ~ CREATE TABLE REP
(REP_ NUM CHAR ( 2 ) PRIMARY KEY ,
LAST_ NAME CHAR(lS ),
Creates a t able
FIRST_NAME CHAR(lS ),
named REP
STREET CHAR(lS) ,
~
CITY CHAR( 15) ,
STATE CHAR( 2) ,
POSTAL_ CODE CHAR(S ),
COMMISSION DECIMAL ( 7 , 2) ,
RATE DECIMAL(3 , 2) ); - - ,
FIGURE 3-11
-I
Command continues
over several lines
Semicolon indicates
end of command
CREATE TABLE command for the REP table
Tl1is CREATE TABLE co111ma11d, wl1icl1 uses the da ta definitio11 features of SQL,
describes a table 11ained REP . Tl1e table co11tains ni11e coli1mns: REP_NUM, LAST_NAME,
FIRST_NAME, STREET, CITY, STATE, POSTAL_CODE, COMMISSION, a11d RATE .
Tl1e REP_NUM colunu1 can s to re t\.\70 cl1a rac te rs a11d is the table 's primary l{ey. Tl1e
L1\ST_NAME colum11 can s tore 15 cl1aracters, a11d the STATE colu11111 can s tore two
cl1arac te rs. Tl1e CONIMISSION colu1n11 ca11 s tor e 011ly numbers, a11d those nu111bers are
li111ited to seven digits, i11cluding t\vo decimal places. Similarly, the RATE colu11111 ca11
s to re tl1ree-digit 11umbe rs, including two deci1nal places. You can tllilu{ of tl1e SQL
Chapter 3
command sho\vn in Fig11re 3 -11 as creating an empty table with col11mn headings fo r
eacl1 col11mn n ame .
In SQL, commands are free format; tl1at is, 110 rule says tl1at a partic11lar word mus t
begin in a particular position on tl1e line. For example, yo11 co11ld have written the
CREATE TABLE command sl10\.vn in Figure 3-11 as follo\.vs:
CREAT E T ABL E REP ( REP NUM CHAR (2) PR I MARY KE Y, LAST NAME
-
-
CHAR ( 1 5 ) , F IRST NAME CHAR ( 15) , STREET CHAR ( 1 5 ) , CI TY
CHAR (l5), STATE CHAR (2), POSTAL CODE CHAR ( 5 ), COMMISSION
DECIMAL (7, 2), RAT E DE CIMAL (3, 2));
Tl1e 1nanner in \.Vhicl1 tl1e CREATE TABLE comma11d sl1own in Figi1re 3-11 \.Vas "'' ritten 1nalres tl1e co1nmru1d 1nore readable. Tllis text \.Vill s trive for s11cl1 readability \.vl1en
writing SQL commands.
NOTE
SQL is not case sensitive; you can type commands using uppercase or lowercase letters. There is one
exception to this rule, however. When you are inserting character values into a table, you must use the
correct case.
To create the REP table iI1 Oracle, click i11 tl1e SQL editor pan e, type tl1e CREATE
TABLE command shown in Figure 3-1 2, and the11 elic it the R11n button to execute the
command and create the table. Fig11re 3-1 2 also sho\vs the message tl1at appe ars in the
Results pane after run11ing the command , \Vhich indicates tha t tl1e table was created . The
figi1res in tl1is text show the pa11es resized so tl1at more of tl1e Res11lts pru1e is visible to
tl1e 11ser .
ORACLE' Application Express
Home
•
Apphcalion Bull<!er ,..
0Autocomma
Rows
j10
Iv I V .f?
WeJcome PRATTllAST r Logout>
•
( Save ) ( Run )
CRE..:UE DJ!LE REP
f"IRSI NA.'iE CHAR ( 15 l ,
CREATE TABLE
STREET Cl!AR(lS),
CI TY C!L'lR(lS),
SlATI: CllAR ( 2),
command
POSIAL_CODE CR."1\(5),
COMMISSION DECIMlU.(7,2),
RAn. OECIMAL(3, 2) l;
Results ExplaJn Oescnbe
!abl~ cr~aced. -
Si, ed S...l
,.
Run button
illi-~C~J~ts;~MAAY Kt:Y,
Drag t his
line to resize
the panes
HISIO,Y
- - - - - - -----{
Message indicates
successfu l table creation
0.04 seconds
FIGURE 3-12
Running the CREATE TABLE command for the REP table
"
Creating Tables
ACCESS
USER
NOTE
Microsoft Office Access is a DBMS that lets you work in a graphical user interface, but you can also use
it to run SQL commands. To run SQL commands in Access, you must first create a new query. In
Access 2013, open the database, click the CREATE tab on the ribbon, click the Query Design button in
the Queries group, close the Show Table dialog box, and then click the SQL View button in the Results
group. In the Query window, type the SQL command, and then click the Run button in the Results group
on the DESIGN tab to execute the command. Figure 3-13 shows the command to create the REP table
using Access 2013. After you click the Run button, Access will create the table described in the
CREATE TABLE command. (Unlike Oracle, Access does not display a message indicating the result
was successful.)
FILE
HOME
EXTERNAL DATA
rm• +! 7'•! rm !X
ADO-INS
Run
Select Malce Append Update Crosstab Delete ~ •
Table
~ Data Odinition
QuecyType
'.!i) Qu~1
CREATE TABLE REP
(REP_NUM CHAR(2) PRIMARY KEY,
LAST_NAME CHAR(15),
RRST_NAME CHAR(l 5),
STREET CHAR(15),
CITY CHAR(15),
STATE CHAR(2),
POSTAL.CODE CHAR(2),
COMMISSION CURRENCY,
RATE NUMBER );
FIGURE 3-13
DESIGN
~
~
Result,
»
DATABASE TOOLS
I
•
View
CREATE
tc Insert Ro
CD Union
@ Pass-Through
,how
Table
Run button
'
Delete R
-~ Builder
Q
CREATE TABLE
command
Using Access SOL view to create a table
Unlike Oracle, Access does not support the DECIMAL data type. To create numbers with decimals,
you must use either the CURRENCY or NUMBER data type. Use the CURRENCY data type for fields
that will contain currency values; use the NUMBER data type for all other numeric fields.
In Access, it is common to create a table using Table Design view and then to add records to the
table using Datasheet view. You still can run SQL commands when you create tables using Design view
and enter data into them using Datasheet view.
•
Chapter 3
SQL
SERVER
USER
NOTE
Microsoft SOL Server is a DBMS designed for use in client-server applications. Microsoft SOL Server
Express is a free version of Microsoft SOL Server. You can run Microsoft SOL Server from your own
computer through a set of client database tools called SOL Server Management Studio. Management
Studio includes a Query Editor window that you can use to run SOL commands. If you are using
Management Studio and connecting to a database on your local computer, accept the default values for
Server Type, Server Name, and Authentication, and then click the Connect button in the Connect to
Server dialog box. When Management Studio is displayed, open the database in which you want to run
SOL commands and click the New Query button on the toolbar. Type the SOL command in the Query
Editor window that opens, and then click the Execute button on the toolbar to execute the command.
The command shown in Figure 3-1 4 creates the REP table and displays a message in the Messages
pane to indicate that the command completed successfully.
File
Edit
Vitw
Query PtoJKI
Debug
Tools
Window H,1p
...
, \g {I .J_ N"" Query [', i:h i:il, fn j, -1..'l ;& "l •
•} t Execute ~ Debug
'/:11. jTAL Distributors
( j] •
SQlQusy6.sql • M... RYLAST\Mary (53))
EI CREATE TABLE &e,
(REP_Nltl CHAA(2 PRII-IARY Kl:Y,
I.AST_NA'IE CHAR ( 15) ,
FIRST_NNIE CHAR(15),
STREET CHAR115)
CITY CHAA(15),
STATE CHAR(Z),
POSTAL_CODE CHAR(S),
COM-IISSION OECi l'\ll.l.( 7 2),
RATE DECIMAl. (3, 2) );
SQLQ ay5.sqt · M...RYLASl\Mary (52))• X
Execute button
CREATE TABLE
statement
Message indicat es
successful table
creat ion
100 %
•
I::) Messages .
Colllll!and(s ) completed successfully .- + - - - - - - - - - - - - -----'
FIGURE 3-14
Using Microsoft SQL Server to create a table
Correcting Errors in SOL Commands
St1ppose that yot1 exect1ted tl1e REP table t1sil1g the CREATE TABLE co1mnand shown in
Figt1re 3-15, which contai11s several mistakes. lt1stead of displaying a m essage that tl1e table
was created successft1lly, Oracle displays an error m essage abot1t a problem that it e11countered. In reviewing the co1n111a11d, you see that CHAR is misspelled on li11e 4, the CITY colt1111n was omitted , and li11e 7 should be deleted. If yot1 tun a command and Oracle displays an
error, yot1 can t1se tl1e m ouse a11d the arrow keys on tl1e keyboard to positio11 the insertio11
point in the correct position so yot1 can correct tl1ese errors t1sil1g the same teclmiqt1es that
yot1 1night tise in a \.Vord processor . For example , yot1 can tise the poil1ter to select tl1e word
CHR on line 4 a11d type CHAR, and tl1e11 yot1 can tise the pointer to move the insertio11 poil1t
to the end of line 5 so you can press Enter to il1sert tl1e missing information to create tl1e
CITY column. You ca11 tise the pointer to select the contents of fu1e 7 and tl1en press Delete to
rem ove it. After 1naking tl1ese cha11ges, yot1 can clicl{ the Run bt1tton to exectite tl1e comn1and
again. If tl1e conunand contail1s additional errors, yot1 will see an e1Tor message agai11. If the
co1nmand is correct, yot1 will see tl1e m essage that tl1e table was created.
Creating Tables
I ORACLE' Application Express
Team Development •
Home
SOL Wooohop
Ell AutocommH
Rows
Sctlema fPIIXtr1l.Xsi'j v I
SQL Commands
i10 Iv I V I/
c:ru:AI£ tAllU: R!P
( Save )
Run
CH R should be CHAR
(REP NOM CHAR(2) PRI!W\Y K£Y,
:.AST-NAME CHAR(15),
fIRST NAM£ CRR~ - , - - - - '
SIRE'f CHAR( l S)
STAI£ CHAR(2) , - - - - - - - - - ---\
XXX CllAR(lO) , - - - - - ,
POSIAL_CODE CIIAR(S),
XXX column
COM!CSSION DEC:::MAL{7, 2),
RAI£ D£CIMAL(3, 2) ) ;
should not be
Results
~
Admmistral1on •
included
lam Describe saved SOL
,i7"'""":~,'-------
CITY column
1s m 1ss1ng
,,L_-=,----r..---- ------~--d
--
Error message
ORA·00907 : miaaing •ight pareotbui•- - - - - - - - '
0.00 seconds
FIGURE 3-15
CREATE TABLE command with errors
Dropping a Table
After creati11g a table , yo11 1nigl1t notice that you added a column tl1at yo11 do not need o r
tl1at you assigned the wro11g data type o r size to a colt1ID11. One way to correct such erro rs
in a table is simply to dele te (drop) tl1e table and start over . For exa1nple , s11ppose yo11
wrote a CREATE TABLE command tl1at co11tained a column named LST i11stead of LAST
or defined a col11mn as CHAR(S) instead of CHAR(lS). St1ppose you do not discover tl1e
error and you execute the command, creati11g a table vvitl1 tl1ese problems. In this case,
you can dele te tl1e entire table using tl1e DROP TABLE co1nmand and the11 re-crea te the
table using the correct CREATE TABLE command.
To drop a table, execute the DROP TABLE command, follovved by tl1e name of tl1e
table yo11 want to dele te a11d a se1nicolo11. To delete the REP table , for example, yo11 vvo11ld
e11ter tl1e following comina11d a11d tl1en clicll tl1e Run button :
DROP TABLE REP;
Dropping a table also deletes a11y data tl1at yo11 e11tered into tl1e table. It is a good idea
to checll your CRE1-\ TE TABLE co1nmands carefully before exec11ti.I1g tl1em a11d to correct
any proble1ns before addi11g data. Later in this text, yo11 vvill learn l1ow to cl1ange a table's
s tn1ct11re \\7itl1011t having to dele te tl1e entire table .
Question: I-low can I correct a mistalle that I made wl1en I created a table?
Answer: Later in the text, you ,vill see how to alter a table to make any necessary
corrections. For now, the easiest wa)' is to drop the table using the DROP TABLE
command and then to execute the correct CREATE TABLE command.
Chapter 3
USING DATA TYPES
For eacl1 colt11n11 it1 a table, yot1 1nus t specify tl1e data type to t1se to store tl1e type of data
tl1a t tl1e colt11n11 "''ill co11 taiL1. Figt1re 3-16 describes some corm11011 data types t1sed i11
databases.
Data Type
Description
CHAR(n)
Stores a character string n characters long. You tise the CI-IAR data type for columns
that contain letters and special characters and for colun1ns containing numbers that
\Vill not be used in any calculations. Because neitl1er sales rep numbers nor
ct1stomer nu,nbers \Vill be used in any calculations, for example, the REP_Nill1 and
CUSTOMER_Nl.Th,f columns are both assign ed the CI-JAR data type.
VARCI-IAR(n)
An alternative to CHAR that stores a character string up ton characters long. Unlike
CI-JAR, only the actual character string is stored. If a character string 20 characters
long is stored in a CHAR(JO) column, for example, it ,vill occupy JO characters
(20 characters plus 10 blank spaces). If it is stored in a VARCHAR(JO) column, it will
only occupy 20 spaces. In general, tables that use VARCHAR instead of CHAR
occupy less space, but the DBMS does not process them as rapidly during queries
and updates. Ho,vever, both are legitimate choices. This text uses CHAR, but
VARCI-IAR ,vould ,vork equally ,veil.
DATE
Stores date data. The specific format in \Vl1ich dates are stored varies from one SQL
implementation to another. In Oracle, dates are enclosed in single quotation marlls
and have tl1e format DD-1'10N-YYYY (for example, '23-0CT-2015' is October 23,
2015). In Access, dates are enclosed in number signs and are entered usi.J1g tl1e
fom1at 1111/DD/Y\'YY (for example, #10/23/2015# is October 23, 2015).
DECThlAL(p ,q)
Stores a decimal number p digits long with q of these digits being decimal places to
the right of the decimal point. For example, the data type DECIMAL(5,2) represents
a number with three places to the left and two places to the right of the decimal (for
example, 100.00). You can use the contents of DECIMAL columns in calculations.
You also can use the NUMBER(p,q) data type ill both Oracle and SQL Server to store
a decimal number. Access does not support the DECIMAL data type; use the
CURRENCY or NUMBER data type instead.
INT
Stores integers, which are numbers \Vithout a decin1al part. Tl1e valid range is
- 2147483648 to 2147483647. You can use the contents of INT coltimns i.J1
calculations. If you follow the word INT with AUTO_INCRE1'1ENT, you create a
colt1.mn for \Vhich SQL ,vUl at1tomatically generate a ne\V sequence nun1ber eacl1
time you add a ne\v ro\V. This \Vould be tl1e appropriate choice, for example, \Vhen
you \Vant the DBMS to gen erate a value for a primary key.
SMALLINT
Stores mtegers, but uses less space than the INT data type. The valid range is -32768
to 32767. SMALLINT is a better choice than INT \vhen you
are certain that the
•
column will store numbers within the indicated range. You can use the contents of
SMALLINT columns in calculations.
FIGURE 3-16
Commonly used data types
Creating Tables
USING NULLS
Occasionally, \Vl1e11 yo11 ente r a ne\v ro\\' i11to a table or m odify an existing ro\v, tl1e
val11es for one or n1ore columns are 11nlrno\,,11 or 11navailable. For example, you ca11 add a
cu stomer 's name and address to a table even tl1ougl1 tl1e c11s ton1er does n ot l1ave an
assigi1ed sales r ep or an establisl1ed credit limit. In otl1er cases, some values 1night never
be lrno\\,n- perl1a ps there is a c11s tom er tl1at does not have a sales re p . In SQL, yo11
l1andle this sit11ation by 11sing a special val11e to represent cases in \Vl1icl1 a11 actual val11e
is 11nlrnow11, 11navailable, or n ot applicable. Tl1is special val11e is called a null data value,
o r simply a null. When creati11g a table, you can specify wl1ether to allo\\' nulls in tl1e
individtial col11mns.
Q11estion: Should a user be allowed to enter null values for tl1e primary l{ey?
Answer: No. The primary lley is supposed to uniquely identify a given row, and this
would be impossible if nulls were allowed. For example, if you stored t,vo customer
records without values in the primary l{ey column, you would have no way to tell them
apart.
111 SQL, you 11se tl1e NOT NULL cla11se i11 a CREATE TABLE com1na11d to i11dicate
columns tl1at can1iot co11tain n11ll val11es. The defa11lt is to allow n11lls; columns for \Vllicl1
yo11 do n ot specify NOT NULL can accept n11ll values.
For example, st1ppose that the LAST_NAME at1d FIRST_NA11IE columns in tl1e REP
ta ble cannot accept n11ll val11es, but all other colt1mns in the REP table can . The following
CREATE TABLE co111111and accomplishes tllis goal:
CREAT E TABLE REP
(REP NUM CHAR (2) PRIMARY KEY,
LAST NAME CHAR ( 15) NOT NULL,
FIRST NAME CHAR ( 15) NOT NULL,
STREET CHAR ( 15) ,
CITY CHAR (15),
STATE CHAR ( 2) ,
POSTAL CODE CHAR ( 5),
COMMISS I ONDE CIMAL(7,2),
RATE DE CIMAL ( 3, 2) ) ;
If yot1 created the REP table with this CREATE TABLE co111111a11d, tl1e DBMS \Vottld
reject any attempt to s tore a null valtie in either tl1e LAST_NA11IE o r FIRST_NAME colu11111 . The system ,vo11ld accept a11 atten1pt to s tore a n11ll val11e in the STREET col11mn,
l1owever , b ecause tl1e STREET column cai1 accept null val11es. Because the pri1nary lley
column ca1mot accept n11ll val11es, you do n ot need to specify tl1e REP_NUM colu111n as
NOT NULL.
Chapter 3
ADDING ROWS TO A TABLE
After yot1 l1ave created a table in a database, you can load data i11to the table by t1sing tl1e
INSERT co1nma11d.
The INSERT Command
Tl1e INSERT co111ma11d adds ro\VS to a table. Yot1 type INSERT INTO follo\v ed b y tl1e 11ame
of tl1e ta.hie i11to \Vl1icl1 yot1 are adding data. Tl1e11 yot1 type tl1e v\rord VALUES follo\,,ed by
tl1e specific valt1es to be i11serted in pare11tl1eses. v\Tl1e11 addi11g ro\vs to character colt111111s,
1nalre st1re yot1 e11close the values it1 sit1gle qt1otatio11111arh.s (for exa1nple, 'Ca1npos'). Yot1
also mt1st e11ter tl1e valt1es it1 tl1e appropriate case, becat1se cl1aracter data is s tored
exactly as yot1 e11ter it.
NOTE
You must enclose values in single quotation marks for any column whose type is character (CHAR),
even when the data contains numbers. Because the POSTAL CODE column in the REP table has a
CHAR data type, for example, you must enclose postal codes in single quotation marks, even though
they are numbers.
If you need to enter an apostrophe (single quotation mark) into a column, you type two single quotation marks. For example, to enter the name OToole in the LAST_NAME column, you would type
'O" Toole' as the value in the INSERT command.
EXAMPLE 2
Add sales rep 15 to the REP table.
'fl1e com1nand for this example is sl10\v n in Figt1re 3-17. No te that tl1e cl1ara.c ter
strings (' 15 1 , 1Campos', 1 Rafael ', and so on) are en closed in single qt1otation marlrs. \\Tl1en
yot1 exect1te the command, the record is added to tl1e REP table.
Home
SOLWOft(shOp
RI Autocommtt
Rows
SQLCommands
-------<
!10 Iv I V 4
( Save ) c..§.n)
Character values
enclosed in single
quotation marks
+
INSER! IN!O REP
\!ALOES
f
Z.,
('15','Campos' ,'Rafae l','724 V+ngg Dr . 1 ,•Grove ' ,'CA','90092 ' ,23451 . 50,0 . 06);
Results 1 ~lam Oc~colle Sa ... r
lllstory
One row
was inserted
0.06 seconds
FIGURE 3-17
INSERT command for the first record in the REP table
Creating Tables
NOTE
Make sure that you type the values in the same case as those shown in the figures to avoid problems
later when retrieving data from the database.
EXAMPLE 3
Add sales reps 30 and 45 to the REP table.
Yott co11ld enter and exec11te ne\v INSERT con1mands to add tl1e 11ew rov.1s to tl1e
table. However , a11 easier and fas ter way to add these 11e\\' ro\vs to tl1e table is to 11se the
mo11se and the lreyboard to modify the previo11s INSERT command and exec11te it to add
tl1e record for tl1e second sales rep, as sl1own in Fig11re 3-18.
Home
SOL Workshop
0 Aulocommil
Rows
SQL Commands
110
1... 1~.?
( Save ) ( Run )
DISKRT INTO REP
VALUES
( '30', 'Gradey•, 'Megan' , • 632 W!.!;i.~ St. •, • Full ton ', •CA' , • 90085 • , 41317 . 00, O. 08) ;
Results [ plain Describe Sllved SOL History
1 row (s) inserted.
0.01 seconds
FIGURE 3-18
INSERT command to add the second row to the REP table
You can modify and execute the INSERT com111and again for the tllird sales rep , as
sl10\,111 i11 Figure 3-19, to add tl1e third rov.1 to the table. You \\7ould tl1e11111odify a11d
execute a si111i1ar comn1and to add the fourth ro\v to the table.
I
Home
SOL Workshop
0 Aulocommil
Rows
SQL Commands
110
1... ,~,?
( Save ) ( Run)
DISE.RT INTO REP
VALUES
('45 ', 'Tian','Hui', '1 785 :yler Ave . ', 'Northfield','CA', ' 90098 ',27789.25,0.06);
Results
.plain Descnbe Saved SOL History
l row (s) inserted.
0.00 seconds
FIGURE 3-19
INSERT command to add the third row to the REP table
Chapter 3
Inserting a Row that Contains Nulls
To enter a 1111ll value into a table, you use a sp ecia l form of tl1e INSERT conuna nd i11
wl1ic h you ide ntify tl1e n a1nes of tl1e colu11111s that will a ccept 11on-null values, a11d the11 lis t
only tl1ese n o11-11ull values after the VALUES co111mand, as sh ov\'11 ill Exa111ple 4 .
EXAMPLE 4
Add sales rep 7 5 to the REP table. I-ler name is Annabel Parry. All columns except
REP_NUM, LAST_NAME, and FIRST_NAME are null.
l11 tl1is case, yot1 do 11o t e11te r a va lt1e of null ; yo11 e11te r 011.ly tl1e no11-11ull valt1es. To
do so, yo11 mt1st i11dicate precisely vvl1ic l1 val11es yot1 are e11te ri11g by lis til1g tl1e corre spo11di11g colt11n11s as sl1ow11 in Fig11re 3 -20 . The co1111na11d sl1ov,,11 i11 Figure 3-2 0 il1dic ates
tl1at yot1 are e11te ring da ta i11 011ly the REP_NUM, LAST_NAME , and FIRST_NAME colt11m1s
and tl1at yot1 are not e11te ri11g val11es in a11y o tl1er colt1nu1s; the o tl1e r colu1n11s "''ill co11tai11
11ull val11es.
l Home SOLWorkstlop SQL Commands
0Autocommit
Rows
110
lvl~.f
( Save )( Run )
INSERT INTO 8£P (REP_NUM, LAST_Nl'.ME, FI!tST_NAME)
VALUES
(
1
75 ', 'Parry','Annabel' ) ;
Results E: plain Oesc.11be Sflved SOL History
/
Only values for the '\
listed columns wil l
be inserted
=
-
1 ro~(s) inserted.
0.00 seconds
FIGURE 3-20
Inserting a row that contains null values in the REP table
VIEWING TABLE DATA
To vie w tl1e data in a table, yot1 u se the SELECT co1nmand, whic l1 is desc1ibed in m o re
de ta il ill Chapte rs 4 a11d 5.
EXAMPLE 5
Disp lay all the rows and columns in the REP table.
Y011 can t1se a sitnple version of the SELECT command to display a ll tl1e rows a11d
columns in a ta ble by typing tl1e word SELECT, followe d by an aste ris l{, followed by tl1e
word FRON[ and the name of the table conta ining tl1e d a ta you want to vie \.\' . J11s t as with
o the r SQL conUTiands, tl1e com ma11d ends \.Vith a semicolon. In Oracle, you typ e tl1e
command shovvn in Figure 3-2 1, and the11 c lic k the Run butto n to display the r es11lts.
Creating Tables
Home
SQL Workshop
0 Autocommit
Schema PRATT/I.A
SQL Commands
, .., I ~ .fl
Iio
Rows
( Save ) ( Run )
Command to
display all rows
and all columns
SELECT*
fROM REP;
,......Results
1c pl/Jin
Ol>scnbe
Saved SOL
History
15
Campos
Rafael
724 Vinca Dr.
Grove
CA
30
45
Gradey
Megan
Fullton
CA
Tian
Hui
Northfield
CA
60
75
Sefton
Janel
632 Liatris st.
1785 Tyler Ave.
267 Oakley st
Congaree
CA
Parry
Annabel
23457.5
41317
27789.25
.08
0
.06
.06
.06
Download
5 rows returned in 0.00 seconds
FIGURE 3-21
90092
90085
90098
90097
Using a SELECT command to view table data
ACCESS
USER
NOTE
In Access, type the query shown in Figure 3-22 in SOL view to display all the rows and columns in a
table.
FILE
HOME
'
Run
•
EXTERNAL DATA
DATABASE TOOLS
ADO-INS
EW• +! ~•! ~ !X @
~
•
View
CREATE
DESIGN
~
tc Insert Ro
OO Union
Pass-Through
u1
'
Select Make Append Update Crosstab Delete ._,!
Table
~ Data Definition
Show
Table
.~ Builder
Results
DeleteR<
Query Type
Q
:§'.] Query1 \
»
SELECT
command
SELECT•
FROM REP;
RGURE 3-22
Using a SELECT command to view table data in Access
To run the query, click the Run button. Access will display the query results in Datasheet view, as
shown in Figure 3-23. If the data does not fit on the screen, you can adjust the columns to best fit
the data they contain by double-clicking the right edge of each column heading. You can use the
scroll bars when necessary to view data that has scrolled off the screen.
HOME
CREATE
EXTERNAL DATA
L] !rm, Copy
Views
»
T Selecbon •
Descending
't;J Advanced •
Remove Sort
Toggle Filter
Filter
Paste
•
•
~! Ascending
T ~!
J(, Cut
A
Format Painter
r.
Olpboard
DATABASE TOOLS
Mi
ADD-INS
l@l
~New
L Totals
:;;3 ~Save
✓ Spelling
Refresh
All • X Delete • E!J More•
So rt & FIiter
Rr cords
Calibri (Detail)
Find
Find
8
I
• 11
~
U
Text Formatting
~ Queryl
REP _NUM •
LAST NAME •
FIRST_NAME •
Campos
Rafael
n4 Vinca Dr.
30
Gradey
Megan
45
nan
60
Sefton
m
STRIB
STATE •
POSTAL CODE •
Grove
CA
632 Liatris st_
Fulton
HUI
1785 Tyler Ave.
Janet
267 Oakley St.
•
COMMISSION •
RATE•
90092
$23,457.50
0.06
CA
90085
$41, 317.00
0.08
Northfield
CA
90098
$27,789.25
0.06
Congaree
CA
90097
$0.oo
0.06
OTY
•
*l
RGURE 3-23
Query results in Access Datasheet view
Chapter 3
SQL SERVER
USER
NOTE
In SQL Server, type the query shown in Figure 3-24 in the Query Editor window.
File
Edit
View
: w-
Que,y
Project
__; g §II .J.
Debug
New Query
W [TAL Distributors
Tools
Window
Help
r- e1J, CTI ra i ~
•[
") .
, Execute
SQLQueiyS.sql - M ...RYLAST\Mary (52))• X
EJ SELECT ' ..+- - - - - - - - - <
l fRa-1 REP ;
RGURE 3-24
command
Using a SELECT command to view table data in SOL Server
To run the query, click the Execute button. SQL Server will display the query results in the Results pane,
as shown in Figure 3-25. If the data does not fit on the screen, you can adjust the columns to best fit the
data they contain by dragging the right edge of each column heading to make it narrower or wider.
'.J M=ages
□ Results
REP_NUM
1
2
3
4
LAST_NAME
r·--------·-,
[ 15
j Campos
- ·-·-·-·-·--·-·-Gradey
30
45
Tian
60
Seftoo
FIRST_NAME
STREET
CITY
STATE
POST.A.l_CODE
COMMISSION
RATE
Rafael
Megan
724 Vinca Dr.
Grove
90092
23457.50
0.06
Fullen
0.08
27789.25
0.06
Janet
2G7 Oakley St.
90085
90098
90097
41317.00
Hui
632 Uatris St.
1785 Tyler Ave .
CA
CA
CA
CA
0.00
0.06
Northfield
Congaree
Query results in SQL Server
RGURE 3-25
CORRECTING ERRORS IN A TABLE
Afte r exect1tit1g a SELECT co1nma11d to vie"'' a table 's data, yott 1nigl1t fiI1d tl1a t yot1 11eed
to c hru1ge tl1e valt1e i11 a colt1m11 . Yott ca11 t1se the UPDATE co1111na11d show11 i11
Figt1re 3-26 to c l1a11ge a value i11 a table. Tl1e UPD1\TE co1n111a11d sl10\.v11 i11 Figure 3-26
cl1a11ges the las t 11a1ne it1 tl1e ro \.v 011 v.rhicl1 tl1e sales re p 11t1mber is 7 S to Pe rry.
Home
SQl Worl(shop
E2!Autocommi\
SQL Commands
Rows
[10
I .., IQ ,R
( Save )( Run )
OPDA!E REP
New value
SET LASI_NAME • 'Perry'
WHERE REP_NUM ;
Results
pill n
'75'; -
-------,
Describe Saved SQL History
0.00 seconds
FIGURE 3-26
Change only
affects the row(s)
on which the rep
number is 75
Message indicates
the number of
updated rows
Using an UPDATE command to change a value
Tl1e SELECT com111and sl10\.vn in Figt1re 3-27 displa ys the results of the UPDATE
command sh own in Figure 3-26, i11 which the last 11ame for re p nt1mber 75 is Pe rry.
Creating Tables
Home
SOL Workshop
E21Autocommil
Schema PRATTILAS
SQL Commands
Iv I(/ ,?
Jio
Rows
( Save ) ( Run )
SELECT•
FROM REP;
Results
plllm Oescnbe
Saved SOL History
REP_NUM
LAST_NAME
RRST_NAME
45
nan
15
STREET
CITY
STATE
POSTAL_COOE
COMUIS ON
Hui
1785 Tyler Ave.
Northfield
CA
90098
27789.25
.06
Campos
Rafael
724 Vinca Or.
Grove
CA
90092
23457.5
.06
30
Gradey
Megan
632Liabis Sl
Fuuton
CA
90085
41317
.08
60
Sefton
Janel
267 Oakley Sl
Congaree
CA
90097
0
.06
75
Perry
Annabel
5 rows returned in 0.01 seconds
FIGURE 3-27
Download
Last name changed for sales rep number 75
\\Tl1en you need to delete a row from a table, you can t1se tl1e DELETE corrunand.
Tl1e DELETE comma11d sl10\\7n i11 Figure 3-28 deletes any row 011 wl1ich the sales rep
nt1mber is 75.
I Home SOL Workshop
6ZI Autocommil
Rows
DE:L!!E
fROM REP
tiffiE.RE RE..P_ NUM •
'75';
SQL Commands
Jvl(/,?
Jfd
( Save )( Run )
Results " plam Oescnbe Saved SQL History
.
Only row{s) on wh ich the rep
number is 75 will be deleted
l ro;., ( s ) deleted .
0.00 seconds
FIGURE 3-28
Using a DELETE command to delete a row
Tl1e SELECT com1nand sl10\.vn in Figt1re 3-29 displays tl1e t1pdated data.
Home
SOL Workshop
E2I Autocommil
Rows
Sdlema PRATTILA
SQL Commands
I v I (/ ,?
J10
( Save ) ( Run )
SELECT•
FROM REP;
Results CKplam Descnbe
Saved SQL
History
•
45
nan
Hui
1785 Tyler Ave.
Northfield
CA
90098
27789.25
.06
15
Campos
Rafael
724 Vinca Or.
Grove
CA
90092
23457.5
.06
30
Gradey
Megan
632 Liabis Sl
Fulllon
CA
90085
41317
.08
60
Sefton
Janel
267 Oakley Sl
Congaree
CA
90097
0
.06
4 rows returned in 0.00 seconds
FIGURE 3-29
Download
Sales rep number 75 deleted from RE P table
Chapter 3
Question: I-low do I correct errors in m y data?
Answer: The method you use to correct an error depends on the type of error you need to
correct. If you added a row that should not be in the table, use a DELETE command to
remove it If you forgot to add a row, you can use an INSERT command to add it. If you
added a row that contains incorrect data, you can use an UPDATE command to ma.k e the
necessary corrections. Alternatively, you could use a DELETE command to remove the
row containing the error and then use an INSERT command to insert the correct row.
SAVING SQL COMMANDS
Oracle lets yoi1 save SQL commands so yoi1 can i1se tl1em again \\7ithoi1t retypil1g tl1em. In
Oracle, as \Veil as i.11 many other DB11Ss, yoi1 save connna11ds i11 a script file, or simply a
script, wllich is a text file. In Oracle, script files l1ave tl1e .sql filename extension. \\Tl1en
you use Oracle to create a script, Oracle stores tl1e script i11 a special locatio11 called tl1e
sc1ipt repository. If yoi1 \Vant to save a script 011 the local file system, sucl1 as 011 a l1ard
drive or USB drive, yoi1 ca11 do so by do\vn1oading the script. If you need to i1se a script
tl1at is stored on the local file system, but is 11ot ci1rre11tly stored in Oracle, you ca11
i1pload tl1e script so yoi1 can i1se it in Oracle. The follo\ving steps describe l1ow to create
and use scripts in the Oracle 1\pplication Express. If you are using a different versio11 of
Oracle or another DBMS, use Help or consult the system doci1mentation to deter1nine
110,v to accomplisl1 tl1e same tasks.
NOTE
Although scripts are the preferred method for saving commands in Oracle, there is an alternative. To
save a query that you just created, you can click the Save button, then enter a name and, optionally, a
description. Next, click the Save button in the Save SOL dialog box. The query will appear in the list of
Saved SOL queries. To see the list, click Saved SOL in the Results pane. If you click the name of any
query you have saved, you will immediately see that query in the SOL editor pane. You can then edit it,
run it, or save it again.
Question: When ,vould I simply save a query and when would I create a script?
Answer: Saving a query is a quick and easy process. On the other hand, creating a script
offers some distinct advantages. You can create or edit a script using a text editor or
word processor and then upload the script to the script repository. You can do,vnload a
script in the script repository to a text file, ,vhich enables you to share the script with
others. Additionally, there are some advanced features you will see later in this text that
are only available when using scripts.
Creating Tables
To create a script i11 Oracle:
1.
2.
3.
4.
5.
Clicl{ tl1e SQL ,vorl{sl1op arro,,,, a11d tl1en cliclr SQL Scripts.
On the SQL Scripts page, cliclr the Create button. The Script Editor page
ope11s.
In tl1e Script Nam e text box, type a name for the script.
Clicl{ ill tl1e text box on tl1e page to activate it, a11d tl1e11 type tl1e co1nma11d
or com1nands to save ill tl1e script.
'\\Tl1en yo11 are finisl1ed , clicl{ tl1e Save button. You ret11rn to tl1e SQL Scripts
page a11d tl1e script yo11 cr eated appears as an ico11 on the page.
To view or edit a script in Oracle:
1.
2.
3.
Click the SQL ,\Torl{sl1op arro,v, and tl1en cliclr SQL Scripts.
On the SQL Scripts page, clicl{ the Edit b11tton for tl1e desired script to view
or edit the script. Tl1e script appears 011 tl1e Script Editor page. Yo11 cat1 11se
tl1is page to view tl1e content of tl1e script or to mal{e changes to it by editing
tl1e com1nands it contains.
If yo11 edit a script, cliclr tl1e Save b11tton to save yo11r cl1a11ges. If yo11 ru·e
011ly viewil1g tl1e script or if yo11 decide yot1 do 11ot wisl1 to save your cha11ges,
click tl1e Ca11cel b11tto11 to r et11rn to tl1e SQL Scripts page.
To r1111 an existi11g script i11 Oracle:
1.
2.
Click the SQL ,vorl{sl1op arro,,,, a11d tl1en cliclr SQL Scripts.
Clicl{ the R11n b11tton for the desired script. Tl1e R11n Script page loads and
asl{s yot1 to confirm 11.mning the script. Click the R1111 butto11 011 tl1e R11n
Script page. Tl1e Manage Script Res11lts page opens a11d displays tl1e script
11ame and an ico11 in the , rie,v Res11lts col11tn11. To see the res11lts of tl1e
cormnand stor ed in tl1e script, clicl{ tl1e ico11 in the , riew Res11lts colt1tn11.
'\\T11en yo11 are fi11is l1ed 11sing a script a11d n o longer need to stor e it, yo11 can dele te it.
To delete a script in Oracle:
1.
2.
3.
4.
Clicl{ the SQL , vorl{sl1op arrov.,, and then clic l{ SQL Scripts.
Clicl{ tl1e cl1ecl{ box for the desired script to select tl1e script.
Click tl1e Dele te Cl1eclred b11tto11.
Click tl1e 0 1( b11tto11 to co11fir1n tl1e dele tion .
To do,vnload a script from fue script repositor y in Oracle and save it as a file:
1.
2.
3.
4.
Folio,,, the previo11s il1stn1ctions to view tl1e script.
Clicl{ tl1e Do,vnload b11tton . Tl1e File Dow11load dialog box ope11s.
l11 tl1e dialog box, clicl{ tl1e Save button, a11d tl1e11 sa,,e tl1e file to tl1e desired
locatio11.
Clicl{ the Close b11tton to close tl1e Do,v11load complete dialog box.
Chapter 3
To t1pload a script to the script repository in Oracle:
1.
2.
3.
4.
Clicll tl1e SQL Worllsl1op arro\.v, and tl1en clicll SQL Scripts.
Click the SQL icon arro\.\', poi11t to SQL Scripts, and tl1e11 click Upload. The
Upload Script page ope11s.
Click the Browse button. The Choose file dialog box opens. Navigate to and
select the script file to t1pload. (If you want to upload tl1e script " 'itl1 a different filename, type the new name in the File name text box.) Clicll the Open
bt1tton.
On the Upload Script page, enter a 11ame for the script to be created by the
t1pload process, a11d then clicll tl1e Upload bt1tton. Tl1e new script \.Vill appear
in tl1e list of scripts on tl1e SQL Scripts page.
ACCESS
USER
NOTE
Access does not use script files, but you can save SQL commands as query objects in the database.
Open the database, create the query in SQL view, click the Save button on the Quick Access toolbar,
and then save the query with the desired object name. To run the query without first viewing the SQL
command, right-click the query in the Navigation Pane, and then click Open on the shortcut menu. The
query results will appear in Datasheet view. If you want to view the SQL command before running the
query, right-click the query in the Navigation Pane, and then click Design View on the shortcut menu. To
run the SQL command, click the Run button.
SQL SERVER
USER
NOTE
SQL Server can store scripts in any folder on your local system. All scripts created in SQL Server are
text files with the .sql filename extension. To create a script file in SQL Server:
1. Load SQL Server Management Studio, and then click the Connect button in the Connect to
Server dialog box.
2. Open the appropriate database, and then click the New Query button.
3. Type the command or commands to save in the script. When necessary, click the Execute
button to execute the commands saved in the script.
4. When you are finished, click the Save button, and then enter a name for the script.
To view, edit, or run an existing script
1. Load SQL Server Management Studio, and then click the Connect button in the Connect to
Server dialog box.
2. Open the appropriate database, and then click the New Query button.
3. Click the Open File button on the toolbar.
4. Navigate to the folder containing the script file, and then click the Open button in the Open
File dialog box. The script appears in the Query Editor window. You can view the content of
the script to make changes to it by editing the commands. If you edit a script, click the Save
button to save your changes.
5. To run a script, click the Execute button.
Creating Tables
CREATING THE REMAINING DATABASE TABLES
To create tl1e r e1nai11i11g tables il1 tl1e TAL Distribt1tors database, yot1 11eed to execute tl1e
appropriate CREATE TABLE a11d INSERT con11nai1ds. Yot1 sl1ot1ld save tl1ese co1ru11ands
as scripts so you ca11 re -creat e your data base, if 11ecessary, by rt111ni11g tl1e scripts.
NOTE
Your instructor might give you the script files to use to create the tables in the TAL Distributors, Colonial
Adventure Tours, and Solmaris Condominium Group databases and to insert data into them.
Figure 3 -30 sl1ows the CREATE TABLE co1TI1Tiand for the CUSTONIER table.
Notice that tl1e CUSTOMER_NAME colt11m1 is specified as NOT NULL. Additionally, tl1e
CUSTOl-.IBR_NUNI colu111n is tl1e ta ble's p1i111ary Irey, il1dicatil1g tl1at tl1e CUSTOMER_NUM
colu111n is tl1e unique identifier of rov.rs il1 tl1e table. ''' ith this colu11111 designated as tl1e
primary key, tl1e DBMS will reject any atte1npt to store a ct1stomer 11umber tl1at already
exists it1 tl1e table.
CUSTOM ER_N UM
is the p rimary key
CREATE TABLE CUSTOMER
(CUSTOMER_NUM CHAR ( 3) PRIMARY KEY •,_ _ _ _ ____,____
_
_
_____
CUSTOMER_NAME CHAR(35 ) NOT NULL , - + - - - - ~
CUSTOMER_NA ME
STREET CHAR ( 2 0 ) ,
can not be null
CITY CHAR( lS ) ,
STATE CHAR ( 2 ) ,
Sem icolon indicat es
POSTAL_CODE CHAR (S ) ,
end of command
BALANCE DECIMAL(B , 2) ,
CREDIT_LI MIT DECIMAL(B ,2 ) ,
REP_ NUM CHAR ( 2 ) ) ; + - - - - - - - - + - - - - '
FIGURE 3-30
CREATE TABLE command for the CUSTOMER table
After creating the CUSTOMER table, yot1 can cr ea te another file containing tl1e
INSERT commands to add the ct1stom e r rovvs to tl1e table. ,\Then a script file contains
m o re than one command, each com1nand mt1st end with a. semicolon . Figt1re 3 -31 sl10,,,s
tl1e INSERT commands to add r ov\'S to tl1e CUS'fOMER table. As no ted previot1sly, to
enter an apostrophe (single qt1otation marlr) in tl1e valt1e for a field, type two single
qt1otation marlrs , as illt1s trated in the 11ame in the fot1rtl1 INSERT command (Johnson 's
Departme11t Store) in Figt1re 3-31 .
Chapter 3
ITNsERT I NTO cusTOMER
I ;~~UES
Data f or
( '126 ' , ' Toys Galore', '28 Laketon St . ' , ' Fullt on ' , ' CA', '90085 ' , 1 210.25,7500.00, ' 15 ' );
fi rst row
INSERT INTO CUSTOMER
VALUES
( ' 260 ' , ' Brookings Direct', ' 452 Columbus Dr. ' , 'Grove', 'CA', ' 90092 ' ,575.00,10000.00, '30 ' );
second row
INSERT INTO CUSTOMER
VALUES
( '334 ' , ' The Eve ryth i ng Shop ' , ' 342 Magee
St .', ' Congaree', ' CA ' , '90097 ' ,2345.75,7500.00, '45 ' );
Type two single quotation
INSERT INTO CUSTOMER
VALUES
, - - - - - - - - - - - - - - - - - ---\
marks t o insert an
apostrophe in a value
( ' 386 ' , ' Johnson ' ' s Department Store', ' 124 Mai n
St .', 'Northf ield ' , ' CA' , '90098 ' ,879.25, 7500.00, '30 ' );
INSERT INTO CUSTOMER
VALUES
( ' 440 ' , ' Grove Historical Museum St or e ' , '3456 Central
Each command
Ave.', ' Fullton', ' CA ' , ' 90085 ' ,345.00,5000.00, '45 ' ) ; -- --i
ends with a
INSERT INTO CUSTOMER
semicolon
VALUES
( '502 ' , ' Cards and More', '167 Bale St. ' , 'Mesa', ' CA ' , '90104 ' ,5025.75,5000.00, '15 ' );
INSERT INTO CUSTOMER
VALUES
( '586 ' , ' Al mondton Gener al Store', '3345 Devon
Ave.', ' Almondton ' , ' CA ' , ' 90125 ' ,3456 . 75,15000 . 00, ' 45' ) ;
INSERT I NTO CUSTOMER
VALUES
( '665', ' Cricket Gi ft Shop ' , ' 372 Oxfor d St.', 'G r ove', 'CA', ' 90092' ,678.90,7500.00, ' 30' );
INSERT INTO CUSTOMER
VALUES
( '713 ' , ' Cr ess Store ' , ' 12 Ri s i ng Sun Ave. ' , 'Congar ee', 'CA ' , ' 90097' ,4234.60, 10000.00, ' 15 ' );
INSERT INTO CUSTOMER
VALUES
( '796 ' , ' Unique Gifts', '786 Passmore St . • , 'Northfield', 'CA ' , ' 90098' ,124 . 75,7500 . 00, '45' );
INSERT INTO CUSTOMER
VALUES
( ' 824 ' , ' Kline' 's ' , ' 945 Gilham St.', 'Mesa ' , 'CA', ' 9010 4 ' ,2475.99,15000.00, '30 ' );
INSERT INTO CUSTOMER
VALUES
( ' 893 ' , ' All Se ason Gifts', ' 382 Wildwood
Ave. ' , ' Full t on', ' CA ' ,' 90085 ' , 935. 75, 7500. 00, '15 ' );
FIGURE 3-31
INSERT commands for the CUSTOMER table
Figt1res 3-32 throt1gh 3-37 show the scripts for the CREATE TABLE and INSERT
commands for c reating and i11serting data into the ORDERS, ITEM, and ORDER_LINE
tables in tl1e TAL Distribt1tors database. Figt1re 3-32 contains the CREATE TABLE
command for tl1e ORDERS table.
CREATE TABLE ORDERS
( ORDER_NUM CHAR ( 5) PRIMARY KEY,.,.___.,
ORDER_DATE DATE,
CUSTOMER NUM CHAR(3) );
FIGURE 3-32
ORDER_NUM
is the p rimary key
CREATE TABLE command for the ORDER S table
Creating Tables
Fig11re 3-33 contains the INSERT commands to load data into the ORDERS table.
Notice tl1e \\ray that dates are e11tered.
INSERT INTO ORDERS
VALUES
( '51608 ', '10 - 12 - 2015', '126') ;
INSERT INTO ORDERS ~ - - - - - + - t
VALUES
( '51610' , '10 - 12 - 2015', '334') ;
INSERT INTO ORDERS
Format used
to enter a date
in Oracle
VALUES
( '51613' , '10 - 13- 2015', '386') ;
INSERT INTO ORDERS
VALUES
( '51614' , '10 - 13- 2015', ' 260') ;
INSERT INTO ORDERS
VALUES
( '51617' , '10 - 15- 2015', '586' ) ;
INSERT INTO ORDERS
VALUES
( '51619' , '10 - 15- 2015', '126') ;
INSERT INTO ORDERS
VALUES
( '51623' , '10 - 15- 2015', '586') ;
INSERT INTO ORDERS
VALUES
( '51625' , '10 - 16- 2015', '796') ;
FIGURE 3-33
INSERT commands for the ORDERS table
Fig11re 3-34 contains tl1e CREATE TABLE com111ai1d for the ITEM table .
CREATE TABLE ITEM
( ITEM_NUM CHAR(4) PRIMARY KEY,----~
DESCRIPTION CHAR(30),
ON_HAND DEC I MAL(4,0),
ITEM_NUM
CATEGORY CHAR(3},
is the primary key
STOREHOUSE CHAR(l),
PRI CE DECIMAL(6,2) );
FIGURE 3-34
CREATE TABLE command for the ITEM table
Fig11re 3-35 contai11S the INSERT comn1ands to load data into tl1e ITEM table.
Chapter 3
IINSERT INTO ITEM
VALUES
( 'AH74', 'Patience' ,9.00, 'GME' , '3' ,22 . 99);
INSERT INTO ITEM
VALUES
( 'BR2 3 ' , ' Skittles ' , 21 . 0 0, 'GME' , ' 2 ' , 2 9 . 9 9) ;
INSERT INTO ITEM
VALUES
( 'CD33', 'Wood Block Set (48 piece)' ,36.00, 'TOY', '1' ,89.49);
INSERT INTO ITEM
VALUES
( 'DLSl', 'Classic Railway Set', 12.00, 'TOY',' 3', 107 .95);
INSERT INTO ITEM
VALUES
( 'DR6 7', 'Giant Star Brain Teaser' ,24.00, 'PZL' , '2',31.95);
INSERT INTO ITEM
VALUES
( 'DW23', 'Mancala' ,40 . 00, 'GME' , '3' , 50 .00);
INSERT INTO ITEM
VALUES
( 'FD ll', 'Rocking Horse' ,8.00, 'TOY' , '3' , 124 .9 5) ;
INSERT INTO ITEM
VALUES
( 'FH24', 'Puzzle Gift Set' ,65.00, 'PZL', '1' ,38.95);
INSERT INTO ITEM
VALUES
( 'KAl 2 ' , 'Cribbage Set' , 5 6. 0 0, 'GME' , ' 3 ' , 7 5. 0 0) ;
INSERT INTO ITEM
VALUES
( 'KD34', 'Pentorninoes Brain Teaser' ,60.00, 'PZL', '2' ,14.95);
INSERT INTO ITEM
VALUES
( 'KL78', 'Pick Up Sticks' ,110.00, 'GME', '1' ,10.95);
INSERT INTO ITEM
VALUES
( 'MT03', 'Zauberkasten Brain Teaser' ,4 5 .00, 'PZL', '1' ,45.79);
INSERT INTO ITEM
VALUES
( 'NL89', 'Wood Block Set (62 piece)' ,32.00, 'TOY', '3' ,119.75);
INSERT INTO ITEM
VALUES
( 'TR40', 'Tic Tac Toe' ,75.00, 'GME' , '2' ,13.99);
INSERT INTO ITEM
VALUES
( 'TW35', 'Fire Engine' ,30.0 0, 'TOY' , '2' ,118.95);
FIGURE 3-35
INSERT commands for the ITEM table
Fig11re 3-36 contains tl1e CREATE TABLE com111and for tlle ORDER_LINE table.
Notice tl1e \.Vay that the primary key is defi11ed whe11 it consis ts of more tl1an on e col11mn.
Creating Tables
CREATE TABLE ORDER LINE
(ORDER_ NUM CHAR(5),
ITEM_ NUM CHAR(4) ,
NUM_ ORDERED DECIMAL(3 , 0),
QUOTED_ PRICE DECIMAL(6 , 2),
PRIMARY KEY (ORDER_ NUM, ITEM_ NUM) ) ;+--l
-
The combination of
ORDER_NUM and ITEM_NUM
is the primary key
FIGURE 3-36
Primary key must be
entered in this format when
it consists of more than
one column
CREATE TABLE command for the ORDER LINE table
Figt1re 3-37 contains tl1e INSERT commands to load data i11to the ORDER_Lli\TE table.
INSERT INTO ORDER LINE
VALUES
( '51608', 'CD33' ,5.00,86.99);
INSERT INTO ORDER LINE
VALUES
( '51610', 'KL78' ,25.00,10.95);
INSERT INTO ORDER LINE
VALUES
( '51610', 'TR40' ,10.00,13.99);
INSERT INTO ORDER LINE
VALUES
( ' 51613 ' , 'DL5 l ' , 5 . 0 0, 10 4 . 9 5) ;
INSERT INTO ORDER LINE
VALUES
( ' 51614 ' , ' FD 11 ' , 1 . 0 0 , 12 4 . 9 5 ) ;
INSERT INTO ORDER LINE
VALUES
( '51617', 'NL89' ,4.00,115.99);
INSERT INTO ORDER LINE
VALUES
( '51617', 'TW35' ,3.00,116.95);
INSERT INTO ORDER LINE
VALUES
( ' 5 1619 ' , ' FD 11 ' , 2 . 0 0 , 12 1 . 9 5 ) ;
INSERT INTO ORDER LINE
VALUES
( ' 516 2 3 ' , 'DR6 7 ' , 5. 0 0, 2 9 . 9 5) ;
INSERT INTO ORDER LINE
VALUES
( ' 516 2 3 ' , ' FH 2 4 ' , 12 . 0 0, 3 6 . 9 5 ) ;
INSERT INTO ORDER LINE
VALUES
( ' 5 16 2 3 ' , ' KO 3 4 ' , 10 . 0 0 , 13 . 1 0 ) ;
INSERT INTO ORDER LINE
VALUES
( ' 51625', 'MT03' ,8.00,45.79);
FIGURE 3-37
INSERT commands for the ORDER LINE table
Chapter 3
DESCRIBING A TABLE
Tl1e CREATE TABLE comma11d defines a table's st11.1c t11re by listing its col11mns, data
types, and col111nn lengtl1s. Tl1e CREATE TABLE comm and also indicates \.\rl1icl1 col11mns
cannot accept nulls. W11en yo11 \\rorl{ \\rith a ta ble, yo11 m igl1t n ot l1ave access to the
CREATE TABLE command tha t \Vas 11sed to cr eate it. For exa1nple, an o tl1er progra mmer
migl1t l1ave c reated the ta ble, or p e rl1a ps yo11 c reated the ta ble sever al 1nontl1s ago b11t d id
not save tl1e comm and . You m igl1t \.\'ant to exam in e tl1e table 's st11.1c ture to see the d eta ils
about tl1e col111n ns in the ta ble. Eacl1 DBMS provides a m e tl1od to examin e a table's
st11.1c ture .
EXAMPLE 6
Describe the REP table.
In Oracle , yo11 can 11se tl1e DESCRIBE comma nd to lis t all the columns in a table
at1d tl1eir prope rties. Fig11re 3 -38 sl10\VS tl1e DESCRIBE com111a11d for tl1e REP table.
Tl1e res11lt indicates the 11a1ne of eacl1 col111m1 i11 tl1e ta ble, alo11g \\ritl1 its da ta type a11d
le ngtl1. A val11e of 1 i11 tl1e Prilnary l{ey col11m11 indicates the table 's primary l{ey column.
A cl1ecl{ m a rl{ in tl1e N11lla ble col11m11 indicat es a col11mn tl1at can accept n11ll val11es.
(Tl1e Precisio11, Scale, Defa11lt, a11d Con11nent col1111111s i11 tl1e res11lts are beyond tl1e
scope of tl1is disc11ssion .)
Home
SOL WortcshOp
0Autocommil
Rows
Schema
SQL CommillldS
Iv I V .(/
120
( Save ) ( Run )
DESCRIB'.:: REP;- - - ~
DESCRIBE command
and table name
~
Describe
"'" p
SOL H1s1ory
Object Type TABLE Object REP
• • •
~
.'
'
REP !:l!.IM
LAST NAME
CHAR
CHAR
15
✓
FIRST NAME
CHAR
15
✓
STREET
CHAR
15
✓
CITY
CHAR
15
✓
STATE
CHAR
2
✓
POSTAL CODE
CHAR
5
✓
CQMMISSIO!:l
NUMBER
7
2
✓
RATE
NUMBER
3
2
✓
A check mark
indicates a column
can accept null
values
1
2
1-9
FIGURE 3-38
DESCRIBE command for the REP table
Creating Tables
ACCESS
USER
NOTE
In Access, you use the Documenter tool to describe the tables (and other objects) in a database. To
start the Documenter in Access 2013, click the DATABASE TOOLS tab on the ribbon, and then click the
Database Documenter button in the Analyze group. In the Documenter dialog box, click the Tables tab,
select the tables that you want to describe by putting a check mark in the check box next to their
names, and then click the OK button. The Object Definition window opens and displays a report containing the requested documentation. You can customize the Documenter to control the amount of detail
included in the report.
SQL SERVER
USER
NOTE
In SQL Server, you execute the system stored procedure, sp_columns, to list all the columns in a table.
The following command will list all the columns in the REP table:
Exec sp_columns REP
The result will indicate the name of each column in the REP table, along with its data type and
length. A value of 1 in the Nullable column indicates a column that can accept null values. (The
remaining columns that appear in the results are beyond the scope of this discussion.)
Chapter 3
Chapter Summary
•
Use the CREATE TABLE command to create a table by typing the table name and
then listing within a single set of parentheses the columns in the table.
•
Use the DROP TABLE command to delete a table and all its data from the
database.
•
Some commonly used data types in are INT, SMALLINT, DECIMAL, CHAR,
VARCHAR, and DATE. Microsoft Access does not support DECIMAL.
•
A null data value (or null) is a special value that is used when the actual value for a
column is unknown, unavailable, or not applicable.
•
Use the NOT NU LL clause in a CREATE TABLE command to identify columns that
cannot accept null values.
•
Use the INSERT command to insert rows into a table.
•
Use the SELECT command to view the data in a table.
•
Use the UPDATE command to change the value in a column.
•
Use the DELETE command to delete a row from a table.
•
You can save SOL commands in a script file in Oracle and SOL Server. In Microsoft
Access, you save the commands as a query object in the database.
•
You can use the DESCRIBE command in Oracle to display a table's structure and
layout. In Access, you use the Documenter tool to produce a report of a table's structure and layout. In SOL Server, execute the sp_columns stored procedure to display
the structure and layout of a table.
Key Terms
breadcrumb
null data value
CREATE TABLE
script
data type
script file
DELETE
script repository
DESCRIBE
SELECT
DROP TABLE
Structured Query Language (SOL)
INSERT
UPDATE
NOT NULL
workspace
null
Review Questions
1. How do you create a table using SOL?
2. How do you delete a table using SOL?
3. What are the common data types used to define columns using SOL?
Creating Tables
4. Identify the best data type to use to store the following data in Oracle, in SOL Server, and
in Access:
a.
b.
The month, day, and year that an employee was hired
An employee's Social Security number
c.
The department in which an employee works
d.
An employee's hourly pay rate
5. Identify the following column names as valid or invalid in Oracle:
a.
b.
COMMISSIONRATE
POSTAL- CODE- SCHAR
c.
d.
SHIP TO ADDRESS
INVOICE-NUMBER
6. What is a null value? How do you use SOL to identify columns that cannot accept null values?
7. Which SOL command do you use to add a row to a table?
8. Which SOL command do you use to view the data in a table?
9. Which SOL command do you use to change the value in a column in a table?
10. Which SOL command do you use to delete rows from a table?
11. How do you display the columns in a table and their characteristics in Oracle?
C RITICAL
THINKING
C RITICAL
THINKING
12. Explain the difference between the CHAR data type and the VARCHAR data type. Use the
Internet to find examples of when to use VARCHAR and when to use CHAR. Be sure to
cite the URL(s) that provided the examples as references at the end of your document.
13. Use the Internet to research BOOLEAN data types. What is a BOOLEAN data type and
what is it called in Oracle, SOL Server, and Access? Be sure to cite the URL(s) that provided the information at the end of your document.
Exercises
To print a copy of your commands and results using Oracle, use the browser's Print command
on the File menu or click the Print button on the browser's toolbar.
To print a copy of your commands and results using Access, use the instructions provided
in the chapter to save your commands as query objects. To print a command, start Word or
another word processor and create a new document. Select the SOL command in Access, copy
it to the Clipboard, and then paste it into the document. To copy and paste a command's
results, right-click the datasheet selector (the box in the upper-left comer of the datasheet) to
select the entire datasheet, copy it to the Clipboard, and then paste it into the document.
To print a copy of your commands and results using SOL Server, start Word or another
word processor and create a new document. Select the SOL command in SOL Server, copy it
to the Clipboard, and then paste it into the document. To copy and paste a command's results,
right-click the datasheet selector (the box in the upper-left corner of the datasheet) to select
the entire datasheet, copy it to the Clipboard, and then paste it into the document.
If you are using Windows 7 or higher, you also can use the Snipping Tool to copy and paste
SOL commands and query results into a Word document. You can use the Snipping Tool with
Oracle, Access, and SOL Server.
•• •
Chapter 3
T AL Distributors
Use SOL to complete the following exercises.
C RITICAL
1.
Create a table named SALES REP. The table has the same structure as the REP table
shown in Figure 3-11 except the LAST_NAME column should use the VARCHAR data type
and the COMMISSION and RATE columns should use the NUMBER data type. Execute
the command to describe the layout and characteristics of the SALES_REP table.
2.
Add the following row to the SALES_REP table: rep number: 35, last name: Lim; first
name: Louise; street: 535 Vincent Dr.; city: Grove; state: CA; postal code: 90092; commission: 0.00; and rate : 0.05. Display the contents of the SALES_REP table.
3.
Delete the SALES REP table.
4.
Run the script file for the TAL Distributors database to create the five tables and add
records to the tables. Be sure to select the script file for the particular DBMS that you are
using (Oracle, SOL Server, or Access). (Note: If you do not have the script files for this
text, ask your instructor for assistance.)
5.
Confirm that you have created the tables correctly by describing each table and comparing the results to Figures 3-11 , 3-30, 3-32, 3-34, and 3-36.
6.
Confirm that you have added all data correctly by viewing the data in each table and
comparing the results to Figure 2-1 in Chapter 2.
7.
Review the data for the ITEM table in Figure 2-1 in Chapter 2 and then review the data
types used to create the ITEM table in Figure 3-34. Suggest alternate data types for the
DESCRIPTION, ON_HAND, and STOREHOUSE fields and explain your recommendations.
THINKING
Colonial Adventure Tours
Use SOL to complete the following exercises.
1.
Create a table named ADVENTURE TRIP. The table has the same structure as the TRIP
table shown in Figure 3-39 except the TRIP_NAME column should use the VARCHAR
data type and the DISTANCE and MAX_GRP_SIZE columns should use the NUMBER
data type. Execute the command to describe the layout and characteristics of the
ADVENTURE TRIP table.
2.
Add the following row to the ADVENTURE_TRIP table: trip ID: 45; trip name: Jay Peak;
start location: Jay; state: VT; distance: 8; maximum group size: 8; type: Hiking and season: Summer. Display the contents of the ADVENTURE_TRIP table.
3.
Delete the ADVENTURE TRIP table.
4.
Run the script file for the Colonial Adventure Tours database to create the six tables and
add records to the tables. Be sure to select the script file for the particular DBMS that you
are using (Oracle, SOL Server, or Access) . (Note: If you do not have the script files for
this text, ask your instructor for assistance.)
5.
Confirm that you have created the tables correctly by describing each table and comparing the results to Figure 3-39.
6.
Confirm that you have added all data correctly by viewing the data in each table and
comparing the results to Figures 1-4 through 1-8 in Chapter 1.
Creating Tables
GUIDE
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
G UID E_Nl/J\,C
Cl-11\R
4
No
Guide number
(primar)1 key)
L1\ST_NM1IE
Clu\R
15
Guide last na1ne
FIRST_NrU.IB
CHAR
15
Guide first name
ADDRESS
Clli\R
?_:,
Guide street address
CITY
CHAR
25
Guide city
STATE
CHAR
2
Guide state
POSTAL_CODE
CTlAR
;,
-
Guide postal code
Pl 101\' t.;_NU!vl
CHAR
12
Guide phone number
J-IJ RE_D1\'J'E
Dr\1' E
Date guide ,vas hired
TRIP
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
TRJP_JD
DECINIAL
3
0
No
Trip ID (primary key)
TRIP_N1U.fE
CIJAR
75
Trip name
ST1\RT_LOC1\TION
CHAR
50
Start location for trip
STATE
Clli\R
2
Trip state
DIS'J'J.\N(;E
DECINIAL
4
lvfAX_GRP_SJZE
DECil\JAL
TYPE
c:111\R
20
Trip type
SEASON
C:I-IAR
20
Trip season
Column
Type
Length
CUSTOA,lER_NU11
CIIAR
4
LAS'l'_NA!vl g
Clli\ R
JO
Cu.'ito111er last 11an1e
FIR.ST_NM1E
CHAR
3()
Custo1ner tirst name
1\DDIIBSS
Clli\R
JS
Custon1er street address
CITY
CII,\R
35
Custo111er city
STATE
CIL\R
2
Customer state
POS1'AL_CO DE
CI-li\R
;:,
-
Customer postal code
PilONE
CIL\R
12
Customer phone number
0
Distance (length) of trip
0
lvfa,--.dmu1n nu1nber of
persons
CUSTOMER
FIGURE 3-39
Decimal
places
Nulls
allowed?
Description
No
Custon1cr number
( pri n1ary key)
Table layouts for the Colon ial Adventure Tours database
Chapter 3
RESERVATION
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
lIBSEllVJ',.'l'ION_ID
Cf!J.\ll
7
No
lleservation 1D (ptimary
key)
TRJP_JD
DECh\iI,\L
3
TRJP_D.A 'rE
Di\TE
NU!vl_PElIBONS
DEC livl.t\.L
3
0
Number of persons in
reservation
l'RIP_PRlCE
DECliVLAl,
6
2
Trip price per person
OTIIER_FEES
DECTivli\L
6
2
Other fees per person
CUS1'0~fER_NU1'1
CIIAR
4
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
1'R1P_ID
DECLVIAL
3
0
No
Trip ID (prin1ary key)
GUIDE_NlJM
Cll1-\R
4
No
Guide nun1ber (prin1ary
key)
Trip JD of the t1ip being
reserved
0
'rrip date
Custon1er nurnber
TRIP- GUIDES
FIGURE 3-39
C RITICAL
7.
TH INKING
C RITICA L
TH INKING
Table layouts for the Colonial Adventure Tours database (continued)
Review the data for the TRIP table in Figure 1-5 in Chapter 1 and then review the data
types used to create the T RIP table in Figure 3-39. Suggest alternate data types for at
least two fields that currently have the CHAR data type and at least two fields that
cu rrently have the DEC IMAL data type. Create but do not execute t he SOL command
to create the TRIP table using these alternate data types.
8.
Colonial Adventu re Tours would like to increase the length of the START_LOCATION field
in the TRIP table to 75 characters. C reate but do not execute the SOL statement to
change the length of the field to 75 characters.
Creating Tables
Solmaris Condominium Group
Use SOL to complete the following exercises.
1.
Create a table named VACATION UNIT. The table has the same structure as the
CONDO_UNIT table shown in Figure 3-40 except the CONDO_ID, LOCATION_NUM, and
CONDO_FEE columns should use the NUMBER data type. Execute the command to
describe the layout and characteristics of the VACATION_UNIT table.
2.
Add the following record to the VACATION_UNIT table: condo ID: 20; location number: 2;
unit number: A04; square feet: 1680; bedrooms: 3; bathrooms: 3; condo fee: 775; and
owner number: BL720. Display the contents of the VACATION_UNIT table.
3.
Delete the VACATION UNIT table.
4.
Run the script file for the Solmaris Condominium Group database to create the five tables
and add records to the tables. Be sure to select the script file for the particular DBMS that
you are using (Oracle, SOL Server, or Access) . (Note: If you do not have the script files
for this text, ask your instructor for assistance.)
5.
Confirm that you have created the tables correctly by describing each table and comparing the results to Figure 3-40.
6.
Confirm that you have added all data correctly by viewing the data in each table and
comparing the results to Figures 1-9 through 1-13 in Chapter 1.
Chapter 3
LOCATION
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
LOC1\TION_NUl\ll
DECTh-11\L
2
0
No
Location number
(primary key)
LOCATION_t\AME
CIIAR
25
Location nan1e
,<\DDRESS
Cl-it\R
25
Location street address
CITY
Cll-1\R
25
Location city
S'l'i\'fE
Cll.i\l\
2
Location state
POS'f1VJ_CODE
Clll\R
:,
-
Location postal code
Column
Type
Length
O\VNER_NlThl
CHt\R
5
L.t\ST_N1\i\llE
Cllr\R
0_:,
O,vncr last name
FlRS'f _N1\NlE
ClL-\R
25
O,vner first name
1\DDRESS
CllAR
25
O\\,ncr street address
CITY
CFIJ\R
25
O,vncr city
STi\'l'E
ClL\R
2
o,vner state
POS1'1\L_CODE
Cfu\R
5
0\\1 11cr postal code
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
COJ\TDO_TD
DECINIAL
4
()
No
Condo JD (pri1nary key)
LOCA'f!ON_NU.t-1
DECL\ilAL
2
0
Location nu1nber
UNTT_NlTh1
CITAR
3
0
Unit nu1nber in condo
building
SQR_FT
DECI1IAL
:,
-
0
Size of condo unit in
square feet
BDRMS
DBCh\111\L
2
0
Number of bedrooms
in condo
BATTIS
DRCl~l1\L
2
0
Nun1ber of bathroon,s
in condo
CONDO_l<'EE
DEC LvlAL
6
2
!Vlonthly condo fee
O\VNER_NlTh,J
Cll.t\.R
s
OWNER
Decimal
places
Nulls
allowed?
Description
No
O,vner number
(pri111ary key)
CONDO_UNIT
FIGURE 3-40
Number of condo o,vner
Table layouts for the Solmaris Condominium Group database
Creating Tables
SERVICE_CATEGORY
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
CATEGORY_NUM
DECIMAL
4
0
No
Category number
(primary key)
C1\TEGOR't'_
DESCRrPTTON
CIL\R
Category description
SERVICE_ REQUEST
Column
Type
Length
Decimal
places
Nulls
allowed?
Description
SERVTCE_ ill
DECT~fAL
4
0
No
Service ID
(prin1ary key)
CONDO_ill
DECh\lu\L
4
0
Condo 11) of the condo
for ,vhlch service
is requested
CA'l'EGORY_NUM
DECTh1AL
0
Category nu1nber of
the requested service
DE8CR1PTJON
CIIAR
255
Description of
specific service
requested for condo
S11\TUS
Cl-L\R
255
Description of status
of service request
EST_IIOlJR..':l
DECL\1.i\L
4
2
Estimated number of
hours required to
co1nplcte the service
SPENT_JTOUR8
DECTh1IAL
4
2
Tlours aJready spent
on the service
NEXT_SER\TJCE_DATE
D1\TE
FIGURE 3-40
C RITICA L
THINKING
7.
Next scheduled date
for \vork on this
service (or null if no
next service date is
specified)
Table layouts for the Solmaris Condominium Group database (continued)
The SERVIC E_REQUEST table uses the CHAR data type for the DESCRIPTION and
STATUS fields. Is there an alternate data type that could be used to store the values in
these fields? Justify your reason for choosing an alternate data type or for leaving the
data type as CHAR.
C H A PTER
SINGLE-TABLE
UERIES
OBJECTIVES
•
Retrieve data from a database using SOL commands
•
Use simple and compound conditions in queries
•
Use the BETWEEN, LI KE, and IN operators in queries
•
Use computed columns in queries
•
Sort data using the ORDER BY clause
•
Sort data using multiple keys and in ascending and descending order
•
Use aggregate functions in a query
•
Use subq ueries
•
Group data using the GROUP BY clause
•
Select individual groups of data using the HAVING clause
•
Retrieve columns with null values
INTRODUCTION
In this chapter, you will learn about the SOL SELECT command that is used to retrieve data in a
database. You will examine ways to sort data and use SOL functions to count rows and calculate
totals. You also will learn about a special feature of SOL that lets you nest SELECT commands by
placing one SELECT command inside another. Finally, you will learn how to group rows that have
matching values in some column .
CONSTRUCTING SIMPLE QUERIES
One of the 1nost importa11t feat11res of a DBMS is its ability to ans\ver a wide vai-iety of
q11estions concerning the data i11 a database. \\The11 you 11eed to find data that ans\vers a
specific question, you use a q11ery. A query is a qt1estio11 represented in a \Vay tl1at the
DBMS can t1nderstand.
111 SQL, yo11 use tl1e SELECT co1nmand to query a database. Tl1e basic form of tl1e
SELECT cominand is SELECT-FROM-\\THERE. After you type tl1e \\7ord SELECT, you list
tl1e columns that yo11 want to i11clude in tl1e query results. This portion of the command is
called the SELECT clause. Next, you type tl1e \\7 ord FROM follo\ved by tl1e name of the
table tl1at co11tains the data you need to qt1ery. Tllis portion of the command is called tl1e
FROlVI clause. Finally, after the \Vord \\THERE, yo11 list any conditions (rest1ictions) tl1at
Chapter 4
apply to tl1e data yo11 \.Vant to retrieve. Tl1is optional portion of the command is called the
WHERE clause . For example, wl1en yo11 need to retrieve tl1e rows for only those c11stom ers \.\1itl1 credit limits of $ 7,500, incl11de a condition in tl1e \VHERE cla11se specifying
tl1at tl1e val11e in tl1e CREDI'f _LI11IT col11mn must be $ 7,500 (C REDI'f_LINIIT = 7500).
Tl1er e are no special formattil1g r11les in SQL. In tl1is text, the FROM cla11se ru1d the
\\THERE clai1se (wl1en it is i1sed) appear 011 separate lines 011ly to malte tl1e co1nn1ands
more readable and i1nde rs tandable.
Retrieving Certain Columns and All Rows
You can \.\7rite a com111and to retrieve specified colum11s and all ro\.\7S from a table , as
illus trated il1 Exan1ple 1.
EXAMPLE 1
List the number, name, and balance for all customers.
Beca11se yoi1 need to list all cus tom ers, the \VHERE cla11se is i1nnecessary; yoi1 do not
11eed to p11t any r estrictions on tl1e data to re trieve. Yoi1 list tl1e coli1mns to be i11cluded
(CUSTOMER_Nill/1, CUST01t1ER_NAME, and BALANC E) il1 tl1e SELECT clause and tl1e
11ame of the table (CUSTOMER) i11 tl1e FROM cla11se. Type a semicolon to i11dicate the end
of the comma11d , and tl1en click the Ri1n button to display tl1e results. Tl1e quer y and its
results appear in Figure 4-1.
ORACLE' Application Express
Home Home
Application Builcler,..
SOL Workshop
0 Autocommit
Rows
ifeam Oevelopmen
Rows list box
set to display
20 rows in the
results
SQL Commands
[2.(J
;,7 V I/
( Save ) ( Run )
SELEC: cus: OMER_NUM, CUSTOMER_Nll'E, BALA.~CE
fROM CUSTOMER; - - - - - - - - - - - - - - - - - - ,
Results
L Hist ry
-
•
126
Toys Galore
1210.25
260
Brookings Direct
575
334
The Everything Shop
2345.75
386
Johnson's Department Store
879.25
440
Grove Historical Museum store
345
502
Cards and More
5025 75
586
Almondton General Store
3456.75
665
Cricket Gift Shop
678.9
713
Cress Slore
4234.6
796
Unique Gifts
124.75
824
Kline's
2475.99
893
All Season Gifts
935.75
12 rows retumed in 0.00 seconds
FIGURE 4-1
Columns to
include in the
query resu lts
Data will
come from the
CUSTOMER
table
Query results
Q21mloa11
SELECT command to select certain columns from the CUSTOMER table
Single-Table Queries
NOTE
In Oracle Application Express, the number in the Rows list box indicates the maximum number of rows
that Oracle will display in the query results. The default value is 10. To change the value, either click the
arrow and select a new value from the list or type a new value in the box. Figure 4-1 shows the Rows
list box after the user changed it to display 20 rows. When you run a query that will include more rows
than the number set in the Rows list box, Oracle will display a message indicating this fact. If this
situation occurs, increase the number in the Rows list box, and then click the Run button again to
display the complete query results.
NOTE
If you are using Access or SOL Server to run the SOL commands shown in this text, your query
results will differ slightly from the results shown in the figures. In Access, the BALANCE field has the
CURRENCY data type and Access will display values in this column with two decimal places and a
dollar sign. In SOL Server, values in the BALANCE field will be displayed with two decimal places
and DATE field values might be displayed with a time value. Although your output might be formatted
differently, the data should be the same as what you see in the figures.
Retrieving All Columns and All Rows
Yo1.1 can 1.1se the same type of command ill1.1s trated in Example 1 to retrieve all col1.1mns
and all rO\\'S fro1n a table. As Example 2 ill1.1strates, l1owever, yo1.1 can 1.1se a sl1ortcut to
accomplisl1 this tasl{.
EXAMPLE 2
List the complete ITENI table.
Instead of incl1.1ding every col1.1 mn in tl1e SELECT cla1.1se, yo1.1 can use an asterisli (*)
to indicate tl1at yo1.1 want to iI1clude all columns. Tl1e result lists all col1.11nns in the order
in wl1ich yo1.1 described tl1em to the DBMS when you created tl1e table. If yo1.1 want tl1e
col1.1mns listed iI1 a different order, type tl1e column 11ames in tl1e order in \.Vhicl1 yo1.1 wa11t
tl1e1n to appear i11 the q1.1ery rest1lts. In tl1is case, asst1ming that tl1e default order is appropriate, yo1.1 ca11 1.1se tl1e q1.1ery sl10\.\'n i11 Fig11re 4 -2 to display tl1e complete ITEM table.
••
Chapter 4
[ Home
SQL Workshop
SQL Commands
I v I " ,? ( Save ) ( Run )
SELEC1 •- - - - - - - - - - - - - - - - - - - - !
0 Autocommil
(20
Rows
FROM ITEM;
Asterisk indicates
all columns will
be included
Results
• •
•
•
•
•
AH74
Patience
9
GME
3
22.99
BR23
SkiWes
21
GME
2
29.99
C033
Wood Block Set (48 piece)
36
TOY
1
89.49
OL51
Classic Railway Set
12
TOY
3
107.95
OR67
Giant Star Brain Teaser
24
PZL
2
31 .95
OW23
Mancala
40
GME
3
50
F011
Rocking Horse
8
TOY
3
124.95
FH24
Puzzle Gill Set
65
PZL
1
38.95
KA12
Cribbage Set
56
GME
3
75
K034
Pentomlnoes Brain Teaser
60
PZL
2
14.95
Kl78
Pick Up Slicks
110
GME
1
10 95
MT03
Zauberkasten Brain Teaser
45
PZL
1
45.79
NL89
Wood Block set (62 piece)
32
TOY
3
119.75
TR40
n cTacToe
75
GME
2
13.99
TW35
Fire Engine
30
TOY
2
118.95
15 rows returned in 0.0 1 seconds
FIGURE 4-2
l:!21m!!li!!I
SELECT command to select all columns from the ITEM table
Using a WHERE Clause
\\'11en yo1.1 need to re trieve rows that satisfy some condition , yo1.1 incl1.1de a vVHERE clause
in tl1e SELECT co1nm and , as sh o\vn in Example 3.
EXAMPLE 3
\Vhat is the name of the customer with customer numbe r 126?
Y01.1 ca11 1.1se a WHERE clause to restrict the q1.1e ry res1.1lts to c1.1stome r 111.11n b er 126, as
show11 i11 Fig1.1re 4 -3. Because CUSTONIER_l\TUM is a cl1aracter column, tl1e val1.1e 126 is
e11closed i11 single quotatio11 1na rlcs. 111 additio11, beca1.1se tl1e CUSTONIER_l\TUM colt11m1 is
tl1e pritnary lcey of tl1e CUSTOMER table, tl1ere ca11 be 011ly 011e custo1ner v\rl1ose 111.11nber
1na tcl1es tl1e 111.11nbe r it1 tl1e \\TI-JERE cla1.1se.
Home
SQL Workshop
0 Autocommlt
SQL Commands
[20
Row s
Iv I " ,?
SEliCI CUSTOMER MAME
FROM CUSTOMER
!iffiERE COSIOMER_ ?lUM
Results
I
( Save )( Run )
= ' 126' ;- - - - - - - - - - i
n
Value is enclosed in
single quotation marks
because CUSTOMER_N UM
is a character column
Toys Galore
1 rows returned in 0.00 seconds
FIGURE 4-3
Download
SELECT command to find the name of customer number 126
Single-Table Queries
Tl1e co11dition in tl1e preceding \\THERE cla11se is called a simple condition. A simple
condition has tl1e form colu1n11 name, comparison operator, and tl1en either another
coltnnn natne or a value. Fig11re 4-4 lists the comparison operators tl1at you can 11se in SQL.
COMPARISON OPERATOR
DESCRIPTION
Equal to
>
Less than
<
Greater than
<=
Less than or equal to
>=
Greater than or eq11a] to
<>
Not equal to
FIGURE 4-4
Comparison operators used in SOL commands
EXAMPLE 4
Find the 11ame of each customer located in the city of Grove.
Tl1e only difference betwee11 tllis example and tl1e previo11s one is tl1at in Example 3,
tl1ere co11ld only be one ro\v in tl1e ans\\7er because tl1e condition i11volved tl1e table 's primary l{ey. In Example 4, tl1e condition involves a col11mn tl1at is not the table's pri1nary
l{ey. Because there is more tl1an one c11stomer located in the city of Grove, the results can
and do contain more tl1an one ro\v, as sl10\\rn in Fig11re 4-5.
I Home SOL Workshop
E2l Autocommit
Rows
SQL Commands
(io
!vlV.f
: Save )( Run )
SELECT CUSTOMER NAME
FROM CUSIOt-lER
WHERE CITY = 'Grove';
Results
......
l
n
Brooklngs Dlred
Cricket Gift Shop
cnoe
L
-
2 rows returned in 0.01 seconds
FIGURE 4-5
Cond it ion
Download
SELECT command to find all customers located in Grove
EXAMPLE 5
Find the 11ame, balance, and credit limit for all customers with balances that exceed
their credit limits.
Chapter 4
A simple condition can also compare the val11es stored in t\.vo col11mns. In Fig11re 4-6,
tl1e \\THERE clause i11cludes a comparison opera tor that selects only tl1ose rows in wl1icl1
tl1e balance is greater than tl1e credit llinit.
Home
SOL Workshop
~Autocommit
Rows
SQL Commands
j20
v
I (; of>
r Save ' ( Run )
SELECT COST◊MER_Nl\ME, Bl\LMICE, CR£DII_ LIMII
FROM CtJSIOMtR
lilfil:RE BALA!lCE > CREDII_LIMIT ;
at
Results
Cards and More
5025.75
1 rows returned in 0.01 seconds
FIGURE 4-6
H st rv
5000
Download
SELECT command to find all customers with balances that exceed their credit limits
Using Compound Conditions
Tl1e conditions you have seen so far are called simple co11ditio11s. Tl1e follo\.,,ing examples
require compo11nd conditions. You form a compotmd condition by co1111ecting t\.vo or
more simple co11ditio11s with the AND, OR, and NOT operators. \Vhen tl1e Al'\TD operator
com1ects simple co11ditions, all the simple conditions m11st be true in order for the
con1po1md condition to be true. \i\Then the OR operator connects tl1e simple co11ditions,
tl1e compound condition \.Vill be true wl1enever any one of the simple co11ditio11s is tr11e.
Preceding a condition by the NOT operator reverses the tr11tl1 of the original condition.
For example, if tl1e origi11al condition is tr11e, the 11ew condition will be false ; if tl1e original
condition is false, tl1e new 011e will be tr11e.
EXAMPLE 6
List the descriptions of all items that are located in storehouse 3 and for which there are
more tha.n 25 units on hand .
111 Example 6, yo1111eed to retrieve those items tl1at meet botli co11ditions-the
storel1011se number is equal to 3 ancl the 11-umber of 11nits on l1and is greater than 25.
To find the answer, you form a compo11nd condition 11sing the AND operator, as shown in
Fig11re 4-7. The q11ery exa1nines the data iJ1 the ITENI table and lists the items tl1at are
located i11 storeho11se 3 and for ,vhich there are more tl1an 25 units on hand. W11en a
WHERE cla11se uses tl1e AND operator to con11ect simple conditions, it also is called an
AND condition.
Single-Table Queries
Home
SOL Workshop
~ Autocommit
Rows
SQL Commands
120
lvl V Q
SELECT DESCRIPTION
FROM ITEM
WHERE STOREHOUSE a '3 '
MID ON_!IJI.ND > 25 ;
Results
___.
(
Save ) ( Run )
AND cond ition
p n De
ved s
, 1s1ory
·,mi1,m
Mancala
Cribbage Set
Wood Block Set (62 piece)
3 rows returned in 0.01 seconds
FIGURE 4-7
Download
SELECT command with an AND condition on separate lines
For readability, each of tl1e simple co11ditions il1 tl1e query shov.,11 in Figure 4 -7
appears on a separate line. Son1e people prefer to put the co11ditions 011 tl1e same line vvitl1
pare11tl1eses arou11d eacl1 simple co11ditio11, as sl1ow11 in Figure 4-8. Tl1ese tv.ro methods
accomplisl1 tl1e sai11e thing. 111 this text, simple conditio11s will appear 011 separate lines
and vvithout pare11tl1eses.
. Home
SOL Workshop
~Autocommit
Rows
SOL Commands
120
lvlV Q
,
Save ) ( Run )
SELEC7 DESCRIPTION
FROM ITEM
WHERE (STOREHOUSE = '3 ' ) .AND (Otl_l!AND > 25) ;
,-
Results
platn Describe S~ved Sul History
'mri!im
Mancala
I
Cribbage Set
Wood Block Set (62 piece) ,
3 rows returned in 0.00 seconds
FIGURE 4-8
Qownloi!d
SELECT command with an AND condition on a single line
EXAMPLE 7
List the descriptions of all item s that are located in storehouse 3 or for which there are
more than 25 units on hand.
lI1 Example 7, yot1 11eed to retrieve descriptions for tl1ose items for which the storehot1se numbe r is eqt1al to 3, or the numbe r of units on hai1d is greater tl1an 25, or botl1.
To do this, yot1 form a compot1nd condition using the OR operator, as shown i11 Figure 4-9.
When a v,TI-IERE clause t1ses the OR operator to connect simple conditions, it also is called
an OR condition.
Chapter 4
Home
SOL WorkshOp
0 Autocommlt
SQL Commands
Rows
[211
SELECT C!SCRIPTION
FROM I TEM
WliERE SIORD!OOSE • ' 3 '
OR Otl _li.>.ND > 25;
Results
.
~ Save )( Run )
OR condition
V
I
.la
Iv IV ~
l
H tory
:.! HIJ:I
Patience
Wood Bloclc Set (48 piece)
Classic Railway Set
Mancala
Rocking Horse
Puzzle Gift Set
Cribbage Set
Pentominoes Brain Teaser
Pick Up Slicks
Zauberkasten Brain Teaser
Wood Block Set (62 piece)
TIC Tac Toe
Are Engine
13 rows returned in 0.00 seconds
FIGURE 4-9
DQWRIQa!I
SELECT command with an OR condition
EXAMPLE 8
List the descriptions of all items that are not in storehouse 3.
For Example 8 , you could t1se a simple co11dition a11d tl1e not equal to operator
(\\THERE STO REI1 OUSE < > 13 1). As a11 alter11ative, you co11ld 11se tl1e EQUAL operator
(= ) in tl1e condition and precede tl1e e11tire co11dition \Vith the NOT operator, as sl1own in
Figure 4 -10. \\Tl1en a ,,THERE cla11se uses tl1e NOT operator to connect silnple co11ditio11s,
it also is called a NOT condition.
Home
SQL Workshop
0Autocommil
Rows
SQL Commands
(20
Iv IV .f
( Save )( Run )
Sa.tCT DESCRI PTION
FROM I TEM
WHL'E NOT (SIORD!Ot!SE = ' 3 ' ) ; - - - - 1
Results
NOT condit ion
r
•
•
•
Skittles
Wood Bloclc Set (48 piece)
Giant Star Brain Teaser
Puzzle Gift Set
Pentomlnoes Brain Teaser
Pick Up Slicks
Zauberkasten Bram Teaser
nc Tac Toe
Fire Engine
9 rows returned In 0.00 seconds
FIGURE 4-10
Download
SELECT command with a NOT condition
Single-Table Queries
Yott do not need to enclose tl1e condition STOREHOUSE = '3 ' in parentheses, bttt
doing so mal{es tl1e co1nmand more readable.
Using the BETWEEN Operator
Exai11ple 9 requires a compound condition to dete11nit1e tl1e a11swer.
EXAMPLE 9
List the number, name, and balance of all customers with balances greater than or equal
to $2,000 and less than or equal to $5,000.
Yott can ttse a \\THERE clattse a11d tl1e AND operator, as sho\-\r11 i11 Figttre 4-11, to
retrieve tl1e data.
I Home SOL Workshop SQL Commands
E21Autocommil
Rows
[io
!vlV.?
~ Save )( Run )
SELECT COSTOMER_Ntn~, CUStOMER_NA.'fE, BALANCE.
FROM CUSTOMER
WHEE\='. BJ>.LJ,.NCE >= 2000
MID BAUNCE <= 5000 ;
Results f
==~=i~ De rlbe Saved SUL History
"T'f""..r:} ~iJJ
•
334
The Everything Shop
2345.75
586
Almondlon General Store
3456.75
713
Cress Store
4234.6
824
Khne·s
2475.99
4 rows returned in O00 seconds
FIGURE 4-11
DownJoad
SELECT command with an AND condition for a single column
NOTE
In SOL, numbers included in queries are entered without extra symbols, such as dollar signs and
commas.
An alternative to tl1is approach uses tl1e BET\\TEEN operator, as sl1own in Figttre 4-12.
Tl1e BETWEEN operator lets yott specify a range of valttes in a condition.
Chapter 4
Home
SOL Workshop
~Autocommil
Rows
SQL Commands
lv l V ,?
120
(
Save ' ( Run)
SELECT CUSTOMER_NUM, CUSTOMER_NA.'ir, B.~lCE:
fROM CUSTOMER
IIBERE BALANCE BETWEEN 2000 AND 5000;
plain
Results
-
·-
Describe Saved SUL
""TT".r,, l"Tf!
"
-
lfrstory
I
334
The Everything Shop
2345.75
586
Almondton General Store
3456.75
713
Cress store
4234.6
824
Kline's
2475.99
4 rows returned in 0.01 seconds
FIGURE 4-1 2
Download
SELECT command with the BETWEEN operator
Tl1e BET\VEEN operator is i11clt1sive, 111ea11i11g tl1at tl1e qt1e ry selects a valt1e eqt1al to
eithe r valt1e in the condition and in the range of the valt1es. 111 the clat1se BET\VEEN 2000
a11d 5000, for example, valt1es of 2,000 tl1rougl1 5 ,000 would 1nake tl1e co11ditio11 trt1e. Yot1
ca11 t1se tl1e BET\\TEEN ope rator i11 Oracle, SQL Server , a11d Access.
Tl1e BE'f\VEEN ope rator is n ot an esse11tial featt1re of SQL; yot1 h ave jt1st seen that
yot1 ca11 obtai.11 tl1e sa111e rest1lt witl1out it. Usi11g tl1e BET\\TEEN operator, 110,,,ever, does
1nalre certail1 SELECT comma11ds si111ple r to con s trt1c t .
Using Computed Columns
You cru1 p erfor1n co1nputations u si11g SQL que ries. A con1puted colunm does not exist in
tl1e database but can be compt1ted t1si11g data in tl1e existing columns. Co1nputations can
involve any aritllllletic op erator sl10,vn in Figure 4-13 .
ARITHMETIC OPERATOR
DESCRIPTION
+
Additio11
Subtraction
Multiplication
I
Division
FIGURE 4-13
Arithmetic operators
EXAMPLE 10
Find the number , name, and available credit (the credit limit minus the balance) for
each customer.
Single-Table Queries
Tl1er e is no column i11 tl1e TAL Dis tribt1tors database that s to res a ci1s tom e r's
available credit, but yoi1 can co1npi1te tl1e available c redit i1s i11g tl1e CREDIT_LIMIT
ru1d BALANCE coli1n1ns. To compi1te the available credit, yoi1 use the expression
CREDIT_LIMIT - BALANCE , as shown i11 Figi1re 4-14.
Home
SOL Worlcshop
~Autocommit
Rows
SQL Commands
Iv I V ~
120
( Save ;( Run )
SELECT cus: O!ER_NUM, CUS:IOMER_NA!-IE, CREDIT_L IMIT - BllLllNCT
FROM CUSTOMER;
126
Toys Galore
6289.75
260
Brookings Direct
9425
334
The Everything Shop
5154.25
386
Johnson's Department Store
6620.75
440
Grove Historical Museum Store
4655
Computed
502
Cards and More
-25.75
column results
586
Almondton General Store
11543.25
665
Cricket Gift Shop
6821.1
713
Cress Store
5765.4
796
Unique Gifts
7375.25
824
Kline's
12524.01
893
All Season Gifls
6564.25
12 rows returned in 0.01 seconds
Download
SELECT command with a computed column
FIGURE 4-14
You also can assign a. 11-am e to a compi1ted colum11 by following tl1e compt1ta tion with
tl1e \.Vord AS a11d the desired nam e. Tl1e comma11d sl10\.vn in Figi1re 4-15, for example,
assigns the nam e AVAILABLE_CREDIT to the computed coliunn.
Home
SOL Worlcshop
~ Autocommit
Rows
SQL Commands
120
Iv I V 4>
( Save )( Run )
-
-
S ELECT cus: OME:R NUM, CUSTOME..'l NAME , CREDIT Lil{IT - BALl\..';CE ~.5 AVAIi.ABLE CREDIT
fROM CUSTOMER;
-
Results
-
s
Computed
column name
•
126
Toys Galore
6289.75
260
Brookings Direct
9425
334
The Everything Shop
5154.25
386
Johnson's Department Store
6620.75
440
Grove Historical Museum Store
4655
502
Cards and More
-25.75
586
Almondton General Store
11543.25
665
Cricket Gift Shop
6821.1
713
Cress Store
5765 4
796
UnlQue Gifts
7375 25
824
Kline's
12524.01
893
All Season Gifts
6564.25
12 rows returned in 0.00 seconds
FIGURE 4-15
QQwrnoag
SELECT command with a named computed column
Chapter 4
NOTE
You can use names containing spaces following the word AS. In many SQL implementations, including
Oracle, you do so by enclosing the name in quotation marks (for example, AS "AVAILABLE CREDIT").
Other SQL implementations require you to enclose the name in other special characters. For example,
in Access you would enclose the name in square brackets (AS [AVAILABLE CRED IT]). In SQL Server,
you can use either quotation marks or square brackets.
EXAMPLE 11
Find the number , name, and available credit for each customer with at least $ 5,000 of
available c redit.
You a lso cai1 use co1npi1ted columns in compa riso11s, as sho\\711 in Figi1re 4-16.
Home
SOL Workshop
@Aulocommit
SQL Commands
Rows
[20
Iv I V "1
( Save ) ( Run )
SELECT CUSJ O'VR_NUM, CUSIO">R_NME, CREDIT_LIMIT - BALANCE AS AVAII.AB:.E_CRS:DlT
fROM CUSIOMER
WHERE (CREDI!_LOO! - BALA}ICE) >= 5000 ;
Results
. L Hist
rb
I
126
Toys Galore
6289.75
260
Brookings Direct
9425
334
The Every1hing Shop
5154.25
386
Johnson's Department store
6620.75
586
Almondton General Store
11543.25
665
Cricket Gift Shop
6821.1
713
Cress store
5765.4
796
Unique Gifts
737525
824
Kline"s
12524.01
893
All Season Gifts
6564.25
10 rov,s returned in 0.00 seconds
FIGURE 4-16
Download
SELECT command with a computation in the cond ition
Using the LIKE Operator
l11 1nost cases, tl1e co11ditio11s ill \iVHERE c lai1ses i11volve exact 111atcl1es, si1cl1 as re trievil1g
rov.1s for each ci1s ton1er locate d in the ci ty of Grove. 111 so111e cases, l10\.\1ever , exact
1na tcl1es do 11ot worlt. F or exai11ple, yot.1 111ight lt110\.\' tl1at the desire d vali1e co11ta i11s 011ly a
certai11 collectio11 of c l1ar acter s. l11 si1c l1 cases, yot.1 t.1se tl1e Lll{E op er ator \.\1itl1 a wildcai·d
sy111bol, as sh o\.\111 ill Exa1nple 12. Ra tl1e r tl1an testi11g for e qua li ty , tl1e Lllffi op e ra to r u ses
011e or 111ore \.\1ildcard c l1a r acte rs to test fo r a p a tte rn 1na tcl1.
Single-Table Queries
EXAMPLE 12
List the number, name, and complete address of each customer located on a street tl1at
contains tl1e letters "Columbus."
All you lrno\\' is tl1at tl1e addresses you \\7ant contai11 a certain collection of characters
("Colu111bus") some\vl1ere in the STREET colu11111, but you do not kno\.\7 where. 111 SQL for
Oracle a11d for SQL Server, tl1e perce11t sign (%) is used as a wildcard to represent any
collection of cl1aracters. As sho\\7n in Figure 4-17, the co11dition Lll(E 1 %Colun1bus%1
retrieves iltlormation for each customer \.\7hose street contai11s so111e collectio11 of characters , followed by the lette rs "Columbus," followed pote11tially by some additional characters. Note that tllis query also \Vould retrieve inforn1atio11 for a customer \Vl1ose address is
"123 Columbusia" because "Colu111b11sia" also contai11s the letters "Colun1bus."
Home
SQL Workshop
0 Autocommil
SQL Commands
(20
Rows
' v I Q ,I/
( Save ) ( Run )
SEL=:CT cus: o..~R_?IDM, CUSTOME:R_NJI.ME, STREET, CITY, STAIE, POS'IAL_CODE
FROM CUSTOMER
l'IHL'E STREET LIKE '\Columbus\' ;+ - - - - - - - - - - - - - - - - - i
Results
r
p
n O c.r
S
W ildcard
symbols used
in condit ion
HI t ry
Brookings Direct
452 Columbus Or.
260
1 rows returned in 0.01 seconds
Download
Grove
CA
90092
Street contains
"Columbus"
FIGURE 4-17
SELECT command with a LIKE operator and wildcards
At1other "''ildcard symbol in SQL is tl1e u11derscore (_), \Vllich represe11ts a11y i11dividual cl1aracter. For example, "T_m" represe11ts tl1e le tte r "T" follo\ved by any single cl1aracter, followed by tl1e letter "m," a11d would retrieve ro\\'S tl1at include tl1e words Tim,
Tom, or T3n1.
ACCESS
USER
NOTE
Access uses different wildcard symbols. The symbol for any collection of characters is the asterisk (*),
as shown in Figure 4-18. The symbol for an individual character is the question mark (?).
SELECT CUSTOMER_ NUM , CUSTOMER_ NAME , STREET , CITY , STATE , POSTAL CODE
FROM CUSTOMER
! WHERE STREET LIKE ' *Columbus* ';
FIGURE 4-18
Access SELECT command with wildcards
Chapter 4
NOTE
In a large database, you should use wildcards only when absolutely necessary. Searches involving wildcards can be extremely slow to process.
Using the IN Operator
At1 IN clause, vvl1ic h con sists of tl1e IN ope ra tor follo\ved by a collectio11 of val11es , provides
a conc ise way of pl1rasi11g certain conditions , as Exan1ple 13 illustra tes. Yo u \Vill see
ano tl1e r u se for the IN cla use ill 1no re complex exa111ples la ter in this c h apte r .
EXAMPLE
13
List the number, name, and credit limit for each customer with a credit limit of $ 5,000,
s 10,ooo, or $15,000.
111 tl1is query, yott ca11 11se a11 IN cla use to de ter1nil1e \\rl1etl1er a c re dit li1nit is $ 5 ,000,
$ 10,000, o r $ 15,000. Yo11 co11ld obtail1 the sa1ne a11swer b y u si11g tl1e co11ditio11 vVHERE
CREDIT LIMIT= 5000 OR CREDIT LIMIT = 10000 OR C REDIT LIMIT= 15000. Tl1e
approach sl10\v11 i11 Fig11re 4-19 is sin1ple r beca11se tl1e IN c la11se co11tai11s a collectio11 of
val11es: 5000, 10000, a11d 15000. Tl1e conditio11 is true fo r tl1ose ro\VS i11 \Vl1icl1 tl1e value i11
tl1e C REDIT LIMIT col11m11 is i11 tl1is collectio11.
Home
SOL Workshop
!ilAutocommtt
Rows
SQL Commands
120
Iv IV I/
( Save )( Run )
SELEC: cos:oMER_ NUM, CUS!OMER_ NAME, CR£Dll_ LIMIT
FROM CUSTOMER
li<HEPZ CR£DIT_L.:Ml! IN ( 5000 , 10000, lSOOO) ; - - - - - - i
•
260
440
502
Brookings Direct
586
Almondton General Store
713
Cress store
10000
5000
5000
15000
10000
Kline's
15000
1 s24
Grove Historical Museum store
Cards and More
6 rows returned in 0.00 seconds
FIGURE 4-19
Down1oad
SELECT command w ith an IN clause
SORTING
Recall tl1at tl1e o rde r of rows i11 a table is il11m a te rial to tl1e DBMS. Fro1n a practical
sta11dpoi11t, tl1is 1nea11s tl1at \Vh e11 yo11 q11e ry a rela tio11a l data base, there is 110 de fi11ed
o rde r ill "' rl1ic l1 to display tl1e res11lts. Ro\,rs 111ight b e displayed i11 tl1e orde r i11 \\rl1ic l1 tl1e
da ta \\'as o rigit1ally e11te re d , b11t eve11 tl1is is 11ot certai11. If tl1e orde r i11 \\rl1ich the da ta is
displayed is impo rta11t, yo11 ca11 specifically r eq11est tl1at tl1e res11lts appear ill a desil·ed
o rde r . lt1 SQL, you specify tl1e res11lts orde r b y 11si11g tl1e ORDER BY c lau se.
Single-Table Queries
Using the ORDER BY Clause
You use tl1e ORDER BY clause to list data ill a specific o rder, as sl1own in Example 14.
EXAMPLE 14
List the number, name, and balance of each customer. Order (sort) the output in
ascending (increasing) order by balance.
Tl1e colt1m11 on \Vl1icl1 to sort data is called a sor t key or si1nply a key. In Exa1nple 14,
yot1 11eed to order tl1e ot1tpt1t by balance, so tl1e sort lcey is tl1e BALANC E colt1m11.
To sort tl1e 011tpt1t, t1se a11 ORDER BY clat1se followed by tl1e sort lcey. If yo11 do 11ot specify
a sort order , tl1e defat1lt is asce11dil1g. Tl1e q11ery appears ill Figt1re 4-20.
Home
SOL Wooo;hop
0Autocommil
Rows
SQL Commands
120
Iv I ~ ,?
( Save )( Run )
GSort key
0
SEU:C! CUSTOMER_NUM, CUSTOMER_NAME, BALANCE
fROM CUSTOMER
ORDER BY BALANCE ; •
Results
-
n
ISto
I
I
796
Unique Gifts
124.75
440
Grove Historical Museum Store
345
260
Brookings Direct
575
665
Clicl<el Gift Shop
678.9
386
Johnson's Department Store
879.25
893
All Season Gifts
935.75
126
Toys Galore
12~0.25
334
The Everything Shop
2345.75
824
Kline's
2475.99
586
Almondton General Store
3456.75
Cress store
4234.6
Cards and More
5025.75
713
502
12 rows returned in 0.01 seconds
FIGURE 4-20
Rows are sorted
in ascending order
by balance
Downloag
SELECT command to sort rows
Additional Sorting Options
Sometimes you might need to sort data usil1g m ore tha 11 one key, as s l10\\711 in Example 15.
EXAMPLE 15
List the number , name, and credit limit of each customer . Order the customers by name
within descending credit limit. (In other words, first sort the customers by c redit limit in
descending order. Within each group of customers that l1ave a common credit limit, sort
the customers by name in ascending order.)
Exa1nple 15 i11volves t\vo 11e\v ideas: sorting 011 mttltiple l{eys-CREDIT_LIMIT and
CUSTOMER_NAME-and sorting one of tl1e l{eys i11 desce11dil1g order . \\'11en you need to sort
Chapter 4
da ta on two col11mns, tl1e m ore important col11mn (in tllis case, CREDI'f_LINIIT) is calle d tl1e
major sort liey ( or the primary sort liey) and the less important col11mn (in tl1is case,
CUSTOMER_NAME) is called tl1e minor sor t liey (or tl1e secondru-y sort liey). To sort on n111ltiple lieys, yo11 list the lieys in order of importance in tl1e ORDER BY clause. To sort in descending
order , you follo\.v the 11ame of the sort liey witl1 the DESC operator , as sl10\,,n in Fig11re 4-21.
Home
SOL WorkshOP
0 Autocommit
Major sort key
Rows
SQL Commands
12° I'- I q I/
( Save )( Run )
SEL=:CT cus:<»E!I._NUM, CUS!OMER_!UI..M!':, CREDIT_LIMIT
FROM CUSfOMER
ORDER BY CREDI I_Lit1:T DESC, CUSTOMER_NAME; - - - - ~
Minor sort key
Results
Descending
order
!
Rows w ith the
same credit
limit are sorted
by name
586
Almondton General Store
15000
824
260
Kllne·s
Brookings Direct
15000
10000
713
Cress Store
10000
893
All Season Gifts
7500
665
Cricket Gflt Shop
7500
386
334
126
Johnson's Department Store
The Everything Shop
7500
7500
Toys Galore
7500
796
Unique Gifts
7500
502
Cards and More
5000
440
Grove Histoncal Museum Store
5000
12 rows returned in 0.01 seconds
FIGURE 4-21
Rows sorted in
descending order
by credit limit
Download
SELECT command to sort data using multiple sort keys
USING FUNCTIONS
SQL 11ses sp ecial f11nc tion s, calle d a.ggregate functions, to calc11late s11ms, averages,
co11nts, maximum vah..1es, and 1ninim111n val11es. Tl1ese ft1nc tions apply to groups of rows.
Tl1ey co11ld apply to all tl1e rows in a table (for e xainple, calc u lating tl1e average balance of
all cu stom e rs). Tl1ey also co11ld apply to tl1ose ro\\'S sa tisfying so1ne pa rtic11lar condition
(for example, tl1e average balance of all c11s ton1er s of sales r ep 30). The description s of tl1e
aggregate ft1nc tions appear in Fig11re 4-22.
FUNCTION
DESCRIPTION
AVG
Calculates tl1e average value in a column
COUNT
Determines the numbe r of rows in a table
11AX
Determines the maximum value in a colurru1
MIN
Determines the minimum value in a column
Sl.Thil
Calculates a to tal of the values in a column
FIGURE 4-22
SOL aggregate functions
Single-Table Queries
Using the COUNT Function
Tl1e COUNT f11nc tion, as illus trated in Example 16, cou11ts the number of ro\.\7S il1 a table.
EXAMPLE 16
How many items are in category G.fvIE?
For tllis q11ery, you 11eed to de te rmi11e the total numbe r of rovvs i11 tl1e ITEM table vvitl1
tl1e value GME i11 the CATEGORY col11mn. You could co11nt the item n11mber s i11 the
q11ery res11lts, or the 11umbe r of description s, or the numbe r of entries i11 any other colu11111. It d oes not matter wl1icl1 col111m1 you cl1oose because all col1111111s sl101tld provide the
same a11svver. Ratl1er tha11 arbitrarily selecti11g one col11mn, most SQL impleme11tation s le t
yo11 11se tl1e asteris k (*) to represent any column, as sh ovvn i11 Figure 4-23.
Home
SOL Workshop
0 Autocommit
Rows
SE:LEC:' COUNT(*l -
SQL Commands
[20
; v I V .tJ>
------------i
~
~
FROM IIE.M
WH£RE CATEGORY = ' GME'; ...
Results
....J
~
p I
( Save )( Run )
COUNT function
in SELECT clause
~onditi~
De
- - - - - - - - - - -
6- - - - - - - - - - - - - - - - - l
1 rows returned in 0.00 seconds
FIGURE 4-23
Download
Number of rows
in the ITEM table
on which the
category is GME
SELECT command to count rows
You also ca11 cou11t tl1e nu111ber of ro\.\7S i11 a query by selecting a sp ecific col11m11
instead of usrng tl1e aste risk, as follov\7s:
SEL E CT COUNT ( ITEM NUM)
FROM ITE M
WHERE CATEGORY = 1 GME 1 ;
Using the SUM Function
If you 11eed to calcu late tl1e total of all cus tom e rs ' bala11ces, you can use tl1e SUNI fu11ction ,
as illustrated il1 Exa111ple 17.
EXAMPLE 17
Find the total number of TAL Distributors customers and the total of their balances.
,\T11en yo11 11se the SUM f11nction, yo11 1nust specify tl1e col11mn to total, and the
col11mn 's data type must be n11meric. (How cou ld yo11 calc ula te a s11m of 11ames or
addresses?) Fig11re 4-24 sl1ovvs the que ry and the r esults.
Chapter 4
Home
SOL Workshop
~Autocommrt
Rows
SQL Commands
J20
Iv IV Q
( Save ) ( Run )
SELECT COONT(• ), SOM(BALANCE)
FROM CUSIOt-!ER;
tory
Results
22287 74
1 rows returned in 0.00 seconds
Download
SELECT command to count rows and calculate a total
FIGURE 4-24
Using the AVG, MAX, and MIN Functions
Using the AVG, NIAX, and NilN functions is shnilar to using SUM, except that different statistics
are calcttlated. A,ra calculates tl1e average valt1e in a numeric range, ~IA.X calculates the ma.'<imt1m valt1e in a nt1me ric range , and MIN calct1lates tl1e minimum valt1e in a numeric range.
EXAMPLE 18
Find the sum of all balances, the average balance, the maximum balance, and the minimum balance of all TAL Distributors customers.
Figt1re 4-25 shows tl1e qtiery a11d tl1e r est1lts.
Home
SQL Workshop
0 Autocommil
Rows
SQL Commands
(20
Iv IV Q
( Save )( Run )
S EECI SUM (R.l\.O~lCE) , AVG (B.I>.Lll.NCE) , !-ml< (BAIJI.NCE) , MIN ( R.~ICE)
FROM CUSTOMER;
Results
p
22287.74
Des
1857.31166666666666666666666666666666667
1 rows returned in 0.00 seconds
FIGURE 4-25
5025.75
124.75
Download
SELECT command with several functions
NOTE
When you use the SUM, AVG, MAX, or MIN functions, SOL ignores any null value(s) in the column and
eliminates them from the computations.
Null values in numeric columns can produce strange results when statistics are computed.
Suppose the BALANCE column accepts null values, there are currently four customers in the
CUSTOMER table, and their respective balances are $100, $200, $300, and null (unknown). When
you calculate the average balance, SOL ignores the null value and obtains a result of $200 (($100 +
$200 + $300) / 3). Similarly, when you calculate the total of the balances, SOL ignores the null value
and calculates a total of $600. When you count the number of customers in the table, however, SOL
includes the row containing the null value, and the result is 4. Thus, the total of the balances ($600)
divided by the number of customers (4) results in an average balance of $150!
Single-Table Queries
NOTE
You can use an AS clause with a function. For example, the following command computes a sum of the
BALANCE column and displays the column heading as TOTAL_BALANCE in the query results:
SEL E CT SUM ( BALANCE ) A S TOTAL BALANCE
FROM CUSTOMER ;
Using the DISTINCT Operator
In som e s itt.1ation s, tl1e DISTINCT operator is t.1seful when t.1sed in conjt.1nc tion \.\7 itl1 tl1e
COUNT fu11c tio n because it elimi11ates dt.1plicate vali1es in the qt.1e 1y results. Examples 19
a11d 2 0 illt.1s trate the m ost common t.1ses of tl1e DISTINCT operator .
EXAMPLE 19
Find the number of each customer that currently has an open order (that is, an order
currently in the ORDERS table) .
Tl1e co111111and seem s fairly simple. \V11en a ct.1stome r currently has ru1 open order ,
tl1ere mt.1s t be at least on e r ow in the ORDERS table on which that ct.1s tom e r's nt.1mber
appears. Yot.1 cot.1ld t.1se the qt.1e1y sh own in Figi1re 4-26 to fi11d tl1e ct.1s tom er nu1nbers
\Vitl1 open orders.
Home
SOL Workshop
0 Autocommit
Rows
SQL Commands
I" I V .fl
120
( Save )( Run )
-
SELECT COS'!OMER NUM
E"ROM ORDERS;
I
sa d S L
Results
126 -
----~
334
386
260
586 -
-----1
Customers 126 and
586 each have two
orders on fi le
126- - - - - - 1
586 _
_ _ _ _....,
796
8 rows returned in 0.01 seconds
FIGURE 4-26
Download
Numbers of customers with open orders
Chapter 4
Notice that cus tom er n11mbers 126 and 586 eacl1 appe ar mo re than on ce in the
res11lts ; this means tl1at both c11s tom ers c11rre11tly l1ave more tl1a11 011e open order in
tl1e ORDERS table. Suppose yo11 want to lis t each c11s tom er only once, as ill11strated in
Example 20.
EXAMPLE 20
Find the number of each customer that currently has an open order. List each customer
only once.
To en st1re 11niq11en ess, yo11 can 11se tl1e DISTINCT ope rato r, as sh o\.\'11 in Fig11re 4-2 7 .
Home
SOL Workshop
Ell Autocommil
Rows
SQL Commands
lvl V ~
120
( Save )( Run )
SEL~CT DI S:-INC: (:USTOMER Nm!)
fROM ORDE.'<S;
Results
-- --
saved s L History
rr:.. •1. ' .T"TI
•
386
260
334
126
586
I 796
,
6 rows returned in 0.01 seconds
FIGURE 4-27
!;!Qr,:[llQi!!l
Numbers of customers with open orders and with duplicates removed
You might ,vonde r abo11t tl1e relatio11ship between COUNT and DISTINCT, beca11se
bo th involve cou11ting rows. Example 2 1 identifies tl1e differen ces.
'
EXAMPLE 21
Count the number of customers that currently have open orders.
Tl1e que ry sl1own in Fig11re 4-28 co11nts tl1e n11mber of c11stom ers 11sing the
CUSTONIER NUM col11mn.
Single-Table Queries
Home
SOL Workshop
0 Autocommit
Rows
SQL Commands
V .{/
, .., 1
120
( Save )( Run )
SEL£CT COUNT {COSTOMER_NUM)
fROM ORDE.'tS;
Results
saved s · L
s
fl
1 rows returned i n 0.00 seconds
FIGURE 4-28
Hr t ry
Oownload
Count that includes duplicate customer numbers
Question: \\That is \.Vrong with the query results shown in Figure 4-28?
Answer: The answer , 8, is the result of cou11ting the custome rs that have open orde rs
multiple times-once for each separate order currently on file. The result counts each
customer number and does not eliminate duplicate customer numbers to provide an
accurate count of the number of customers.
Some SQL implementa tions, incl11ding Oracle and SQL Server (bt1t not Access), allo\.v
yo11 to 11se the DISTINCT operator to calc11late tl1e correct co11nt, as sho\vn in Fig11re 4- 29.
Home
SOL Workshop
0 Autocommit
Rows
SQL Commands
j20
, ..,
I V .{/
( Save )( Run )
SELECT COUITT{D: STINC: (CUSIO~ NUM))
fROM ORDERS;
Results
6
1 rows returned in 0.00 seconds
FIGURE 4-29
Download
Count that excludes duplicate customer numbers (using DISTINCT within COUNT)
NESTING QUERIES
Some times obtaining tl1e res11lts yo11 need req11ires t\.v o or more steps, as shown in tl1e
next two examples.
EXAMPLE 22
List the number of each item in category PZL.
Chapter 4
Tl1e com1na11d to obta in the m1swer and tl1e r est1lts are sl1ovv11 il1 Figt1re 4-3 0 .
Home
SOL Workshop
El!Autocommil
Rows
SQL Commands
1--1v .f
120
( Save ) ( Run )
-
SELECT II!.M NUM
fROM ITEM
WHERE CATEGORY a
Results
p
~
'
PZL' ;
-~
..
savea SQL
History
~
OR67
FH24
1<034
MT03
4 rows returned in 0.00 seconds
!;!Qwn1os1!1
Selecting all items in category PZL
FIGURE 4-30
EXAMPLE 23
List the order numbers that contain an order line for an item in category PZL.
Exmnple 23 aslu; yot1 to find the order 11t1mbers in the ORDER_LINE table tha t correspond
to the item ntrmbe rs in tl1e rest1lts of the qt1ery t1sed in Example 22. After viewi11g tl1ose
rest1lts (DR67, FH24, Iill34, and N1T03), yoi1 can t1se tl1e co1nmat1d shov.m il1 Figt1re 4-3 1.
I Home SOL Workshop SQL Commands
Ell Autocommit
Rows
(20
l--lV .f
( Save )( Run )
SELECT ORDER NUM
--
fROM ORDER LINE
.
WHER5: ITEM NUM IN ( 'DR67 ' ,
Results
.
.
'FH24'
'
5.JedSL
'KD34', 'MT03') ;
~
,story
-
I
51623
I
Results from
previous query
)
51623
51623
51625
4 rows returned in 0.01 seconds
FIGURE 4-31
Download
Query using the results from Figure 4-30
Subqueries
It is p ossible to place 011e qt1e ry i11side a11o tl1er . Tl1e i1me r qt1er y is called a subquery. Tl1e
st1bqt1e ry is evaluated firs t. Afte r tl1e st1bqt1er y l1as bee11 evalt1ate d , tl1e ot1te r qt1e ry ca11
use tl1e rest1lts of tl1e st1bqt1e ry to fil1d its results, as sl1ov\'ll i11 Exan1ple 24.
Single-Table Queries
EXAMPLE 24
Find the answer to Examples 22 and 23 in one step.
Yot1 can find tl1e same rest1lt as in the previou s t\vo examples in a single step by tising a
s11bqt1e ry. 111 Figt1re 4-32, the com111and sl10\V11 in p arentheses is the st1bqt1ery. Tllis st1bquery is
evaluated first, prodt1cing a temporary table. The temporary table is used only to evalt1ate the
qt1ery-it is not available to tl1e tiser or displayed-and it is dele ted after the evalt1a tio11 of tl1e
qt1ery is comple te. 111 tllis example, the te1nporary table l1as only a single column (ITEM_NUNI)
and fot1r ro,vs (DR6 7, FH24, Iill34, and MT03). The ot1ter qt1e ry is evaltiated next. In this case,
tl1e ot1ter qt1ery retrieves the orde r 11t1mber 011 every ro\,, iI1 the ORDER_LINE table for ,vhicl1
tl1e item number is in the results of the subqt1e1y. Becat1se tha t table contaiI1s ortly tlle item
11umbers in category PZL, the results display tl1e desiI·ed list of order nt1mbers.
Home
SQL Workshop
E21 Autocommit
SOL Commands
Rows
I" I V ~
120
( Save )( Run )
(§IN
-
SEU:C! ORDER NUM
FROM ORDER LINE
(SELECT :ITM_NUM
V
opera\or
Wfil:RE ITEM- tnJM IN -4-C- - - - - - - - - - <
_
_
E'ROM ITEM
WHERE CJUEGORY s 'PZ.:,'J;
Subquery to find
item numbers for items
in category PZL
Results
51623
51623
51623
51625
4 rows returned in 0.05 seconds
FIGURE 4-32
Download
Using the IN operator and a subquery
Figt1re 4-32 sh o\,rs dt1plicate o rder nt1mbe rs in the resttlts. To elimi11ate this dt1plication, yot1 ca11 t1se the DISTINCT op er a tor as follows:
S EL E CT DISTINCT (ORDER NUM)
FROM ORDER LINE
WHERE ITEM NUM IN
(SE LE CT ITEM NUM
FROM ITEM
WHERE CATEGORY
= PZL
1
1
) ;
Tl1e r est1lts of this qt1ery will display each orde r 11umber 011ly 011ce.
EXAMPLE 25
List the 11umber, name, and balance for each customer whose balance exceeds the average balance of all customers.
Chapter 4
l11 tl1is case, you 11se a st1bq11ery to obtain the average balance. Beca11se tl1e subqt1ery
prodt1ces a single n11mber (tl1e average balance of all c11s tom e rs), eacl1 individt1al
ct1stomer's balance is co1npared to tl1is nt1mber , and tl1e rov,, fo r a c11stom e r is selected
\\rl1en the ct1stomer 's bala11ce is greater than the average balance. The qt1er y and its
res11lts are sl1ovvn in Figure 4-33.
Home
SOL Workshop
Rows
0Autocommil
SQL Commands
lvlV..?
120
( Save ) ( Run )
SEEC! COS:OMER_NUM, CUSTOME:R_N11.ME, BALA.~CE
FROM CUSTOMER
WHERE BALANCE >
( SELECT Pa.VG ( BALANCE)
FROM CUSTOMER);
Results
Des
"
-~vcd - L Hist rv
-
• ",1:=:1•.11~
334
The Everything Shop
2345.75
502
Cards and More
5025.75
586
Almondton General Store
3456.75
713
Cress Store
4234.6
824
Kfine's
2475.99
5 rows returned in 0.01 seconds
FIGURE 4-33
Download
Query using an operator and a subquery
NOTE
You cannot use the condition BALANCE > AVG(BALANCE) in the WHERE clause; you must use a
subquery to obtain the average balance. Then you can use the results of the subquery in a condition,
as illustrated in Figure 4-33.
GROUPING
Grouping creates groups of rO\\'S that share some commo11 charac te 1istic. If yo11 grot1p
ct1stom ers by credit li1nit, fo r example, the firs t grot1p co11tains ct1stomers vvith $ 5 ,000
credit lilnits, tl1e second group conta ins cus to1ners ,vith $ 7,500 cr edit lilnits, and so on .
If, on the otl1er l1and, you grot1p c11s to1ners by sales r ep 11umber, the first grot1p co11tains
tl1ose c11sto1ners r epresented by sales r ep 1111mbe r 15 , the second grot1p contains those
ct1stom ers represented by sales rep 1111mbe r 3 0, and tl1e tllird gro11p contains tl1ose
customers represe11ted by sales rep 1111mbe r 45 .
,\T11en yo11 grot1p rov\'S, any calculatio11s i11dicated in tl1e SELECT comma11d are
performed for the e11tire gr oup. For example, if yo11 grot1p c11s tom ers by r ep n11mber and
tl1e query requests the average balance, tl1e r esults i11clude tl1e average balance for the
grot1p of custo1ners represented by rep n11mber 15, tl1e average balance for tl1e grot1p
represented b y rep n11mbe r 30 , a11d the average balance for tl1e gr ot1p represe11ted by
rep n11mber 45. Tl1e follo\\ri11g examples illustrate tllis process.
Single-Table Queries
Using the GROUP BY Clause
Tl1e GROUP BY clause lets you group data on a particular colu11111 , sucl1 as REP_NlTh1, and
tl1en calculate statistics, when desired, as sl1ow11 in Example 26.
EXAMPLE 26
For each sales rep, list the rep number and the average balance of the rep's customers.
Becat.1se you need to group customers by rep nt.11nber and tl1e11 calculate tl1e average
bala11ce for all ct.1stomers in eacl1 grot.1p, yot.1 mt.1st use the GROUP BY clause. In tllis case,
GROUP BY REP_NUM puts customers witl1 tl1e same rep nt.11nber into separate grot.1ps.
1\11y s tatistics indicated in the SELECT command are calct.1lated for eacl1 grot.1p. It is
importa11t to 11ote tl1at tl1e GROUP BY clat.1se does not sort the data in a partict.1lar order;
yot.1 must t.1se tl1e ORDER BY clat.1se to sort data. Asst.1ming tl1at the rest.tlts shot.tld be
ordered by rep 11umber, yot.1 can use tl1e command sl1own i11 Figure 4-34.
Home
SOL Workshop
E2l Autocommit
Rows
SQL Commands
1-- 1~ ~
120
( Save )( Run )
SEECT REP_NUM, AVG(BALANCE)
fROM CUSTOMER
GROUP BY REP NUM
ORDER BY ru:P_NOM;
-
Results
:pJa1n
·-
savea Sul History
•
• i
••
15
2851.5875
30
1152.285
45
1568.0625
'
3 rows returned in 0.00 seconds
FIGURE 4-34
One row for
each group
l
Download
Grouping records on a column
,,Then rows are grot.1ped, one line of output is prodt.1ced for eacl1 group. The 011ly
tl1i11gs that cai1 be displayed are statistics calculated for the group or colum11s "''hose
values are tl1e saine for all ro\.VS i11 a group.
Question: Is it appropriate to displa.y the rep number in the query for Example 26?
Answer: Yes, because the rep number in one row in a group must be the same as the rep
number in any other ro,v in the group.
Chapter 4
Question: Would it be appropriate to display a customer number in the query for
Example 26?
Ans,ver: No, because the customer number varies on the rows in a group. (The same rep
is associated with many customers.) The DBMS would not be a.h ie to determine \Vhich
customer number to display for the group, and would display an error message if you
attempt to display a customer number.
Using a HAVING Clause
Tl1e I-IAVING clat1se is t1sed to restrict the groups that are inclt1ded, as sho\vn in
Example 27.
EXAMPLE 27
Repeat the previous example, but list only those reps whose customers have an average
balance greater than $1,500.
Tl1e only difference betwee11 Examples 26 ru1d 27 is the restriction to display only
tl1ose reps "''hose customers have a11 average balance greater than $ 1 ,500. Tllis restriction
does not apply to individual rows bt1t ratl1er to groups . Because tl1e ,\TI-IERE clat1se applies
only to rO\\'S, yot1 caru1ot t1se it to accomplish the lrind of selection that is reqt1ired. Fortt111ately, tl1e HA,rrna clat1se does for grot1ps \\rl1at the WHERE clat1se does for rO\\'S. The
I-IA,TJNG clause linlits the grot1ps that are inclt1ded iI1 tl1e results. In Figt1re 4-35, tl1e rO\\'
created for a grot1p is displayed only vvhe11 tl1e average balance for the rows in the grot1p is
greater tl1an $ 1,500.
Home
SOL Workshop
EZI Autocommil
Rows
SQL Commands
120
j .., I V .(?
( Save )( Run )
SEL!CT REP_NUM, AVG(BALANCE)
fROM CUSTOMER
GROUP BY REP NUM
H..ItVING AVG(H..ll.LA..i;CE)
> 1 500 - - - - - - - - - - - l
ORDER BY REP_NUH;
On ly groups with
an average balance
greater than $1,500
are included
Results
15
2851.5875
45
1568.0625
2 rows returned in O.01 seconds
FIGURE 4-35
Download
Restricting the groups to include in the results
Single-Table Queries
HAVING vs. WHERE
Just as you ca11 use the \~THERE clause to liJ11i t the rows that are iI1cluded m a query's
result, you ca11 use the HA\TING clause to liI11it tl1e groups that are iI1cluded. Tl1e follo,,,mg
examples illustrate the differe11ce betwee11 tl1ese t\.vo clauses.
EXAMPLE 28
List each credit limit and the number of customers having each credit limit.
To count tl1e number of ct.1stomers that l1ave a give11 credit limit, you mt.1st grot.1p tl1e
data by credit limit, as sho,vn i11 Figt.1re 4-36.
Home
SQL Workshop
0 Autocommit
Rows
SQL Commands
1--,v~
120
( Save )( Run )
SELECT CBLDIT_LIMIT, COUNT(*)
fROM CUSIOMER
GROUP BY CREDit LIMI:
ORDER BY cru:orr_LIMI:;
-
Results
p&mn
·-
Saved Sul
Des
lf<T"i
History
'JJ.t'J
5000
2
7500
10000
6
15000
2
2
14row s returned i n 0.00 seconds
FIGURE 4-36
Download
Counting the number of rows in each group
EXAMPLE 29
Repeat Example 28, but list only those credit limi ts held by more than two customers.
Becat.1se tl1is condition involves a grot.1p total, the qi1ery inclt.1des a HAVING clat.1se, as
sl10,v11 in Figi1re 4-3 7.
Home
SOL Workshop
0 Autocommit
Rows
SQL Commands
120
1-- IV ~
( Save )( Run )
SELECT CREDIT_LIMII, COUNT(*)
fROM CUSIOHER
GROIJP BY CREDir Ln-!Ir
HAVING COONi(*) > 2
ORDErt BY CREDit_LIMIT;
-
Results
7500
6
1 rows r eturned in 0.01 seconds
FIGURE 4-37
Download
Displaying groups that contain more than two rows
Chapter 4
EXAMPLE 30
List each credit limit and the number of customers of sales rep 15 that have this limit.
Tl1e condition i11volves only ro\vs, so 11sing the \\THERE cla11se is appropriate, as sl1own
in Fig11re 4 -38.
Home
SOL Workshop
EZI Aulocommit
SQL Commands
1-- I V .{/
(20
Rows
( Save ~( Run )
SELECT CREDIT_ LIMIT, COUN! ( *)
FROM CUSTOMER
WHERE REP N1lM = ' 15 - - - - - - - - - - - - - - - - - ,
;;ROUP BY CREDir_LH1I:
ORDER BY CREDII_LIMI: ;
Results
r
5000
1
7500
10000
2
On ly rows on
which the rep number
is 15 are included
in the groups
1
Download
3 rows returned in 0.01 seconds
FIGURE 4-38
Restricting the rows to be grouped
EXAMPLE 31
Repeat Example 30, but list only those credit limits h eld by fewer than two customers.
Beca11se the conditions involve rows a11d groups, you 1nust 11se both a \\THERE cla11se
and a HA\TING clause, as sl10\vn in Fig11re 4-39.
I Home
SOL Workshop
Ell Autocomrnit
SQL Commands
(20
Rows
i"tv .r?
(_ Save )( Run )
SEL~CT CREDIT_ LIMII, COUNT ( *)
rROM CUSTOMER
@l:ERE REP mJM = ' 15'
GROUP BY CREDIT LIMIT
, li.~VING COU!U{* ) < 2
ORDER BY CREDIT_LIMI!;
-
Results
,............
l l l~I
5000
10000
00~
Suved SOL
HI t ry
,.,,•• .• \t'!J
1
1
2 rows returned in 0.01 seconds
FIGURE 4-39
Download
Restricting the rows and the groups
Single-Table Queries
In Example 3 1, rovvs from tl1e original table are evaluated 011ly when the sales rep
n11mber is 15. Tl1ese r o\\rs tl1en are gro11ped by credit llinit and the co11nt is calculated.
Only gro11ps for \Vhicl1 tl1e calculated count is less tl1an two are displayed.
NULLS
Sometimes a condition involves a column that can accept null val11es, as ill11s trated in
Example 32.
EXAMPLE 32
List the numbe r and name of each customer with a null (unknown) street value .
You migl1t expect tl1e condition to be something lille STREET = NULL. Tl1e correct
format act11ally 11ses the IS NULL operator (STREET IS NULL), as sl1ovv11 in Fig11re 4-40.
To select a c11stomer vvl1ose s treet is no t n11ll, 11se the IS NOT NULL operator (S'f REET IS
NOT NULL). In tl1e c11rrent TAL Distributors database, no c11s tomer l1as a nitll street
val11e; the refore, no rows are retrieved in the q11ery res11lts.
Home
SOL Workshop
E2l Autocommit
Rows
SQL Commands
120
lvl V .f
( Save )( Run )
-
SELECT CCJSI~_NOM, CUSTOMER NAME
fROM CUSTOMER
WH.ERE STREET IS NULL;
Resu lts
:01111n
uescnbe Saved Sul History
no data found
FIGURE 4-40
Selecting rows containing null values in the STREET column
SUMMARY OF SQL CLAUSES, FUNCTIONS, AND OPERATORS
In tl1is ch apte r, you lea rned how to create q11eries tl1at re trieve data from a single table by
cons truc ting appropriate SELECT commands. In the 11ext chapte r, yo11 will learn l1ow to
create que ries tl1at re trieve data fr om mitltiple tables. Tl1e queries yo11 created in tl1is
cl1apter used the cla11ses, f11nc tions, a11d oper ators sl1ovvn iI1 Fig11re 4-41.
Chapter 4
CLAUSE OR OPERATOR
DESCRIPTION
AND operator
Specifies that all simple conditions must be true for the con1pound
condition to be trt1e
BET,VEEN operator
Specifies a range of values in a condition
DESC operator
Sorts the query results in descending order based on the column name
DISTINCT operator
Ensures uniqueness in the condition by eliminating duplicate values
FR011 clause
Indicates the table from \Vhich to retrieve the specified columns
GROUP BY clause
Groups rows based on the specified column
I-IAVING clat1se
Linrits a condition to tl1e groups tl1at are included
IN operator
Finds a value in a group of values specified in the condition
IS NOT NULL operator
Finds ro\VS tha t do not conta in a null value in the specified column
IS NULL operator
Finds rows that contain a null value in the specified column
LIKE operator
Indicates a pattern of cl1aracters to find in a condition
NOT operator
Reverses the result of the original condition
OR operator
Specifies tl1at tl1e compound condition is trt1e whenever any of tl1e simple
conditions is true
ORDER BY clause
Lists the query results in the specified order based on the column name
SELECT clause
Specifies the columns to retrieve in the query
WHERE clause
Specifies any conditions for the query
FIGURE 4-41
SOL query clauses and operators
Single-Table Queries
Chapter Summary
•
The basic form of the SOL SELECT command is SELECT-FROM-WHERE.
Specify the columns to be listed after the word SELECT (or type an asterisk [*] to
select all columns), and then specify the table name that contains these columns
after the word FROM. Optionally, you can include one or more conditions after the
word WHERE.
•
Simple conditions are written in the following form: column name, comparison operator, column name or value. Simple conditions can involve any of the comparison
operators: =, >, >=, <, <=, or < >.
•
You can form compound conditions by combining simple conditions using the AND,
OR, and NOT operators.
•
Use the BETWEEN operator to indicate a range of values in a condition.
•
Use computed columns in SOL commands by using arithmetic operators and
writing the computation in place of a column name. You can assign a name to
the computed column by following the computation with the word AS and then
the desired name.
•
To check for a value in a character column that is similar to a particular string of
characters, use the LIKE operator. In Oracle and SOL Server, the percent (%)
wildcard represents any collection of characters, and the underscore ( _ ) wildcard
represents any single character. In Access, the asterisk (*) wildcard represents
any collection of characters, and the question mark (?) wildcard represents any
single character.
•
To determine whether a column contains a value in a set of values, use the IN
operator.
•
Use an ORDER BY clause to sort data. List sort keys in order of importance. To sort
in descending order, follow the sort key with the DESC operator.
•
SOL processes the aggregate functions COUNT, SUM, AVG, MAX, and MIN. These
calculations apply to groups of rows.
•
To avoid duplicates in a query that uses an aggregate function, precede the column
name with the DISTINCT operator.
•
When one SOL query is placed inside another, it is called a subquery. The inner
query (the subquery) is evaluated first.
•
Use a GROUP BY clause to group data.
•
Use a HAVING clause to restrict the output to certain groups.
•
Use the IS NULL operator in a WHERE clause to find rows containing a null value in a
particular column. Use the IS NOT NULL operator in a WHERE clause to find rows
that do not contain a null value.
Chapter 4
Key Terms
aggregate functions
major sort key
AND
MAX
AND condition
MIN
AVG
minor sort key
BETWEEN
NOT
compound condition
NOT condition
computed column
OR
COUNT
DESC
OR condition
ORDER BY clause
DISTINCT
primary sort key
FROM clause
query
GROUP BY clause
secondary sort key
.
grouping
SELECT clause
HAVING clause
simple condition
IN clause
sort key
IS NOT NULL
subquery
IS NULL
SUM
key
WHERE clause
LIKE
Review Questions
1. Describe the basic form of the SOL SELECT command.
2. How do you form a simple condition?
3. How do you form a compound condition?
4. In SOL, which operator do you use to determine whether a value is between two other
values without using an AND condition?
5. How do you use a computed column in SOL? How do you name the computed column?
6. In which clause would you use a wildcard in a condition?
7. What wildcards are available in Oracle, and what do they represent?
8. How do you determine whether a column contains one of a particular set of values without
using an AND condition?
9. How do you sort data?
10. How do you sort data on more than one sort key? What is the more important key called?
What is the le-ss important key called?
11 . How do you sort data in descending order?
Single-Table Queries
12. What are the SOL aggregate functions?
13. How do you avoid including duplicate values in a query's results?
14. What is a subquery?
15. How do you group data in an SOL query?
16. When grouping data in a query, how do you restrict the output to only those groups satisfying some condition?
17. How do you find rows in which a particular column contains a null value?
C RITICAL
THINKING
18. Use the Internet to research the SOL [charlist] wildcard that is available in Oracle and SOL
Server. Using the information you find, complete the following SOL command to find all cities that begin with the letters "C" or "G."
SEL E CT CUSTOMER NAME , CITY
FROM CUSTOMER
WHERE CITY LIKE
Be sure to cite the URL(s) that provided the information.
Exercises
T AL Distributors
Use SOL and the TAL Distributors database (see Figure 1-2 in Chapter 1) to complete the
following exercises. If directed to do so by your instructor, use the information provided with
the Chapter 3 Exercises to print your output or save it to a document.
1. List the item number, description, and price for all items.
2. List all rows and columns for the complete ORDERS table.
3. List the names of customers with credit limits of $10,000 or more.
4. List the order number for each order placed by customer number 126 on 10/15/2015.
(Hint: It you need help, use the discussion of the DATE data type in Figure 3-16 in
Chapter 3.)
5. List the number and name of each customer represented by sales rep 30 or sales rep 45.
6. List the item number and description of each item that is not in category PZL.
7. List the item number, description, and number of units on hand for each item that has
between 20 and 40 units on hand, including both 20 and 40. Do this two ways.
8. List the item number, description, and on-hand value (units on hand* unit price) of each
item in category TOY. (On-hand value is really units on hand * cost, but there is no COST
column in the ITEM table.) Assign the name ON_HAND_VALUE to the computed column.
9. List the item number, description, and on-hand value for each item whose on-hand value
is at least $1 ,500. Assign the name ON_HAND_VALUE to the computed column.
10. Use the IN operator to list the item number and description of each item in category GME
or PZL.
Chapter 4
11 . Find the number and name of each customer whose name begins with the letter "C."
12. List all details about all items. Order the output by description.
13. List all details about all items. Order the output by item number within storehouse. (That
is, order the output by storehouse and then by item number.)
14. How many customers have balances that are more than their credit limits?
15. Find the total of the balances for all customers represented by sales rep 15 with balances
that are less than their credit limits.
16. List the item number, description, and on-hand value of each item whose number of units
on hand is more than the average number of units on hand for all items. (Hint: Use a
subquery.)
17. What is the price of the least expensive item in the database?
18. What is the item number, description, and price of the least expensive item in the database? (Hint: Use a subquery.)
19. List the sum of the balances of all customers for each sales rep. Order and group the
results by sales rep number.
20. List the sum of the balances of all customers for each sales rep, but restrict the output to those
sales reps for which the sum is more than $5,000. Order the results by sales rep number.
21 . List the item number of any item with an unknown description.
CRITICAL
THINKING
C RITICAL
THINKING
22. List the item number and description of all items that are in the PZL or TOY category and
contain the word "Set'' in the description.
23. TAL Distributors is considering discounting the price of all items by 10 percent. List the
item number, description, and discounted price for all items. Use DISCOUNTED_PRICE
as the name for the computed column.
Colonial Adventure Tours
Use SOL and the Colonial Adventure Tours database (Figures 1-4 through 1-8 in Chapter 1) to
complete the following exercises. If directed to do so by your instructor, use the information
provided with the Chapter 3 Exercises to print your output or save it to a document.
1. List the last name of each guide that does not live in Massachusetts (MA).
2. List the trip name of each trip that has the type Biking.
3. List the trip name of each trip that has the season Summer.
4. List the trip name of each trip that has the type Hiking and that has a distance longer than
1O miles.
5. List the customer number, customer last name, and customer first name of each customer
that lives in New Jersey (NJ), New York (NY) or Pennsylvania (PA). Use the IN operator
in your command.
6. Repeat Exercise 5 and sort the records by state in descending order and then by customer last name in ascending order.
7. How many trips are in the states of Maine (ME) or Massachusetts (MA)?
Single-Table Queries
8. How many trips originate in each state?
9. How many reservations include a trip price that is greater than $20 but less than $75?
10. How many trips of each type are there?
11 . Colonial Adventure Tours calculates the total price of a trip by adding the trip price plus
other fees and multiplying the result by the number of persons included in the reservation.
List the reservation ID, trip ID, customer number, and total price for all reservations where
the number of persons is greater than four. Use the column name TOTAL_PRICE for the
calculated field.
12. Find the name of each trip containing the word "Pond."
13. List the guide's last name and guide's first name for all guides that were hired before
June 10, 2013.
14. What is the average distance and the average maximum group size for each type of trip?
15. Display the different seasons in which trips are offered. List each season only once.
16. List the reservation IDs for reservations that are for a paddling trip. (Hint: Use a subquery.)
17. What is the longest distance for a biking trip?
18. For each trip in the RESERVATION table that has more than one reservation, group by
trip ID and sum the trip price. (Hint: Use the COUNT function and a HAVING clause.)
19. How many current reservations does Colonial Adventure Tours have and what is the total
number of persons for all reservations?
C RITICAL
THINKING
20. List the reservation ID and trip ID for all trips that occur in the month of July, 2016. There
are multiple ways to create this query. Write an alternate command that would produce
the same result.
Solmaris Condominium Group
Use SOL and the Solmaris Condominium Group database (Figures 1-9 through 1-13 in Chapter 1)
to complete the following exercises. If directed to do so by your instructor, use the information
provided with the Chapter 3 Exercises to print your output or save it to a document.
1. List the owner number, last name, and first name of every condo owner.
2. List the complete LOCATION table (all rows and all columns).
3. List the last name and first name of every owner who lives in Bowton.
4. List the last name and first name of every owner who does not live in Bowton.
5. List the location number and unit number for every condo whose square footage is equal
to or less than 1,200 square feet.
6. List the location number and unit number for every condo with three bedrooms.
7. List the unit number for every condo with two bedrooms that is located in location number 2.
8. List the condo ID for every condo with a condo fee that is between $550 and $650.
9. List the unit number for every condo in location number 1 whose condo fee is less than $500.
Chapter 4
10. Labor is billed at the rate of $35 per hour. List the condo ID, category number, estimated
hours, and estimated labor cost for every service request. To obtain the estimated labor
cost, multiply the estimated hours by 35. Use the column name ESTIMATED_COST for
the estimated labor cost.
11 . List the owner number and last name for all owners who live in Florida (FL), Georgia
(GA), or South Carolina (SC).
12. List the location number, unit number, square footage, and condo fee for all units. Sort the
results by condo fee within the square footage.
13. How many one-bedroom condos are located at each location?
14. Calculate the total condo fees Solmaris receives each month.
C RITICAL
THINKING
C RITICAL
TH INKING
15. There are two ways to create the query in Step 11 . Write the SOL command that you
used and then write the alternate command that also would obtain the correct result.
16. What WHERE clause would you use to find all service requests with the word "pantry"
anywhere in the Description field?
C H A PTER
MULTIPLE-TABLE
UERIES
OBJECTIVES
•
Use joins to retrieve data from more than one table
•
Use the IN and EXIST S operators to query multiple tables
•
Use a subquery within a subq uery
•
Use an alias
•
Join a table to itself
•
Perform set operations (union, intersection, and difference)
•
Use the ALL and ANY operators in a query
•
Perform special operations (inner join, outer join, and prod uct)
INTRODUCTION
In this chapter, you will learn how to use SOL to retrieve data from two or more tables using one SOL
command. You will join tables together and examine how to obtain similar results using the SOL IN
and EXIST S operators. Then you will use aliases to simplify queries and join a table to itself. You
also will implement the set operations of union, intersection, and difference using SOL commands.
You will examine two related SOL operators: ALL and ANY. Finally, you will perform inner joins,
outer joins, and products.
QUERYING MULTIPLE TABLES
In Cl1apter 4, you learned l1ow to retrieve d ata from a single table. Many q1.1e ries require
yo1.1 to retrieve data from two o r m ore ta bles. To r etrieve da ta from m1.1ltiple ta bles, yo1.1
first m1.1st jo in tl1e ta bles, and tl1en form1.1late a q1.1ery 1.1sing the sam e com1nands tl1at yo1.1
1.1se fo r single -ta ble q1.1e ries.
NOTE
In the following queries, your results might contain the same rows, but they might be listed in a different
order. If order is important, you can include an ORDER BY clause in the query to ensure that the results
are listed in the desired order.
Chapter 5
Joining Two Tables
To retrieve data from more tl1a11 one table, you must join tl1e tables together by findi11g
rovvs in the two tables tl1at l1ave identical values i11 111atcl1ing colu11111s. You can joi11 tables
by using a co11ditio11 in the \VHERE clause, as you v\Till see in Example 1.
EXAMPLE 1
List the number and name of each customer, toge ther with the number, last name, and
first name of the sales rep who represents the customer.
Becai1se the ci1stomer 111.1mbers a11d 11ames are in tl1e CUSTOMER table and tl1e sales
rep nu111bers and names are in the REP table , you need to incli1de both tables in tl1e SQL
co1111nand so you can retrieve data fro111 both tables. To joi11 (relate) tl1e tables , yoi1 constri1ct tl1e SQL co111mand as follows:
1.
2.
3.
111 tl1e SELECT clai1se, list all colum11s you wa11t to display.
111 tl1e FROM clai1se, list all tables i11volved i11 tl1e qi1ery.
111 tl1e \\THERE clause, list the condition that restricts the data to be retrieved
to only tl1ose rO\\TS from tl1e tvvo tables tl1at match; tl1at is, restrict it to the
rO\\TS tl1at l1ave co1nmon valt1es in 1natcl1i11g columns.
As you learned i11 Cl1apter 2, it is often necessary to qi1alify a coli11nn na1ne to specify
tl1e partict1lar coli111111 you are refere11cing. Qualifyi11g coli111111 11ames is especially ilnportant when joi11i11g tables because yoi1 1nust join tables on matcliing coli111111s that freqi1ently have identical column 11ames. To qi1alify a column name, precede tl1e name of tl1e
coli1mn v\Tith tl1e name of tl1e table, followed by a pe1iod. Tl1e matclling colu11111s in tl1is
example are both 11amed REP_NONI-tl1ere is a column i11 tl1e REP table named REP_NUNI
and a colunn1 in tl1e CUSTONIER table tl1at also is named REP- NONI. Tl1e REP- NUM
coli1mn in the REP table is written as REP.REP- NONI and tl1e REP- NONI colu11111 i11 tl1e
CUSTONIER table is v\Tritten as CUSTOMER.REP_NUM. Tl1e qi1ery and its results appear
in Figure 5-1.
Multiple-Table Queries
ORACLE Appl ication Express
Honie
Home
Application Bu1kler ...
SOL Workshop
b21Al.ltocommit
Rows
. Team Development ..-,
SQL Commands
1.., IV ./l
J20
( Save ) ( Run )
SELECT CUS!OMER_NUM, CUS!OMER_NAME, REP . REP_ NOM, LAST_NJlME, FIRST NAME
FROM CUSTOMER, RE P
!E CUSTOMER . RE P_NiJM ~ REP .REP_NUM; -~
Condition to
Suved S
Results
relate t he tables
H story
126
Toys Galore
15
Campos
Rafael
502
713
Cards and More
15
Campos
Rafael
Cress Store
15
Campos
Rafael
893
All Season Gifts
15
Campos
Rafael
665
824
Cnckel Gift Shop
30
Gradey
Megan
Kline's
30
Gradey
Megan
386
260
440
Johnson's Department Store
30
30
Gradey
Megan
Gradey
Megan
Tian
Hui
796
Unique Gifts
45
45
nan
Hui
586
Almondton General Store
45
nan
Hui
334
The Everything Shop
45
nan
Hui
Brookmgs Direct
Grove Historical Museum Store
12 rows returned in 0.01 seconds
FIGURE 5-1
Download
Joining two tables with a single SOL command
\\Tl1en tl1ere is potential ambiguity in listing column names , you must qttalify tl1e col1.111111s involved in the qt1ery. It is permissible to qt1alify otl1er colt1m11s as well, even vvl1e11
tl1ere is no possible co11ft1sion. Some people prefer to qt1alify all colt1nu1 names; il1 this
text, l1owever, yott will qt1alify colu11111 names 011ly .,,,,l1en necessary.
Question: In the first row of output iI1 Figure 5-1, the customer number is 126, and the customer name is Toys Galore. These values represent the first row of the CUSTOMER table. Why
is the sales rep number 15, the last name of the sales rep Campos, and the first name Rafael?
Answer: In the CUSTOMER table, the sales rep number for customer number 126 is 15.
(This indicates that customer number 126 is related to sales rep number 15.) In the REP
table, the last name of sales rep number 15 is Campos and the first name is Rafael.
EXAMPLE 2
List the number and name of each customer whose credit limit is $7,500, together with
the number, last name, and first name of the sales rep who represents the customer .
111 Example 1, you used a co11ditio11 in tl1e \\THERE clause 011ly to relate a customer witl1 a
sales rep to join tl1e tables. Althougl1 relating a customer with a sales rep is esse11tial in tllis
example as well, you also 11eed to restrict the output to 011ly tl1ose custo111ers wl1ose credit fu11its
are $ 7,500. You cai1 rest1ict the rovvs by usi11g a compou11d condition, as sl1ov\'n il1 Figure 5-2.
Chapter 5
Home
SQL WorkshOp
EliAutocommit
Rows
SQL Commands
1-- I ~ ,<?
[20
( Save )( Run )
SEL:'.C: COSTOMER_N1JM, COSTOMER_ NAME:, REP. REP_NUM, LASI_ N:AME , f IRST NAME
FROM CUST0l1ER, REP
WHERE CUSTOMER.REP_NUM • REP .REP_NlIM +-- - - - - - - - - - - - - - '
AND CREDIT_ l..IMr! = 7500 ; +-- - - - - - - - - - - - - - - - - - ,
Saved SQL H story
Results
=
126
893
386
Condit ion to
relate t he t ables
Condit ion to
restrict the rows
I
Toys Galore
15
Campos
Rafael
All Season Gifts
15
Campos
Rafael
Johnson's Department store
30
Gradey
Megan
665
Cricket Gift Shop
30
Gradey
Megan
796
Unique Gifts
45
Tian
Hui
334
The Everything Shop
45
Tian
Hui
6 rows returned in 0.00 seconds
FIGURE 5-2
-
Download
Restricting the rows in a join
EXAMPLE 3
For every item on order, list the order number, item number, description, number of
units ordered, quoted price, and unit price.
A.11 item is considered on orde1· \\7he11 tl1ere is a row in the ORDER_LThTE table 011
which the item appears. You can find tl1e order n timber, number of u11its ordered, and
qt1oted price in the ORDER_LINE table. To fu1d tl1e description a11d the u11it price, ho'vvever, yot1 need to look in the ITEM table. Then you need to fi11d ro\.vs i11 tl1e ORDER_LINE
table and rows in tl1e ITEM table that match (ro'vvs containing the same item number). The
qt1ery and its results appear in Figt1re 5-3.
I Home SOL Workshop SQL Commands
0 Autocommit
Rows
1--1v -R
["20
( Save )( Run )
SELECT ORDER_NOM, ORDER_LINE. :TEM_Nml, DESCR:P'IION, MllM_ORD!.RED, QUOT!D_ FR: CE, PRIC!
FROM ORD"R_LIN=., IT!M
WllER=: ORDER_LINE . IT!M_Hl!M = ITEM. ITD!_NOM;
Results
~
lain Describe Saved SOL HIS!O:,Y
I
I
"
.. ., . .
••
I
51608
CD33
Wood Block Set (48 piece)
5
36.99
89.49
51613
Dl51
Classlc Railway Set
5
104.95
107.95
51623
DR67
Giant Star Brain Teaser
5
29.95
31 .95
51614
FD11
Rocking Horse
1
124.95
124.95
51619
FD11
Rocking Horse
2
121 95
124 95
51623
FH24
Puzzle Gift Set
12
36.95
38.95
51623
KD34
Pentommoes Brain Teaser
10
13.1
14.95
51610
Kl78
Piek Up sticks
25
10.95
10.95
51625
MTOJ
Zauberkasten Braln Teaser
8
45.79
45.79
51617
NL89
Wood Block Set (62 piece)
4
115.99
11975
51610
TR40
Tic Tac Toe
10
13.99
13.99
51617
TW35
Fire Engine
3
116.95
118.95
12 rows returned in 0.01 seconds
FIGURE 5-3
DownloaCI
Joining the ORDER_LINE and ITEM tables
Multiple-Table Queries
Qt1estion: Can you use ITEM.ITEM_NUM instead of ORDER_LINE.ITEM_NUM in the
SELECT clause?
Answer: Yes. The values for these two columns match because they must satisfy the
condition ORDER- LINE.ITEM- NUM = ITEM.ITEM- NUM.
COMPARING JOINS, IN, AND EXISTS
You joi11 ta bles i11 SQL by including a conditi o11 i11 tl1e "THERE clause to e11sure tl1a t
matclling colu1nns co11tain equal val11es (for example, ORDER_LINE.ITEM_NUM =
ITEM.ITEM_l\TlJM). You can obtain similar res11lts by u siI1g eitl1er the IN op er ator
(described in Cl1apter 4) or tl1e EXIST S op er ator \Vitl1 a subque ry. The cl1oice is a matter
of p erso11al preferen ce beca11se either approach obtains tl1e sam e r es11lts. Tl1e follo\ving
examples illu strate tl1e 11se of eacl1 oper ato r.
EXAMPLE 4
Find the description of each item included in order number 51623.
Beca11se this q11e ry also involves re trieving data from tl1e ORDER_LINE and ITEM
tables (as ill11strated in Example 3), yo11 cottld approacl1 it in a similar fasl1io11. Ther e are
two basic differ en ces, ho\,,ever , be t\v een Examples 3 and 4 . Firs t , tl1e q11ery in Example 4
does n ot req11ire as many col11mns; second, it i11volves only orde r n11mber 51623. Having
fewer col11mns to re trieve 1nean s tl1at the re \\'ill be fewe r col11mns listed i11 tl1e SELECT
clause. Yott can restrict the q11ery to a single o rder by adding the conditio n ORDER_NUM
= 151623 1 to tl1e \\THERE cla11se. Tl1e q11ery and its results a ppear in Fig11re 5-4.
Home
SOL Wor1cshop
0Autocomm1t
SQL Commands
Rows
120
I.., IV ,R
( Save )( Run )
SELEC! OESCRIP!IOM
FROM ORDER_LINE, I1t.M
W'MRE ORDER LINE . IITM NUM • IID!. ITEM !!<"UM
}...!ID ORCLll_~ u '51623';
-
Results
-
-
·-
plam uoscnlle Saved Sul History
Giant Star Brain Teaser
Puzzle Gift Set
Pentominoes Brain Teaser
3 rows returned in 0.00 seconds
FIGURE 5-4
Download
-
Restricting the rows when joining the ORDER_LINE and ITEM tables
Notice that the ORDER_Lll\TE table is listed iI1 tl1e FROM cla11se, even tl1011gl1 yo11 do not
11eed to display any columns from the ORDER_Lll\TE table. Tl1e \\THERE cla11se contains columns from the ORDER_Lll\TE table , so it is necessary to incl11de tl1e table in tl1e FRONI cla11se.
Chapter 5
Using the IN Operator
A11other \\ray to r etrieve data from n1ultiple tables i11 a query is to use tl1e IN operator \\7itl1
a subque ry. In Example 4 , you firs t could use a subquery to fi11d all item nu1nbers in the
ORDER_LINE ta ble that appear in a11y row on whicl1 tl1e order number is 51623. Tl1en
you cou ld find the description for any item \Vhose item 11u1nber is in this list . The query
and its results appear iI1 Figure 5-5.
Home
SOL Workshop
~Autocommrt
Rows
SQL Commands
120
I., I V ~
( Save ) ( Run )
SELECT DESCRIPTION
FROM ITEM
loll!ER£ ITEM N1lM IN
(SELECT ITEM_ NUM
Outer query
selects item
descriptions in
order 51623
FROM ORDER LINE
1'1HE.RE ORDE.R_NU11 a ' 51623' ) ;
Results
Subquery
selects item
numbers in
order 51623
Giant star Bram Teaser
Puzzle Gift set
I
Pentominoes Brain Teaser
3 rows returned in 0.00 seconds
FIGURE 5-5
Download
Using the IN operator instead of a join to query two tables
111 Figt1re 5-5 , evaluatil1g tl1e st1bqt1ery prodt1ces a temporary table co11sis ti11g of tl1ose
item 11t11nbers tl1at are prese11t il1 order 11t1mber 51623. Exect1til1g tl1e re1nai11i11g portio11 of
tl1e qtte ry prodttces descriptio11s for eacl1 item wl1ose 11t1mber is i11 tl1is te1nporary table; i11
tl1is case, Gia11t Star Brai11 Tease r, Pt1zzle Gift Set, a11d Pento1ni11oes Brai11 Teaser.
Using the EXISTS Operator
Yott also ca11 t1se tl1e EXISTS oper ator to ret1ieve data fro1n more tl1an 011e table, as show11
in Exa1nple 5 . The EXISTS operator cl1ecks fo r tl1e existen ce of rows tl1at satisfy so1ne
criterion.
EXAMPLE 5
Find the order number and order date for each order that contains item number FDll .
Tl1is query is similar to tl1e on e in Example 4, but tl1is time tl1e query involves tl1e
ORDERS ta ble a11d 11ot the ITEM ta ble. In this case, you ca11 ,vrite tl1e query il1 eitl1er of
tl1e ways previously demon s trated . For example, you could use the IN op erato r \\7ith a
subque ry, as sl10\\r11 in Figure 5-6.
Multiple-Table Queries
Home
SOL Worl<sllOI)
~Autocommil
Rows
SQL Commands
Iv IV #
120
( Save ) ( Run )
SUEC:: ORDER_NUM, ORDER_DAIE
FROM ORD"RS
WHERE ORDER HUM IN
(SELECT ORDER_ NUM
FROM OR!ltR LINE
lvrlE!!E IIEM_MUM e
Results
1:
Des
p
51614
' ffil l' ) ;
Saved s L
H st
10/13/2015
51619 _ _ _ 1011512
_0_15_
_,
2 rows retu rned in 0.48 seconds
FIGURE 5-6
Download
Using the IN operator to select order information
Usi11g tl1e EXISTS operator provides ai1otl1er approacl1 to solvi11g Exa1nple 5, as show11
i11 Figt1re 5-7 .
Home
SOL WorksllOp
~Autocommll
Rows
SQL Commands
Iv I V #
120
( Save )( Run )
SELECT ORDER_NUM, ORDER_DAIE
FROM ORDERS
WHERE EXIS:S
(SELECT *
FROM ORDER LINE
-
W!IE!E ORDERS . ORDER Nill! •
AND ::::E..'!_NOM ~ 'FDll');
Results
I
-
-
ORDER Lili!': . ORDER NUM
p
51619
10/15/2015
2 rows returned in 0.06 seconds
RGURE 5-7
Download
Using the EXISTS operator to select order information
The subqt1e1y i11 Figtire 5-7 is tl1e first 011e yot1 l1ave seen tl1a t i11volves a table listed in tl1e
outer query. Tl1is type of subquery is called a correlated subquery. In tl1is case, tl1e ORDERS
table, wl1ich is listed in the FROM clause of tlle ot1ter qt1e1y, is t1sed in tlle subquery. For tl1is
reaso11, you need to qt1alify tlle ORDER_NUM colt1mn in tl1e subquery (ORDERS.ORDER_NUM).
You did not need to qualify tl1e colt1mns in tl1e previot1s qt1eries involving tl1e IN ope rator .
Tl1e query show11 in Figt1re 5-7 \Vorl{s as follo\\7S . For eacl1 row iI1 the ORDERS table, tl1e
subquery is executed t1sing the value of ORDERS.ORDER_NUNI tl1at occt1rs in tl1at row. The
i1111er query prodt1ces a list of a ll ro\vs iI1 the ORDER_LINE table in wl1ich ORDER_LINE.
ORDER_NUNI matcl1es this valt1e and i11 wl1ich ITEM_Nill1f is e qt1al to FDll . You ca11 precede a subquery with tl1e EXISTS ope rator to create a condition tl1at is t1ue if one o r 1nore
rows are obtained wl1en the st1bque ry is exect1te d; o tl1er\\7ise, tl1e conditio11 is false.
To illt1strate tl1e process, conside r o rde r 11t11nbers 51613 and 51614 in tl1e ORDERS
table. Order nt1mbe r 51614 is i11clt1ded becau se a ro\v exists i11 the ORDER LINE table
witl1 tl1is o rde r 11t1mber and item nt1mbe r FDll . ,,T11e n the st1bqt1e ry is exect1ted, tl1er e will
be at least one row in the rest1lts, \Vhicl1 i11 tur11 mal{es tl1e EXISTS condition trt1e. Order
Chapter 5
n11mber 51613, h o,vever , will n ot be incl11ded beca11se n o row exists in the ORDER_LINE
table witl1 tl1is order nu1nbe r ai1d item 1111mbe r FDll . Tl1e re 'vvill be n o ro\vs contained i11
tl1e res11lts of tl1e s t1bqt1er y, 'vvhicl1 in t11r11 mal{es tl1e EXIST S condition false.
Using a Subquery Within a Subquery
You can use SQL to c reate a nested subquery (a subque ry 'vVitl1it1 a subque ry) , as
illus trated i11 Example 6.
EXAMPLE 6
Find the order number and order date for each order that includes an item located in
storehouse 3.
One way to approach tl1is proble1n is firs t to de ter1nine tl1e list of itetn nt11nbe rs i11 tl1e
ITEM table for eacl1 ite111 located in s to re11ot1se 3. Tl1e11 yot1 obtait1 a list of order 11t11nber s
i11 tl1e ORDER_LINE table 'vVitl1 a correspo11di11g ite1n 11t1mber i11 tl1e ite111 11umbe r list .
Fit1ally, you re trieve tl1ose o rde r 11t1mbe rs a11d orde r dates it1 tl1e ORDERS table for 'v\rl1icl1
tl1e order 11t11nbe r is in the lis t of orde r nt11nbe rs obtait1ed durit1g tl1e seco11d s te p . Tl1e
qt1e ry ai1d its rest1lts appear it1 Figt1re 5-8.
Home
SOL Workshop
0 Autocommit
Rows
SQL Commands
120
v
I
q ~
( Save ) ( Run )
SELECT ORDER_NUM, ORDER_DAIE
FROM ORDERS
>+-- - - - - - - - - 1
WHE..'lE ORDER NUM IN
(SELECT ORDER_ ~
-
FROMORD• R LINE
-
WHERE ITEM NUM IN
Outer query
is evaluated last
i-.------------,
(SELECT I!EM_NOM
f"ROM ITEM
WHERE STOREJIOOSE = ' 3 ' )) ;
•"-::"""---::----:::;:::;:::~~~::::;::::=~~~~~~~-~
Resu Its
i1 tory
Intermediate
query is evaluated
second
/ --i
1
51613
10/13/2015
51614
10/ 13/2015
51617
10/15/2015
51619
10/ 15/2015
4 rows returned in 0.84 seconds
FIGURE 5-8
Innermost
query is evaluated
first
Download
Nested subqueries (a subquery within a subquery)
As yot1 migl1t expect, SQL evaluates tl1e queries from tl1e it111ermost qt1e1y to the ot1termost qt1e 1y. Tl1e q11e1y in this example is evaluated i11 three s te ps:
1.
2.
Tl1e inne rmos t s11bquer y is evaliiated first, prod11cing a te mpora1y ta ble of
item numbers for tl1ose ite1ns located in stor el1ouse 3.
Tl1e 11ext (i11te r1nediate) st1bqt1e1y is evalt1ated, prod11ci11g a seco11d te mporary table 'vvitl1 a lis t of orde r nt11nbe rs. Eacl1 orde r nt1111ber i11 tl1is collectio11
l1as a ro'vv i11 tl1e ORDER LINE table for 'vvhicl1 tl1e ite111 nt1111ber is it1 tl1e
te111pora.ry table prodttced i11 Step 1.
Multiple-Table Queries
3.
Tl1e 011te r q11e ry is eval11ated last , prod11cing the desired list of order n11mbers
ai1d orde r d ates. Only tl1ose orders \\rl1ose nt1mbers are in the tempor ary
table prod11ced in Step 2 are incl11ded in tl1e r es11lts.
Ano tl1er approach to solving Example 6 involves joining the ORDERS, ORDER_LINE ,
a11d ITEM tables. Tl1e q11er y and its r esttlts appear in Fig11re 5-9.
I' Home SOL Workshop SQL Commands
~ Autocommit
Rows
lvl V -?
120
( Save )( Run)
SELECT ORDERS . ORDER_NUM, ORDER_VAI"E
FROM ORDER LINE, O:UJERS, ITEM
WP.ERE ORDER- LINE. O:Ul.ER- NOM = ORDERS. ORDER- NUM
AND ORDER- Lit!E. ITEM- NUM = ITEM. ITE:11- NUM
AND S!ORLJ!OUSE • ' 3' ;
Results
-
pill n uoscnbe
Saved Sul History
'
l
51613
10/13/2015
51619
10/15/2015
51614
10/13/2015
51617
10/1 5/2015
-
4 rows returned in 0.24 seconds
FIGURE 5-9
oo,ml!!i'!!.1
Joining three tables
In tl1is q11ery, the following conditions joi11 tl1e tables:
ORDER LINE. ORDER NUM = ORDERS.ORDER NUM
ORDER LI NE . I TEM NUM = I TEM. I TEM NUM
Tl1e condition STOREHOUSE = 13 1 restricts tl1e 011tp11t to only tl1ose item s located in
s tore ho11se 3.
Tl1e que ry results are correct regardless of \.vl1icl1 command yo11 11se. Yot1 can 11se
\.vhicl1ever approacl1 you prefer .
You might \.Vonde r whether one approach is m ore efficient tl1an the o ther . SQL
performs m a ny built-in optit11izatio ns tl1at analyze q11eries to de ter1nine tl1e best way to
s atisfy tl1em . Given a good optimize r, it sl1011ld not m alie m11ch differ ence how yo11 form11la te tl1e q11er y-you can see tl1a t 11sing 11ested s11bq11eries (Fig11re 5-8) prod11ces tl1e que ry
in 0 .84 seconds a11d joi11i11g tl1e ta.bles (Fig11re 5-9) prod11ces the res11lts in 0 .24 seconds.
If yot1 ar e us ing a DBMS witho11t an optin1izer, l1owever, tl1e \.Vay yo11 write a q11ery cari
malie a differ ence in tl1e speed at whicl1 tl1e DBMS exec11tes the q11er y. \\Tl1en yo11 ar e
worliing with a ver y large da tabase a nd efficiency is a pritne con cer11 , consult tl1e DB11S's
m a n11al or try so1ne timiI1gs yo11rself. Try r11nning tl1e same q11e ry bo tl1 \\rays to see
\.Vl1ether you notice a differ ence iI1 the speed of exec11tion . In small da tabases, the re sl1ould
no t be a significai1t titne differ ence between the two approacl1es.
A Comprehensive Example
Tl1e q11ery used i11 Ex a1nple 7 i11volves several of tl1e feat11res already prese11ted . Tl1e
quer y ill11s trates all tl1e 1najor cla11ses that yo11 ca11 11se it1 a SELE CT com111a11d. It also
ill11s trates the order in \.\rl1icl1 tl1ese clauses 1nus t appear.
Chapter 5
EXAMPLE 7
List the customer number , order number, order date, and order total for each order ,vith
a total that exceeds $500. Assign the column name ORDER_TOTAL to the column that
displays order totals. Order the results by order number.
Tl1e query and its res11lts appear in Fig11re 5-10.
Home
SOL Worlcshop
0 Autocomm11
Rows
SQL Commands
I" I V ~
[20
( Save )( Run )
SELECT cus:OMER_NOM, ORDERS.ORDER_NOM, ORDER_DAIE,
SIJM(NUM_ORDERED * QUOTI:D_PRICE) AS ORDER_IOIAL- - - 1
fROM ORDL'lS, ORDER_LillE
WHERE ORDERS . ORDER-NID! = ORDE9.-LINE .ORI!::R- NUM
GROUP BY ORDERS.ORDER_NUl1, CUSTOMER_NUM, ORDER_DATE
HAVING SUl1(NOM_ORDEPJ::D • QOOIED_PR!CE) > 500
ORDER BY ORDEll.S .ORDER_NOM;
'iaved <; L H
Results
ry
386
51613
10/13/2015
524.75
586
51617
10/15/2015
814.81
I 586
51623
10/15/2015
724.15
3 rows returned in 0.0 1 seconds
FIGURE 5-1 O
Name for "-----1
computed
column
Download
Comprehensive example
1I1 tllis q11ery, tl1e ORDERS and ORDER_LINE tables are joined by listing bo th tables i11
tl1e FROM clat1se and relating them in the WHERE clause. Selected data is sorted by order
11u1nber u siI1g tl1e ORDER BY cla11se. The GROUP BY cla11se indicates that tl1e data is to be
gro11ped by order 11umber, c11stom er nt1mber , and order date. For eacl1 gro11p, the SELECT
clause displays the c11s tomer 11umber , order 11umbe r, order date, and order total
(SUM(}.TUM_ ORDERED * QUOTED_PRICE)). In addition, the total v.ras re11amed
ORDER_TOTAL. Not a ll groups vvill b e displayed, h owever . Tl1e HJ.\VING cla11se displays
only tl1ose gro11ps wl1ose SUM(}.TUM_ORDERED * QUOTED_PRICE) is greater tl1an $500.
Tl1e order 11umbe r, c11s tom er 1111mber, and order date are 11nique for each order . Tl1us,
it wo11ld seem that m er ely gro11pi11g by order nt1mber ,vould be st1fficient. SQL r eq11ires
tl1at botl1 tl1e ct1stom er 11t1mber and tl1e orde r date b e lis ted in tl1e GROUP BY clat1se.
Recall that a SELECT clause can include statistics calc11lated for 011ly the gro11ps or colu1n11s vvl1ose valt1es are ide11tical for each rovv in a gro11p. By stating tl1at tl1e data is to be
gr o11ped by order n111nber , ct1stomer n11mber, and order date, yo11 tell SQL tl1at tl1e val11es
in tl1ese col11mns mus t be the sa1ne for eacl1 row in a group.
Using an Alias
\\'hen tables are listed in the FROM clause, yo11 can give eacl1 table an alias, or a11 alternate 11ame, tl1at yo11 cru1 11se iI1 tl1e rest of the s ta tem e11t. Yott create an alias by typing the
name of the table, pressing the Spacebar, and tl1en typing tl1e nrune of tl1e alias. No commas or pe riods ar e 11ecessar y to separate tl1e tvvo nrunes.
Multiple-Table Queries
One reason for i1sing an alias is simplici ty. In Exa111ple 8, yot1 assign tl1e REP table
tl1e alias R and tl1e CUST011ER table tl1e alias C. By doi11g tl1is, yot1 can type R instead
of REP and C instead of CUSTOMER in the ren1ai11de r of the query. Tl1e qt1ery in
this example is simple , so yott migl1t not see the ft11l bene fit of this fea tt1re. \\Then a
query is complex and requires yot1 to qt1alify tl1e 11ames, tising aliases can simplify
tl1e process.
EXAMPLE 8
List the number, last name, and first name for each sales rep togetl1er ,vith the number
and name for each customer the sales rep represents.
Tl1e qt1ery and its rest1lts t1sing aliases appear in Figt1re 5-11.
L Home
SOL Worl<stiop
0Autocommil
Rows
SQL Commands
1.,, 1~ #
120
( Save )( Run )
SELECT R. !tEP_NlJM, ~.S!_NM-!E, FIRS!_~'!::, C. COSlO!-ER_NlJM, CUS!OMER_MAME
FROM REP ~, CUSTOMER C ~
Wfil:RE R. REP_HUM = C. REP_NUM;
I
Results
plain
0-lia0
Descnoe Saved S
ll
l
1,1, ..
•·•""II~~ r-1TIT
15
Campos
Rafael
126
Toys Galore
15
15
Campos
Rafael
Cards and More
Campos
Rafael
502
713
15
30
Campos
Rafael
Gradey
30
.,:
Cress store
All Season Gifts
Megan
893
665
Gradey
Megan
824
Klme's
30
30
Gradey
Megan
Johnson's Department Store
Gradey
Megan
45
Tian
Huf
386
260
440
Grove Historical Museum Store
45
nan
Hui
796
Unique Gifts
45
Tian
Huf
586
Almondton General Store
45
Tian
Hui
334
The Everything Shop
12 rows returned in 0.03 seconds
RGURE 5-11
Cricket Giff Shop
Brookings Direct
I
OoYmload
Using aliases in a query
NOTE
Technically, it is unnecessary to qualify CUSTOMER_NUM because it is included only in the
CUSTOMER table. It is qualified in Figure 5-11 for illustration purposes only.
Joining a Table to Itself
A second situation for i1sing a11 alias is to joi11 a table to itself, called a self-join, as
illt1strated in Example 9.
Chapter 5
EXAMPLE 9
For each pair of custom ers located in the same city, display the customer number,
customer name, a.n d city.
If you l1ad rnro separate tables for custo1ners and tl1e query requested customers i11
tl1e first table l1aving the same city as ct1stomers in the second table, you could use a
11ormal join oper atio11 to find tl1e answer. In tllis case, 110\.,,ever, there is 011ly 011,e table
(CUSTOMER) tl1at stores all tl1e custo1ner info rmation. You ca11 treat the CUSTOMER
table as if it \.Vere two tables in tl1e query by creati11g a11 alias, as illustrated i11 Exa111ple 8.
lt1 tl1is case, you use tl1e followi11g FROM clause:
FROM CUSTOMER F, CUSTOMER S
SQL treats this clause as a que ry of t\.\ro ta bles: one that l1as tl1e alias F (first),
and another that has tl1e alias S (second). The fact tha t both tables are really tl1e
same CUSTOMER table is not a pro blem . The query a11d its results appear in
Figure 5-12 .
Home
SQL Workshop
E?lAutocommrt
Rows
Sche
SQL Commands
!20
Iv I " ,?
( Save ) CRu,i_)
SELEC: F.CUSTOMER_NUM, F.CUSTOMER_NAME, S.CUSTOMER_NUM, S.CUSTOMER_ NAME, F.CITY
fROM CUSTOMER F, CUSTOMER s
C d ..
lfflERE: F. C: IY • S . CITY +-- - - - - - ,
on 1t1o n
rum r.cusrUa"!ER_~ < s.cusroME~-~1
.
~
to j oi n F a n d S
O!IDE:R BY r .cus _owR_NUM, s.cus_OMER_NUM,
bl
ta es
Results
His ry
126
Toys Galore
440
Grove Hlstorlcal Museum Store
Fullton
126
Toys Galore
893
All Season Gifls
Fuuton
260
Brookings Direct
665
Cricket Giff Shop
Grove
334
The Everything Shop
713
Cress Store
Congaree
386
Johnson's Department Store
796
Unique Gifts
Northfield
440
Grove Historical Museum Store
893
All Season Gifts
Fullton
824
Kline's
Mesa
~
Cards and More
ws returned in 0.08 seconds
Download
FIGURE 5-12
Using aliases for a self-join
Yo11 a re req11esting a c11stome r n11mber and name from the F table, follo\.ved by a c11stomer n11mber and name from the S table, and tl1en tl1e city. (Because the city in tl1e first
table m11st matcl1 tl1e city in tl1e second table, yo11 can select tl1e city from either table.)
Tl1e \VHERE cla11se contains two co11ditions: the cities m11st match, and the c11stomer
n11mber from the first table m11st be less than tl1e c11stomer n11mber from the second table.
In addition, the ORDER BY cla11se ens11res tl1at the data is sorted by the first c11stomer
n11mber. For those rows \.Vitl1 the same first c11stomer n11mber , the data is ft1rther sorted by
tl1e second customer n11mber.
Multiple-Table Queries
Question: ,Vh)' is the condition F.CUSTOMER_NUM < S.CUSTOMER_NUM important in
the query?
Answer: If you did not include this condition, you would get the query results shown in
Figure 5-13.
Home
SOL Workshop
0 Autocommit
Rows
Sche
SQL Commands
j20
j .., I ~
,R
( Save )( Run )
SELECT F.COSTOMER_NUM, f. COSIO!-!E_R_NAME , S.CUSTOMER_NUM, S.CUSIOMER_NAME, f . CITY
E'ROM CUSTOMER F, CUS70ME:R S
i.HERE F. CITY ~ S.CI:Y
ORDE.R BY f. CUSIOME.R_NUM, s . cus: oMER_NUM;
Results
L H story
~
•
126
Toys Galore
126
Toys Galore
Fullton
126
126
Toys Galore
Grove Historical Museum S1ore
Fultton
Toys Galore
440
893
All Season Gifts
Fullton
260
Brookings Direct
260
Brookings Direct
Grove
260
Brookings Direct
665
Cricket Gift Shop
Grove
334
The Everything Shop
334
The Everything Shop
Congaree
334
386
The Everything Shop
Cress Store
Congaree
Johnson's Department Store
713
386
Johnson's Department Store
Northfield
386
Johnson's Department Store
796
Unique Gifts
Northfield
440
Grove Historical Museum S1ore
126
Toys Galore
Fullton
440
Grove Historical Museum Store
440
Grove Historical Museum Store
Fuinon
440
502
Grove Historical Museum Store
All Season Gifts
Fulllon
Cards and More
893
502
Cards and More
Mesa
502
Cards and More
824
Kline's
Mesa
RGURE 5-13
Incorrect joining of a table to itself
The first row is included because it is true tl1at customer number 126 (Toys Galore)
in the F table has the same city as customer number 126 (Toys Galore) in the S table.
The second row indicates th at customer number 126 (Toys Galore) has the same city as
custome r number 440 (Grove I-listorical Museum Store). The tenth ro,v, however,
repeats the same information because custome r number 440 (Grove Historical Museum
Store) has the same city as customer number 126 (Toys Galore). Of these three rows,
the only row that should be iI1cluded in the query results is the second row. The second
row also is the only one of the three rows in which the first customer number (126) is
less than the second customer number (440). This is why the query requires the condition F.CUSTOMER_NUM < S.CUSTOMER_NUM.
Using a Self-Join on a Primary Key Column
Fig11re 5-14 shows some fields from an EMPLOYEE table whose primary l{ey is
EMPLOYEE_NUM. Another field in the table is N1GR_E11PLOYEE_NUM, \vhicl1 represents
tl1e number of the employee's m anager, \Vho also is an employee. If yo11 lool{ at the ro\v
Chapter 5
for employee 206 (Joan Dyl{stra), yot1 will see that employee 198 (Niona Canzier) is
Joan's 1nanager. By lool{i11g at the ro\.\1 for e1nployee 198 (Mona Canzier), you see tl1at l1er
manager is employee 108 (Martin Holden). In tl1e rovv for employee 108 (Martin Holde11),
tl1e manager nt1mber is nt11l , indicating that he has no manager.
Home
SOL Workshop
Ell Autocommlt
SQL Commands
(20
Rows
, .., I ~ ,,{/
( Save )( Run )
SELECT EMPLOY~_NUM, I.AS!_NAME, FIRSI_NAHE, MGR_EMPLOY::E_NUM
FROM EMPLOYEE;
Results
•
•
Employee 108
108
Holden
Martin
198
Canzier
Mona
108
206
Dyl<stra
Joan
198
255
Murray
Steven
301
301
Galvez
Benito
108
366
Petennan
Beth
198
Employee
391
402
Traynor
Matt
Brent
Ashton
301
301
198 manages
employee 206
466
Scholten
Alyssa
108
551
Wiltzer
Morgan
198
10 rows returned in 0.00 seconds
FIGURE 5-14
has no man a ger
Download
Employee and manager data
Stippose yot1 need to list tl1e employee number, employee last 11ame, and employee
first name along with tl1e ntimber, last name, and first name of eacl1 employee's manager.
Jtist as in the previotis self-joiJ.1, you wot1ld list the ENIPLOYEE table twice in the FROM
clat1se witl1 aliases.
Tl1e command shovvn in Figt1re 5-15 tises the letter E as an alias for tl1e employee and
tl1.e letter NI as a11 alias for the ma11ager. Thtis, E.ENIPLOYEE_NUM is the e1nployee's
11t1mber and NI.EMPLOYEE_NUNI is tl1e nmnber of tl1e employee's 1nanager. In tl1e SQL
command, M.ENIPLOYEE_NUNI is renamed as MGR_NUM, M.LAST_NAME is renamed as
NIGR_LAST, a11.d M.FIRST_NM1E is renamed as MGR_FIRST. Tl1e condition i11 the
\\THERE clause ensures tl1at E.MGR_EMPLOYEE_NUNI (tl1e ntimber of the employee's
1nanager) matches M.ENIPLOYEE_NUM (tl1e employee ntimber on the manager's row in
tl1e table). Employee 108 is 11ot iI1clt1ded in the resttlts becatise Martin Holden l1as no
manager (see Figt1re 5-14).
Multiple-Table Queries
Home
SOL Workshop
El! Autocommit
SQL Commands
Rows
j20
Iv I " .(/
( Save ) ( Run)
SELECT E. EMPLOYEE_NUM, E . lASI_NAME, E . F!RSI_NAME, M.EMPLOYEE_NUM AS MGR_NUM,
M. LAST_trAME AS MGR_LASI, M. FIJtSI_ NAME AS MGR_FlRSI
FROM E~PLOYEE E, E.MP10YE:C: M
WHERE E . MGR- E.MP:'..OYE.E- NUM s M.EMPLOYEE- NUH
ORDER BY E. EMPLOYEE_YUM;
198
Canzier
Mona
108
Holden
Martin
206
Dykstra
Joan
198
canzier
Mona
255
Murray
steven
301
Galvez
Benito
301
Galvez
Benito
108
Holden
Martin
366
Petennan
Beth
198
canzler
Mona
391
Traynor
Matt
301
Galvez
Benito
402
466
Brent
Ashton
Galvez
Benito
Schonen
Alyssa
301
108
Holden
Marlin
551
Winzer
Morgan
198
Canzier
Mona
9 rows returned in 0.05 seconds
FIGURE 5-15
Download
List of employees and their managers
Joining Several Tables
It is possible to join sever al tables, as ill11strated i11 Example 10. For each p air of tables yo11
join, yo11 m11s t m cl11de a conditio11 mdicati11g 110\\' tl1e columns are related .
EXAMPLE 10
For each item on order, list the item number, number ordered, order number, order
date, custome r numbe r, and customer name, along with the last name of the sales rep
who represents each customer.
As m ention ed earlier , an item is on orde r \vl1e11 it occ11rs 011 an y r o\V i11 tl1e
ORDER_LINE ta ble. The item n11mber , n11mbe r orde red , and order nutnbe r appear in
tl1e ORDER_LINE table. If tl1ese req11irem ents re present tl1e entire q11ery, yo11 wo11ld
\Vrite the q11e ry as follo\\7S:
SEL E CT ITEM NUM, NUM ORDERED, ORDER NUM
FROM ORDER LINE ;
Tl1is q11ery is 11ot s11fficient, 110\vever. Y011 also 11eed the order d ate, \Vl1icl1 is in the
ORDERS ta ble; tl1e c11s to1n er n11mbe r and name, which are in tl1e CUSTOMER table;
a11d the re p last name, \vhicl1 is in tl1e REP ta ble. Tl1us, yo11 n eed to jom fou1- tables:
ORDER_LINE, ORDERS, CUSTOMER, and REP. Tl1e procedi1re for jo i11ing m or e tl1a11 t\vo
ta bles is essentially the sam e as tl1e one for joining t\vo ta bles. Tl1e diffe re nce is that tl1e
Chapter 5
condition in the \\THERE clause \.Vill be a compo11nd condition . In tl1is case, you wo11ld
\.Vrite the \\THERE cla11se as follo\\rs:
= ORDER LINE . ORDER NUM
AND CUSTOMER. CUSTOMER NUM = ORDERS. CUSTOMER NUM
AND REP. REP NUM = CUSTOMER. REP NUM
WHERE ORDERS . ORDER NUM
'f l1e first condition relates an order to an o rder line with a matclling order n11mber .
Tl1e second co11dition relates tl1e c11s tom er to the order " 'itl1 a 1natcl1ing c11s tom er n11mber . Tl1e fi11al condition relates tl1e r ep to a c11s tomer \.\ritl1 a 1natcl1ing sales r ep number .
For tl1e comple te q11ery, yo11 lis t all the desi red col11mns in the SELECT cla11se and
q11alify any columns that appear in more tl1a11 on e table. In the FROM clause, you lis t tl1e
tables that are involved in tl1e q11ery. The q11ery and its res11lts appear in Figure 5-16.
Home
SOL Workshop
0 Autocommit
Rows
SOL Commands
Iv I ~ .{/
[}o
( Save ) ( Run )
SELE.C':' I IE.M_NUM, NUM_ORDERED, ORD• R_LINE. ORDER_NUM, OllDE.R_lll>JE, CUSTOME!LCUSTOMER_NUM,
CUSTOMER_ NAME , Ll\.ST_NA.~
FROM ORDER L I NE, ORDERS , CUSTOMER, REP - - - - - - - - - - - - - - - - ---1
lffll:RE ORDERS . ORDER- NOl-1 = ORDER- LINE.ORDER- NUM
AND CUSTOMER. CUSTOMER NUM = ORDERS . CUSTOMER NUM >+- - - - ,
AND REP.REP NUM = CUSTOMER.REP NUM
Conditions to
-
-
ORDER BY :TEM_NOM, ORDER_LINE .ORDER_NUM;
;~ - - - - - - - - - -~ ~ ~ ~:---__..,.__
Results
Tables to
include in query
_
:.uvoa s L
I ' I
relate the tables
/-~~~~~~
1s1ory
•
CD33
5
51608
10/12/2015
126
Toys Galore
Campos
DL51
5
51613
10/ 13'2015
386
Johnson's Department Store
Gradey
DR67
5
51623
10/ 15/2015
586
Almondton General store
Tian
FD11
1
51614
10/13/2015
260
Brookings Direct
Gradey
FD11
2
51619
10/15(2015
126
Toys Galore
Campos
FH24
12
51623
10/15(2015
586
Almondton General Store
Tian
KD34
10
51623
10/15/2015
586
Almondlon General Store
r ran
Kl..78
25
51610
10/ 12/2015
334
The Every1hing Shop
Tian
MT03
8
51625
10/ 16'2015
796
Unique Gins
Tian
NL89
4
51617
10/ 15/2015
586
Almondton General Store
rran
TR40
10
51610
10/ 12/2015
334
The Every1hing Shop
Tian
TW35
3
51617
10/ 15(2015
586
Almondton General Store
Tian
12 rows returned in 0.04 seconds
FIGURE 5-16
Download
Joining four tables in a query
Qt1estion: \\Thy is the ITEM_NUM column, which appears in the ITEM and ORDER_LINE
tables, not qualified in the SELECT clause?
Ans,ver: Among the tables listed in the query, only one table contains a column named
ITEM_NUM, so it is not necessary to qualif)r the table. If the ITEM table also appeared in
the FROM clause, you would need to qualify ITEM_NUM to avoid confusion between the
ITEM NUM columns iI1 the ITEM and ORDER LINE tables.
Multiple-Table Queries
Tl1e qt1e ry sl10\.\'ll i11 Figt1re 5-16 is m or e complex tl1a11 mat1y of tl1e previot1s 011es yot1
l1ave exami11ed . You 1nigl1t tl1i11lr tl1at SQL is 11ot st1c l1 a11 easy la11gt1age to t1se after all. If
yot1 ta ke it 011e ste p a t a ti111e, 110\.,,ever, tl1e que ry i11 Exa1nple 10 really is 11ot tl1at diffic t1lt .
T o co11strt1c t a de tailed qt1e ry i11 a system a tic fashio11, do tl1e follo\.\'Ulg:
Lis t i11 tl1e SELECT c lau se all tl1e colu1nns tl1at yot1 "''ant to display. If tl1e
11am e of a colt11ru1 appears i11 1n or e tl1a11 011e table, precede tl1e colum11 11a111e
v.ritl1 tl1e tab le 11a111e (tl1at is, qt1a lify the colt11ru1 11a1n e).
List iI1 the FRON! clat1se all tl1e tables i11volved in tl1e qt1e ry. Ust1ally yot1 i11clude
tl1e tables that co11tain tl1e colt1mns listed in tl1e SELECT clause. Occasio11ally,
l1owever , the re 1night be a table tl1at does not co11tain any colt1rm1s used in tl1e
SELECT clat1se bt1t tl1at does contai11 colt1m 11s used in the \\Tf-IERE clause. I11
tllis case, yot1 also must list tl1e table i11 tl1e FROM clause. For example, if yot1
do not need to list a c t1sto1ner n t1mber or n ame, bt1t yot1 do n eed to list tl1e rep
11ame, yot1 \.Vottld not i11clt1de a11y colt11nns from the CUSTOMER table in tl1e
SELECT clause. The CUSTOMER table still is reqt1ired , ho\.veve r, because you
m t1st inclt1de a colt1rm1 from it i11 tl1e \\THERE clat1se.
Ta lre one p air of rela te d tables at a time a11d indicate i11 tl1e WHERE c lat1se
tl1e conditio11 tl1at r elates tl1e ta bles. Join tl1ese conditio11s witl1 tl1e AND
ope ra to r . If tl1ere a re any o tl1er conditions, include tl1em in tl1e Wl-IERE
cla t1se and connect the m to the o tl1er conditions \.Vitl1 tl1e AND ope ra tor . For
exa.m ple , if yot1 \.Va11t to view item s present on orde rs placed by only those
cu stom e rs \.Vith $ 7 ,500 c redit limi ts, yot1 would add on e more condition to
tl1e \\THERE clause, as sl10\.vn in Figt1re 5-17 .
1.
2.
3.
j I Home
SQL Commands _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __
SOL Workshop
EZI Autocomm!t
I" IV ~
[211
Rows
Schema jPRATT/LAST .,, I
r Save ) ( Run )
SELECT ITEM_ NUM, NOl·l_ORDERED, ORDER_ LINE,ORDER_ NOM, ORDER_ DATE, COSIOMER.COS!OMER_ NOM,
CUSIOMER_NA.'!E, :.AST_m.ME
FROM ORDER_ LINE, ORDERS, CUSTOMER, REP
Wf!E:U: ORDERS . ORDER NOM = ORDER llfil: . ORDER NUM
1'.ND COSTOMER. COSIOMER MUM = ORDERS . CUSI OHER N1lM
AND REP. REP- NUM = CUSTOMER. REP- NUM
-
-
Jl.ND CREDI:: Lil£:: = 7 SOD
ORDER BY In:M_ NUM, ORDER_ LINE.ORDER_ NUM;
n
Results
r
L
5ilVell
I • I
ISi ry
l
CD33
5
51608
10112/2015
126
Toys Galore
Campos
Dl51
5
51613
10/13/2015
386
Johnson's Department Store
Gradey
FD11
2
51619
10/1512015
126
Toys Galore
Campos
KL78
25
51610
10/1212015
334
The Everything Shop
n an
MT03
8
51625
10/16/2015
796
Unique Gifts
nan
TR40
10
51610
10/1212015
334
The Everything Shop
nan
6 rows returned in 0.01 seconds
FIGURE 5-17
Download
Restricting the rows when joining four tables
Chapter 5
SET OPERATIONS
In SQL, yot1 ca11 t1se the set operatio11s for talting the t1nion , intersection, a11d difference
of t\.vo tables. Tl1e ttnion of two tables uses tl1e UNION oper ator to cr eate a temporary
table contai11ing eve ry ro\.v tl1at is in e itl1e r tl1e firs t table, tl1e second table, or botl1 tables.
Tl1e intersection of t\.vo tables t1ses tl1e INTERSECT operator to crea te a temporary table
containing all ro\.vs tl1at are i11 botl1 tables. The difference of hvo tables uses tl1e lVIINUS
operato r to cr eate a temporary table containi11g tl1e se t of all r o\.vs that are i11 tl1e firs t
table bt1t tl1at are not i11 tl1e second table .
For example, st1ppose tl1at TEMPI is a table containing tl1e nt11nber and name of eacl1 customer represented by sales rep 15. Ft1rtl1er, st1ppose tl1at TEMP2 is a table containi11g tl1e 11t1mber and na1ne of tl1ose custom ers tl1at cu1Tently l1ave orde rs on file, as sl1own in Figt1re 5-18.
TEMP1
TEMP2
CUSTOMER_NUM CUSTOMER_NAME
126
CUSTOMER_NUM CUSTOMER_NAME
'foys Galore
I
126
'l'oys Galore
;
502
Cards and ~'lore
260
Brookings Direct
71J
Cress Store
JJ4
The Everything Shop
893
1\ll Season GiJts
386
Johnson's Department Store
586
Alrnondton General Store
796
lJniquc (}ifts
FIGURE 5-18
'
Customers of rep 15 and customers with open orders
'f l1e t1nio11 of TEMPI and TE1'IP2 (TEMPl UNION TEMP2) cons is ts of the 11t1mber and
name of those cttstome rs that are represented by sales rep 15 or that cttrrently l1ave
orders on file , or both. The inte rsecti on of these two tables ('fEMPl INTERSECT TEMP2)
contains tl1ose cus tom ers that are represented by s ales rep 15 and that have orders on
file. The diffe re11ce of these t\.vo tables (TEMPl MINUS TE1'IP2) contains those ctts tom ers
tl1at are represented by sales rep 15 bttt that do not have orders on file. Tl1e res11lts of
tl1ese se t operations are shown in Fig11re 5-19.
TEMP1 UNION TEMP2
TEMP1 INTERSECT TEMP2
CUSTOMER_NUM CUSTOMER_NAME
126
'foys Galore
260
Brookings Direct
334
'fhe l<;verything Shop
386
Johnson's Departtnent Store
502
Cards and lvlore
586
Afmondton General Store
713
Cress Store
796
Unique Gifts
89J
All Season Gifts
FIGURE 5-19
CUSTOMER_NUM CUSTOMER_NAME
I
126
'foys Galore
TEMP1 MINUS TEMP2
I
CUSTOMER_NUM CUSTOMER_NAME
I
502
Cards and Nfore
713
Cress Store
893
All Season Gifts
I
Union, intersection, and d~ference of the TEMP1 and TEMP2 tables
Multiple-Table Queries
Tl1ere is a restric tion on set oper ations. It does n ot mal{e se11se, fo r example, to tall{
about tl1e union of tl1e CUSTOMER table and tl1e ORDERS table because these tables do
no t conta in the s aine col11m11s. \Vhat migl1t rows i11 this 11nion lool{ lil{e? Tl1e t\.vo tables in
tl1e 11nion miist l1ave tl1e sam e s tr11c t11re for a 11nion to be appropria te ; tl1e formal term is
union compatible. T\,ro tables are union compatible \.vl1en tl1ey l1ave tl1e sam e n111nber of
col11mns a11d their corresponding col11mns l1ave identical d ata types and lengths.
Note that the definition of ttnion compatible does not state that the col11rm1s of tl1e
two tables m11s t be identical but r atl1er that the col11m11s m11st be of tl1e sa1n e type.
Tl111s, if 011e col11mn is CHAR(20), the m atcl1ing col11mn also 1n11s t be CHAR(2 0).
EXAMPLE 11
List the number and name of each custome r that is either represented by sales rep 15 or
currently has orders on file, or both.
You can create a tempo rary table contai11ing tl1e number and n am e of eacl1 ct1stom e r
tl1at is represented by sales rep 15 by selecting the c11s tom er numbers and nam es from
tl1e CUSTOMER table fo r wl1icl1 tl1e sales rep 1111mber is 15 . The n yo11 can create a11otl1er
temporary table containing the n11mbe r and 11am e of eacl1 ct1s tom er tl1at c11rrently l1as
o rders on file by joining the CUST OMER and ORDERS tables. The two tempor ary
tables cr ea ted by this process l1ave tl1e sam e s trt1c t11re ; that is, tl1ey bo th co11tai11 tl1e
CUSTOJ\1ER_NUM and CUSTOJ\1ER_NANIE colu1nns. Beca11se tl1e tempor ary tables ar e
11nion compa tible, it is possible to tal{e the 11nion of tl1ese t\.vo tables. The q11er y and its
res11lts appear in Fig11re 5-20.
L
Home
SOL Worlcshop
E"ll Autocommll
Rows
SQL Commands
(20
!vl V Q
( Save )( Run)
SELEC! CUSTOMER_NOM, CUSIOlfi:R_NAME
FROM CUSTOMER
WHERE REP NOM = ' 15 '
ONION
SEU:C! CUSTOMER.COSIOMER_NUM, COSTOHER_NAME
FROM CUSIOt-lER, ORDERS
WHERE CUSI O!-!E!l. CUSIOMER_&uM = ORO:;:RS . CUSTOME."'t_NUM;
Results
First query
UNION operator
-
:p1.:un Descnoe Saved :iUL History
,.
°lT,:',J
126
Toys Galore
260
334
Brookings Direct
The Everything Shop
386
Johnson's Department store
502
Cards and More
586
Almondton General Store
713
796
Cress Store
Umque Gifts
893
All Season Gifts
9 rows returned in O.00 seconds
FIGURE 5-20
Second q uery
DQwnloag
Using the UNION operator
Chapter 5
If yottr SQL itnplemen tation tr11ly sttpports the 1111ion operation , it will rem ove a11y
dttplicate r o\vs a11tom a tically. For example, any c11sto1ner tl1at is represented by s ales rep
15 a ncl that c1.1rre 11tly l1as orders 011 file will appear only once in the res1.1lts. Oracle,
Access, and SQL Server sttpport tl1e ttnion operation and correctly remove dttplicates.
EXAMPLE 12
List the number and name of each customer that is represented by sales rep 15 a nd that
curren tly has orders on file.
Tl1e only differen ce be n,,,een this q11e ry and the o ne in Exa n1ple 11 is that tl1e
appropriate operator to 11se is INTERSECT, as sl10\vn in Figure 5-21 .
Home
SQL WorllShop
@Autocommit
SQL Convnands
Rows
V ,?
j ..., 1
120
( Save )( Run )
SELEC: cus: oM::R_NUM, CUSTOME:R_NJ>..ME
FROM CUSTOMER
WHERE REP NUM = '15 '
INIERSECT
SELEC'I CUSTOl€R . CUSTOMER_NUM, CUSTOMER_NAME
FROM CUSTOMER, ORDERS
WHERE CUSTOMER . CUSTOMER_NUM = ORDERS . CUSIO.'IER_NUM;
Results
Des
p
126
Toys Galore
Download
1 rows retu rned in 0.07 seconds
1
FIGURE 5-21
Using the INTERSECT operator
Som e SQL implem en tatio11s do 11ot support the INTERSECT operator, so you n eed to
take a different approacl1. Tl1e com111and sh own in Fig1.1re 5-22 prod11ces tl1e same r esttlts as
tl1e INTERSECT operator by ttsing tl1e IN operator and a subquery. Tl1e co1nma11d selects tl1e
11umber a11d 11ame of eacl1 custom er tl1at is re presented by sales rep 15 and \Vl1ose c1.1stome r
11umber also appears in tl1e collection of customer 11umbers in tl1e ORDERS table.
Home
SQL Wor1cshop
@ Aulocommtt
SQL Commands
I" I V ,?
120
Rows
( Save )( Run )
SELECT CUSTOMER_NUM, CUSI OME...'l_NA..'iE
FROM CUSTOMER
Rep number
must b e 15
WHERE REP N1lM = ' 15 •- - - - - - - - - - - - '
-
AND CUST0!1ER NUM IN (SELECT CUSIO!€R_NUM
-----------,
FROM ORDERS I ;
Customer
number must be in
t he resu Its of
Results
e Saved S L
- - - - - - - - - - - - - - - - ' - - - -~ thesubque~
•
126
Toys Galore
1 rows returned in 0.00 seconds
FIGURE 5-22
Download
Subque~to
select numbers of
customers with
orders
Performing an intersection without using the INTERSECT operator
Multiple-Table Queries
NOTE
Oracle and SQL Server support the INTERSECT operator but Microsoft Access does not.
EXAMPLE 13
List the number and name of each customer that is represented by sales rep 15 but that
does not have orde rs currently on file.
Tl1e q1.1ery uses tl1e MThTUS oper ator , as sh o\vn i11 Fig1.1re 5-23.
Home
SOL Wor1cshop
0 Autocommit
Rows
SQL Convnands
[20
I" I V ~
( Save )( Run )
SE:LECT cos:oM:c:.~_NUM, CUSIOMER_NJU!E
FROM CUSIOMER
WHERE REP NIDI a ' 15 '
MINUS
SE:LECT COSTOMER . CUSI OMER_NUM, CUSIOMER_ NAME
FROM CUSIOMER, ORDERS
WHERE CUSTOMER. CUSIOMER_NUM c ORDE:RS. COSIOME.R_tlUM;
-
Results
p
502
Cards and More
713
Cress store
893
All Season Gifts
3 rows returned in 0.00 seconds
FIGURE 5-23
Download
Using the MINUS operator
Jus t as \'\Tith the INTERSECT oper ator , som e SQL i111plem e11ta tio11s do 11ot support the
NIINUS op erator . In such cases, you need to talre a different approach , sucl1 as tl1e on e
sh o\v11 in Figure 5-24. Tllis corm11and produces tl1e same r esults by selecti11g the 11umber
a nd n ame of each cu stom er tha t is re prese11ted by sales r ep 15 and \\Th ose c1.1s tom e r
11un1ber does not appea.r in the collectio11 of cu sto111e r numbers i11 the ORDERS table.
Home
SOL Wor1cshop
0Autocomm1I
Rows
SQL Convnands
120
j .., I
'1 ~
( Save )( Run )
SELECT cos:c»01._NUM, COSIOMER_NJ!.ME
FROM CUSTOMER
WHE:RE REP NUM ; '15 '
AND CUSTOMER NCM HOT ni---------1
(SEL;:CT COSTOI-IER_MUM
FROM ORDERS);
-
Results
Customer
number cannot
be in the
subquery
resu lts
De
502
Cards and More
713
Cress store
893
All Season Gifts
-
13rows returned In 0.12 se::co::n:.:ds:___:Oo:::::'::::''IJ=loa=d= - - - - - - - - - - - - - - - -_ J
FIGURE 5-24
Performing a difference without using the MINUS operator
Chapter 5
NOTE
Oracle supports the MINUS operator, but SQL Server and Microsoft Access do not.
ALL AND ANY
You can use the ALL and ANY op er ators \Vitl1 subque ries to produce a single colum11 of
11u1nber s. \All1en you precede the subquery by the ALL op er ato r , tl1e conditio11 is true only
if it sa tisfies all values produced by the subqt1ery. \\Then you precede the subquery by
tl1e Ai~ ope ra to r , tl1e condition is t1ue if it satisfies a1iy value (one o r more) produced by
tl1e subquery. The followi11g examples illus trate tl1e use of these ope rato rs.
EXAMPLE 14
Find the ct1stomer number , name, ct1rrent balance, and rep number of each customer
wh ose balance exceeds the maximum balance of all customers represented by sales
rep 30.
Yot1 ca11 fi11d tl1e 1na.xi1nt11n bala11ce of tlle ct1s tom ers re prese11ted by sales r ep 30 i11 a
st1bqt1e ry a11d tl1e11 find all ci1s tom er s \,rl1ose bala nces ar e greater tl1a11 tl1is 11t1mber . Tl1ere
is a11 alternative 1ne tl1od tl1at is simple r , 110\\rever . Yoi1 ca11 t1se the ALL opera to r, as
sh ow11 i11 Figi1re 5-25.
Home
SOL Wor1cshop
~ Autocommil
SQL Commands
!20
Rows
jv
I V ,R
( Save )( Run )
SELECT COSTCMER_NUM, CUSTOMER_NAME, BALANCE, R.EP_t.'llM
FROM CUSTOMER
WHER:;: BJI. LANCE > ALL
(SEL~CT ~.:..?!Ncr
FROM CUSTOMER
WHERE Rf P_NUM = '30 ' );
Results
A LL
operator
p
586
Almondton General Store
3456.75
45
713
Cress Store
4234.6
15
502
Cards and More
5025.75
15
I3 rows returned in 0.00 seconds
FIGURE 5-25
-
Download
SELECT command that uses the ALL operator
To som e t1ser s, the qi1ery show11 in Figure 5-25 might seem m o re n ati1r al tl1an finding
tl1e 1n axi1num balance in the si1bqt1ery. For o tl1er ttser s , tl1e opposite m igl1t be tn1e. You
can t1se wl1icl1ever approach yoi1 prefe r.
Multiple-Table Queries
Question: How would you get the same result for Example 14 without using the ALL
operator?
Answer: You could select each customer whose balance is greater than the maximum
balance of any customer of sales rep 30, as shown in Figure 5-26.
I' Home SOL Worl<shop SQL Commands
~Autocommit
Rows
120
lvl V -?
( Save ) (RurQ
SELEC'I cus: ~_UOM, GUSTO~_~, BAIANCE , RE P_NUM
FROM CUSTOMER
WHERE BAU>JlCE >
(SELECT !ru.: (BALANCE)
FROM CUSTOMER
WHERE REP_NID! a ' 30 ' );
Results
piam
·-
Descnbe Soved SUL t1 story
rr,,;:1 ,~, r.
t Llf
502
Cards and More
5025 75
15
586
Almonctton General Store
3456.75
45
713
Cress Store
4234.6
15
3 rows returned in 0.01 seconds
FIGURE 5-26
Dgwnload
Alternative to using the ALL operator
EXAMPLE 15
Find the customer number, name, current balance, and rep number of eacl1 customer
whose balance is greater than the balance of at least one customer of sales rep 30.
You can find tl1e minim11m balance of tl1e c11stome rs represented by sales rep 3 0 in
a s11bq11ery and tl1e11 find all customers \.vl1ose balance is greater tl1an this 1111mber . To
simplify the process, yo11 can 11se tl1e Al\TY operator , as sl10\.vn in Fig11re 5-27.
Chapter 5
I[
Home
SOL Workshop
~Autocommil
SQL Commands
!2<1
Rows
I
y'"
.(l
( Save
~c
Run )
SELECT CUSTOMER_MIJM, OJSTO!-IER m.ME, BAL.~cr, REP Nm!
fROM CUSTOMER
lilHERE BALA!lCE > ANY
ANY
( SELECT !!A!..<>.NCE
fROM CUSTOMER
operator
WHERE REP !ml!~ ' 30 ' } ;
L
Results
History
502
Cards and More
5025.75
15
713
Cress Store
4234.6
15
586
Almondton General Store
3456.75
45
824
Kline's
2475.99
30
334
The Eveiything Shop
2345 75
45
126
Toys Galore
1210.25
15
893
All Season Gills
935.75
15
386
Johnson's Department Store
879.25
30
665
Crid<et Gift Shop
678.9
30
oown1oa11
9 rows returned in 0.00 seconds
FIGURE 5-27
SELECT command with an ANY operator
Q11estion: I-low would you get the sam e results ,vithout using the ANY operator?
Ans,ver: You could select each customer whose balance is greater than the minimum
balance of any customer of sales rep 30, as shown in Figure 5-28.
Home
SOL Workshop
~ Autocommrl
SQL Commands
!20
Rows
Iv I ff .(l
( Save ) ( Run )
ctJSTOll.Fi\_NIJM, OJSTO~II. NAME, BAL.11JlCE, REP NUM
fROM CUSTO~IER
I SELEC'c
lill!ERE BALA."ICT >
( SEL£CT Hnl (BAIJ.NCE}
fROM CUSTO~IER
lfflt!\E: REP_NOM = ' 30 ' } ;
'iQL
Results
•
ER_NUII
HI t ry
C'USTa.R_NAME
BALANCE
REP_MUM
126
Toys Galore
1210 25
15
334
The Evel)'lhing Shop
2345 75
45
386
Johnson's Department Store
879.25
30
502
Cards and More
5025 75
15
586
Almondton General Store
3456 75
45
665
Crid<et Gift Shop
678.9
30
713
Cress Store
4234_6
15
824
Kline's
2475.99
30
893
All Season Gifts
935.75
15
9 rows returned in 0.00 seconds
FIGURE 5-28
Download
Alternative to using the ANY operator
Multiple-Table Queries
SPECIAL OPERATIONS
You can perforn1 special operations vvithi11 SQL, st1cl1 as the self-joi11 tl1at yot1 already
t1sed. Three other special operations are tl1e inner join, tl1e ot1ter join, and tl1e product.
Inner Join
A joi.11 tl1at co111pares tl1e tables i.11 a FRO NI clat1se ai1d lists 011ly tl1ose rows tl1at satisfy tl1e
co11ditio11 i11 tl1e \\THERE clat1Se is called a11 inner join. The joi11s tl1at yott l1ave perfor1ned
so far i11 tllis text l1ave b ee11 i1u1er joi11s. Exa1nple 16 illt1s trates tl1e i1111er joi11.
EXAMPLE 16
Display the customer number, customer name, order number , and order date for each
order. Sort the results by customer number.
Tllis example reqttires the sam e type of join that yot1 l1ave b een using. Tl1e command is:
SE L E CT CUSTOMER. CUSTOMER NUM, CUSTOMER NAME , ORDER NUM, ORDER DATE
FROM CUSTOMER , ORDERS
WHERE CUSTOMER . CUSTOMER NUM
= ORDERS . CUSTOMER NUM
ORDER BY CUSTOMER. CUSTOMER NUM;
Tl1e previot1s approach sl1ot1ld vvorh. in any SQL implem entation . An ttpdate to tl1e
SQL standard approved in 1992 , called SQL-92 , provides an altern ative vvay of performing
an inne r join, as sh own in Figt1re 5-29.
Home
SOL Worlcshop
~Autocommit
SQL Commands
120
Rows
Iv I ~ .(/
( Save ) ( Run )
SELEC: CUSTOMER.CUSTOMER_ mJM, CUS!OtiER_ NJIME, ORD:'.R_ NUM, OROER_ DA!E
FROM CUSTOMER
INNER JOIN OROE.RS + - - - - - - - - - - - - - - - - - - - <
ON COSI OMER . CUS: O!ER NUM • ORDERS . CUSI OJ-!ER NUM ----,
ORDER BY CUSTOMER. CUSI O!-ER_NUM;
-
Results
-
INN ER JO IN
clause
µ
ON clause
126
Toys Galore
51608
10112/2015
126
Toys Galore
51619
10/15/2015
260
Brookings Direct
51614
10/13/2015
334
The Everything Shop
51610
10/12/2015
386
Johnson's Department Store
5161 3
10/13/2015
586
Almondton General store
51617
10(15/2015
586
Almondton General store
51623
10/15/2015
796
Unique Gifts
51625
10/16/2015
8 rows returned in 0.01 seconds
FIGURE 5-29
Download
-
J
Query that uses an INNER JOIN clause
111 tl1e FROM clause, list the first table, and the11 i11clude a11 INNER JOIN clause tl1at
includes the naine of tl1e second table . I11stead of a \\THERE clause, use an ON clause
contai11it1g the same conditio11 tl1at you would have i11cluded i11 tl1e \\THERE clause.
Chapter 5
Outer Join
Sometimes you need to list all tl1e ro'1\'S from one of the tables ill a joil1, regardless of
whetl1er they matcl1 a11y ro'1vs ill a seco11d table. For exa111ple, you cai1 perform the joi11
of the CUSTOMER a11d ORDERS tables i11 the query for Example 16, but display all
customers-even tl1e 011es '1Vithout orders. This type of joil1 is called an outer join.
Tl1ere are actually tl1ree types of outer jorns. In a left outer join, all ro\ivs from the
table on the left (the table listed first in the qi1ery) ai·e rncluded regardless of '1vhetl1er tl1ey
1natcl1 ro'1vs from tl1e table on tl1e right (the table listed second in the query). Ro\ivs from
tl1e table 011 tl1e rigl1t ai·e rncluded only when they match. In a right outer join, all ro'1\'S
from tl1e table 011 tl1e rigl1t are rncluded regardless of \.\7hetl1er they 1natcl1 ro\ivs from tl1e
table on the left. Ro'1\'S from the table on the left are i11cluded 011ly "''he11 tl1ey 111atcl1. l11 a
full outer join, all rows from both tables are included regardless of whetl1er tl1ey match
rov.rs from the other table. (The full outer join is rai·ely used.)
Exai11ple 17 illus trates the use of a left outer join.
EXAMPLE 17
Display the customer number, customer name, order number, and order date for all
orders. Include all customers in the results. For customers that do not have orders, omit
the order number and order date.
To i11cli1de all ci1stomers, you mi1st perform an oi1ter jorn. Assumit1g tl1e CUSTONIER
table is listed first, tl1e join sl1oi1ld be a left oi1ter join. 111 SQL, yott i1se tl1e LEFT JOIN
clai1se to perfor1n a left outer joi11 as sl10\iv11 in Figi1re 5-30. (Yot1 woi1ld i1se a RIGHT JOIN
clai1se to perfor1n a rigl1t oi1ter jorn.)
Home
SOL Workshop
t?l Autocommit
Rows
SQL Commands
120
Iv I V ~
( Save )( Run )
SELl:C'I CUSTOMER. CUSIOMf:R_NUM, CUSI OMER_ NIL'!E, ORDER_ NUM, OROER_ DAIE
fROM CUSTOMER
:.EFT JOIN ORDER.5- - - - - - - - - - - - - - - - - f
ON CUSIOMER.CUSTOM::R NUM ~ ORDERS.COSIOMER NOM
- OMYR_NUM;
ORDER BY C1JSIOMER. COSI
Results
r
clause
-
story
C
•
•
126
Toys Galore
51608
10/12/2015
126
Toys Galore
51619
10/15/2015
260
Brookings Direct
51614
10/13/2015
334
The Everything Shop
51610
10/12/2015
386
Johnson·s Oepartmenl Store
51613
10/13/2015
440
Grove Hlstorfcal Museum Store
502
Cards and More
586
Almondton General Store
51617
10/ 15/2015
586
Almondton General Store
51623
10/15/2015
665
Cncl<el Gift Shop
713
Cress Store
796
Unique Gifts
51625
10/16/2015
824
Kline's
893
Ail Season Gifts
14 rows returned in 0.01 seconds
FIGURE 5-30
LEFT JOIN
Download
Query that uses a LEFT JOIN clause
Customers
without matching
orders are
also included
Multiple-Table Queries
All customers are incl11ded in tl1e res11lts. For c11stom ers \Vitl1011t o rde rs, the order
n11mber and date are blanh.. Tech11ically, tl1ese blanlr val11es are n11ll.
NOTE
In Oracle, there is another way to perform left and right outer joins. You write the join as you have been
doing, with one exception. You include parentheses and a plus sign in the WHERE clause after the column in the table for which only matching rows are to be included. In this example, the plus sign would
follow the CUSTOMER_NUM column in the ORDERS table because only orders that match customers
are to be included. Because customers that do not have orders are to be included in the results, there is
no plus sign after the CUSTOMER_NUM column in the CUSTOMER table. The correct query is as
follows:
SELECT CUSTOMER . CUSTOMER NUM, CUSTOMER NAME, ORDER NUM, ORDER DATE
FROM CUSTOMER, ORDERS
WHERE CUSTOMER. CUSTOMER NUM
= ORDERS. CUSTOMER NUM ( +)
ORDER BY CUSTOMER. CUSTOMER NUM;
Running this query produces the same results as shown in Figure 5-30.
Product
Tl1e product (formally called tl1e Cartesian product) of t\.\70 ta bles is tl1e combination of all
ro,vs in the first table a11d all rows in the second table.
NOTE
The product operation is not common. You need to be aware of it, however, because it is easy to create
a product inadvertently by omitting the WHERE clause when you are attempting to join tables.
EXAMPLE 18
Form the product of the CUSTOMER and ORDERS tables. Display the customer number
and name from the CUSTOrvIER table, along with the order number and order date from
the ORDERS table.
Forming a product is actually very easy. Yo11 silnply 01nit the WI-IERE cla11se, as
sho\v11 i11 Fig11re 5-31 .
Chapter 5
Home
SOL Workshop
0 Autocomm11
Rows
SQL Commands
; ., I V .r?
[ib
( Save )( Run )
SELECT CUSTOMER.CUSTOMER_~ , CUS!OMER_Nl\..'!E, ORDER_NUM, ORDER DATE
FROM CUSTOMER, ORCE.RS;
sav
Results
No condition
relates the tables
in t he FROM
clause
•
126
Toys Galore
51608
1011212015
260
Brookings Direct
51608
10/1212015
334
The Everything Shop
51608
10/1212015
386
Johnson's Department store
51608
10/1212015
440
Grove Historical Museum Store
51608
10/1212015
502
Cards and More
51608
10/1212015
586
Almondton General store
51608
10/1212015
665
Cricket GIil Shop
51608
1011212015
713
Cress store
51608
10/1212015
796
Unique Gifts
51608
1011212015
824
Kline's
51608
10/1212015
893
All Season Gifts
51608
10/1212015
126
Toys Galore
51610
10/1212015
260
Brookings Direct
51610
10/1212015
334
The Everything Shop
51610
10/1212015
386
Johnson's Department store
51610
10/1212015
FIGURE 5-31
Query that produces a product of two tables
Q11estion: Figure 5-31 does not show all the rows in the result . I-low many rows are
actually included?
Answer: The CUSTOMER table has 10 rows and the ORDERS table has seven rows.
Because each of the 10 custom er rows is match ed with each of the seven order rows,
there are 70 (10 x 7) rows in the result.
Multiple-Table Queries
Chapter Summary
•
To join tables, indicate in the SELECT clause all columns to display, list in the FROM
clause all tables to join, and then include in the WHERE clause any conditions requiring values in matching columns to be equal.
•
When referring to matching columns in different tables, you must qualify the column
names to avoid confusion. You qualify column names using the following format: table
name.column name.
•
Use the IN or EXISTS operators with an appropriate subquery as an alternate way of
performing a join.
•
A subquery can contain another subquery. The innermost subquery is executed first.
•
The name of a table in a FROM clause can be followed by an alias, which is an alternate name for a table. You can use the alias in place of the table name throughout the
SQL command. By using two different aliases for the same table in a single SQL
command, you can join a table to itself.
•
The UNION operator creates a union of two tables (the collection of rows that are in
either or both tables). The INTERSECT operator creates the intersection of two
tables (the collection of rows that are in both tables). The MINUS operator creates
the difference of two tables (the collection of rows that are in the first table but not
in the second table). To perform any of these operations, the tables involved must
be union compatible. Two tables are union compatible when they have the same
number of columns and their corresponding columns have identical data types and
lengths.
•
When the ALL operator precedes a subquery, the condition is true only if it is satisfied
by all values produced by the subquery.
•
When the ANY operator precedes a subquery, the condition is true if it is satisfied by
any value (one or more) produced by the subquery.
•
In an inner join, only matching rows from both tables are included. You can use the
INNER JOIN clause to perform an inner join.
•
In a left outer join, all rows from the table on the left (the table listed first in the query)
are included regard less of whether they match rows from the table on the right (the
table listed second in the query). Rows from the table on the right are included only
when they match. You can use the LEFT JOIN clause to perform a left outer join. In a
right outer join, all rows from the table on the right are included regardless of whether
they match rows from the table on the left. Rows from the table on the left are
included only when they match. You can use the RIGHT JOIN clause to perform a
right outer join.
•
The product (Cartesian product) of two tables is the combination of all rows in the first
table and all rows in the second table. To form a product of two tables, include both
tables in the FROM clause and omit the WHERE clause.
Chapter 5
Key Terms
. .
alias
ALL
JOln
left outer join
ANY
MINUS
Cartesian product
nested subquery
correlated subquery
outer join
difference
product
EXISTS
right outer join
self-join
full outer join
.
..
•
inner 101n
union
INTERSECT
UNION
intersection
union compatible
Review Questions
1. How do you join tables in SOL?
2. When must you qualify names in SOL commands? How do you qualify a column name?
3. List two operators that you can use with subqueries as an alternate way of performing joins.
4. What is a nested subquery? In which order does SOL evaluate nested subqueries?
5. What is an alias? How do you specify an alias in SOL? How do you use an alias?
6. How do you join a table to itself in SOL?
7. How do you take the union of two tables in SOL? How do you take the intersection of
two tables in SOL? How do you take the difference of two tables in SOL? Are there any
restrictions on the tables when performing any of these operations?
8. What does it mean for two tables to be union compatible?
9. How do you use the ALL operator with a subquery?
10. How do you use the ANY operator with a subquery?
11 . Which rows are included in an inner join? What clause can you use to perform an inner join
in SOL?
12. Which rows are included in a left outer join? What clause can you use to perform a left
outer join in SOL?
13. Which rows are included in a right outer join? What clause can you use to perform a right
outer join in SOL?
14. What is the formal name for the product of two tables? How do you form a product in SOL?
C RITICAL
TH INKING
15. Use the Internet to find definitions for the terms equi-join, natural join, and cross join.
Write a short report that identifies how these terms relate to the terms join, inner join, and
Cartesian product. Be sure to reference your online sources properly.
Multiple-Table Queries
CRITICAL
TH INKING
16. Use the Internet to find information on cost-based query optimizers. Write a short report that
explains how cost-based query optimization works, and what type(s) of queries benefit the
most from cost-based query optimization. Be sure to reference your online sources
properly.
Exercises
T AL Distributors
Use SOL and the TAL Distributors database (see Figure 1-2 in Chapter 1) to complete the
following exercises. If directed to do so by your instructor, use the information provided with
the Chapter 3 Exercises to print your output or save it to a document.
1. For each order, list the order number and order date along with the number and name of
the customer that placed the order.
2. For each order placed on October 15, 2015, list the order number along with the number
and name of the customer that placed the order.
3. For each order, list the order number, order date, item number, number of units ordered,
and quoted price for each order line that makes up the order.
4. Use the IN operator to find the number and name of each customer that placed an order
on October 15, 2015.
5. Repeat Exercise 4, but this time use the EXISTS operator in your answer.
6. Find the number and name of each customer that did not place an order on October 15, 2015.
7. For each order, list the order number, order date, item number, description, and category
for each item that makes up the order.
8. Repeat Exercise 7, but this time order the rows by category and then by order number.
9. Use a subquery to find the rep number, last name, and first name of each sales rep who
represents at least one customer with a credit limit of $10,000. List each sales rep only
once in the results.
10. Repeat Exercise 9, but this time do not use a subquery.
11. Find the number and name of each customer that currently has an order on file for a
Rocking Horse.
12. List the item number, description, and category for each pair of items that are in the same
category. (For example, one such pair would be item CD33 and item DL51 , because the
category for both items is TOY.)
13. List the order number and order date for each order placed by the customer named
Johnson's Department Store. (Hint: To enter an apostrophe (single quotation mark) within
a string of characters, type two single quotation marks.)
14. List the order number and order date for each order that contains an order line for a Fire
Engine.
Chapter 5
15. List the order number and order date for each order that either was placed by Almondton
General Store or that contains an order line for a Fire Engine.
16. List the order number and order date for each order that was placed by Almondton
General Store and that contains an order line for a Fire Engine.
17. List the order number and order date for each order that was placed by Almondton
General Store but that does not contain an order line for a Fire Engine.
18. List the item number, description, unit price, and category for each item that has a unit
price greater than the unit price of every item in category GME. Use either the ALL or
ANY operator in your query. (Hint: Make sure you select the correct operator.)
19. For each item, list the item number, description, units on hand, order number, and number
of units ordered. All items should be included in the results. For those items that are currently not on order, the order number and number of units ordered should be left blank.
Order the results by item number.
C RITICAL
TH INKING
C RITICAL
TH INKING
20. If you used ALL in Exercise 18, repeat the exercise using ANY. If you used ANY, repeat
the exercise using ALL, and then run the new command. What question does the new
command answer?
21 . For each rep , list the customer number, customer name, rep last name, and rep first
name. All reps should be included in the results. Order the results by rep number. There
are two SOL commands for this query that will list the same results. Create and run each
SOL command.
Colonial Adventure Tours
Use SOL and the Colonial Adventure Tours database (see Figures 1-4 through 1-8 in
Chapter 1) to complete the following exercises. If directed to do so by your instructor, use
the information provided with the Chapter 3 Exercises to print your output or save it to a
document.
1. For each reservation , list the reservation ID, trip ID, customer number, and customer last
name. Order the results by customer last name.
2. For each reservation for customer Ryan Goff, list the reservation ID, trip ID, and number
of persons.
3. List the trip name of each trip that has Miles Abrams as a guide.
4. List the trip name of each trip that has the type Biking and that has Rita Boyers as a
guide.
5. For each reservation that has a trip date of July 23, 2016, list the customer's last name,
the trip name, and the start location.
6. List the reservation ID, trip ID, and trip date for reservations for a trip in Maine (ME).
Use the IN operator in your query.
7. Repeat Exercise 6, but this time use the EXISTS operator in your query.
8. Find the guide last name and guide first name of all guides who can lead a paddling trip.
(Note : The query results should include duplicate values.)
Multiple-Table Queries
9. Repeat Exercise 8 but use aliases for the table names.
10. List the trip IDs and trip names for each pair of trips that have the same start location.
(For example, one such pair would be trip ID 2 and trip ID 3, because the start location of
both trips is Weathersfield .) The first trip ID listed should be the major sort key, and the
second trip ID should be the minor sort key.
11 . Find the trip name of all reservations for hiking trips and sort the results by trip name in
ascending order.
12. List the number and name of each customer that either lives in the state of New Jersey
(NJ), or that currently has a reservation, or both.
13. List the number and name of each customer that lives in the state of New Jersey (NJ) and
that currently has a reservation.
14. Find the trip ID and trip name for each trip whose maximum group size is greater than the
maximum group size of every trip that has the type Hiking.
15. Find the trip ID and trip name for each trip whose maximum group size is greater than the
maximum group size of at least one trip that has the type Biking.
16. Display the trip ID, trip name, and reservation ID for all trips. All trips should be included in
the result. For those trips that currently do not have reservations, the reservation ID
should be left blank. Order the results by trip ID.
CRITICAL
THINKING
17. Repeat Exercise 8 but list the guide name only once and sort the guide names in order by
last name.
C RITICAL
THINKING
18. Repeat Exercise 10, but this time list only hiking trips in the state of New Hampshire (NH),
list each trip only once, and sort the results in descending order by trip name.
Solmaris Condominium Group
Use SOL and the Solmaris Condominium Group database (see Figures 1-9 through 1-13 in
Chapter 1) to complete the following exercises. If directed to do so by your instructor, use the
information provided with the Chapter 3 Exercises to print your output or save it to a document.
1. For every condo , list the location number, unit number, condo fee, owner number, owner's
first name, and owner's last name.
2. For every completed or open service request for janitorial work, list the condo ID, description, and status.
3. For every service request for janitorial work, list the condo ID, location number, unit number, estimated hours, spent hours, owner number, and owner's last name.
4. List the first and last names of all owners who have a three-bedroom condo. Use the IN
operator in your query.
5. Repeat Exercise 4, but this time use the EXISTS operator in your query.
6. List the unit numbers of any pair of condos that have the same square footage. For
example, one pair would be unit number 201 and unit number 401 , because the square
footage for both units is 1,030 square feet. The first unit number listed should be the
major sort key and the second unit number should be the minor sort key.
Chapter 5
7. List the square footage, owner number, owner last name, and owner first name for each
condo in location number 1.
8. Repeat Exercise 7, but this time include only those condos with three bedrooms.
9. List the location number, unit number, and condo fee for condos whose owners live in
Bowton or own one-bedroom condos.
10. List the location number, unit number, and condo fee for condos whose owners live
in Bowton and own a one-bedroom condo.
11 . List the location number, unit number, and condo fee for condos whose owners live in
Bowton but do not own one-bedroom condos.
12. Find the service ID and condo ID for each service request whose estimated hours is
greater than the number of estimated hours of at least one service request on which the
category number is 5.
13. Find the service ID and condo ID for each service request whose estimated hours is
greater than the number of estimated hours on every service request on which the
category number is 5.
14. List the condo ID, square footage, owner number, service ID, number of estimated hours,
and number of spent hours for each service request on which the category number is 4.
15. Repeat Exercise 14, but this time be sure each condo is included regardless of whether
the condo currently has any service requests for category 4.
C RITICAL
TH INKING
16. Repeat Exercise 15 using a different SOL command to obtain the same result. What is
the difference between the two commands?
C H A PTER
UPDATING DATA
OBJECTIVES
•
Create a new table from an existing table
•
Change data using the UPDATE command
•
Add new data using the INS ERT command
•
Delete data using the DELETE command
•
Use nulls in an UPDATE command
•
Change the structure of an existing table
•
Use the COMMIT and ROLLBACK commands to make permanent data
updates or to reverse updates
•
Understand transactions and the role of COMMIT and ROLLBACK in
supporting transactions
•
Drop a table
INTRODUCTION
In this chapter, you will learn how to create a new table from an existing table and make changes to
the data in a table. You will use the UPDATE command to change data in one or more rows in a
table, and use the INS ERT command to add new rows . You will use the DELETE command to delete
rows. You will learn how to change the structure of a table in a variety of ways and use nulls in
update operations. You will use the COMMIT command to make changes permanent and use the
ROLLBACK command to undo changes, and understand how to use these commands in transactions. Finally, you will learn how to delete a table and its data.
CREATING A NEW TABLE FROM AN EXISTING TABLE
Yot1 ca11 create a 11e,v table usi11g data i11 a11 existi11g table, as illt1strated i11 tl1e followi11g
exa111ples.
EXAMPLE 1
Create a new table na.m ed LEVELl_CUSTOMER that contains the following columns from
the CUSTOMER table: CUSTOivIER_NUM, CUSTOMER_N~~1E, BALANCE, CREDIT_LIMIT,
and REP_NUM. The columns in the new LEVELl_CUSTOMER table should have the same
cha racteristics as the corresponding columns in the CUSTOMER table.
Chapter 6
Yot1 describe the 11e,,, table 11a111ed LEVELl_CUSTOMER by t1sing tl1e CREATE TABLE
com1na11d show11 i11 Figt1re 6-1 .
ORACLE' Application Express
Home
SQL Workshop
&?lAutocommit
Rows
SQL Commands
po
! v IV ,R
( Save )( Run )
CREATE I:P.B:.E LEVELl CUSTOMER - - - - - - - - - - - - - !
(CUSTOMER ~ CBJ!...R(3) PRIMARY KEY,
cusroMER_NAME CBAR(35l,
BALANCE D~CIMi\I.(8,2),
CREDII_LIMIT llECll-!AI.(8,2),
REP_NOM CRAR ( 2)
);
Table to ,._.__,
create
Table
structure
0.02 seconds
FIGURE 6-1
Creating the LEVEL 1_CUSTOMER table
ACCESS
USER
NOTE
If you are using Access to create the LEVEL1_CUSTOMER table, use the CURRENCY data type
instead of the DECIMAL data type for the BALANCE and CREDIT_LIMIT fields. (Access does not
support the DECIMAL data type.) You do not need to enter the field size and number of decimal
places when using the CURRENCY data type.
EXAMPLE 2
Insert into the LEVELl_CUSTOMER table the customer number, customer name,
balance, credit limit, and rep number for customers with credit limits of $7,500.
Yot1 can create a SELECT command to select the desired data from tl1e CUS'fOMER
table , jt1st as yot1 did in Cl1apter 4. By placing this SELECT command in an INSERT
command, yot1 can add the qt1ery results to a table. Tl1e INSER'f command appears in
Figt1re 6-2; tllis command inserts six ro,vs i11to tl1e LEVELl_CUS'f ONIER table.
Updating Data
Home
SOL Worksh01>
li'.! Autocommft
SQL Commands
Rows
[10
,v I
V .(/
( Save )( Run )
INSERT INTO LEVELl CUSTOMER
SELEC'I CUSTOMER_NUM, CUSTOMER_~, BAI.i\.NCE, CREDI'::_LIMII, REP_NU!~
fROM CUSTOMER
~
-----i
QHERE CREDIT L!"MIT = 7S00:
SELECT command
retrieves the data
to insert
n Des
Results
6 row( s ) i nsened.
0.01 seconds
FIGURE 6-2
INSERT command to add data to the LEVEL 1 CUSTOMER table
Tl1e SELECT command sl10\.vn in Fig11re 6-3 displays tl1e data i11 tl1e
LE\TELl_CUSTOMER table. Notice tl1at tl1e data comes from the new table yo11 j11st
created (LE\TELl_CUSTOMER), and not from the CUSTONIER table .
Home
SOL Workshop
0 Autocommit
Rows
SQL Commands
Qo
Iv I V ~
( Save ) ( Run )
SELECT *
FROM U:V-tl.1_cos: ol!!'..R;
Results
126
Toys Galore
334
386
The Everything Shop
Johnson's Department Store
1210.25
2345.75
879.25
665
Cricket Giff Shop
796
893
Unique Gifts
All Season Gills
6 rows returned in 0.01 seconds
FIGURE 6-3
7500
678.9
7500
7500
7500
15
45
30
30
124.75
935.75
7500
7500
45
15
Download
LEVEL1 CUSTOMER data
CHANGING EXISTING DATA IN A TABLE
Tl1e data stored it1 tables is s11bject to consta11t cha11ge; prices, addresses, commission
amounts, and otl1er data in a database cha11ge on a reg11lar basis. To keep data curre11t,
yot1 must be able to make these cl1anges to tl1e data in your tables. Yo11 ca11 11se the
UPDATE co1nmand to change ro\.vs for \.Vhicl1 a specific conditio11 is tn1e.
EXAMPLE 3
Change the name of customer 796 in the LEVELl_CUSTOMER table to "Unique Gifts
and Toys."
Chapter 6
Tl1e forma t for tl1e UPDATE co1n m and is tl1e word UPDATE, follo\ved by the 11ame of
tl1e ta ble to be updated . Tl1e next portion of tl1e corrunand consists of tl1e word SET, follo\.ved by the name of the col11mn to be 11pda ted , an equals s ign, ru1d the 11e\v val11e. V.Then
11ecessa1y, incl11de a \\THERE cla11se to indicate tl1e rovv(s) on "''hicl1 tl1e cl1ange is to
occur. Tl1e UPDATE con1mand sl10\.\7n in Fig11re 6-4 cl1anges the n ame of cus tom e r 796 to
U11iq11e Gifts and Toys.
Home
SQL Workshop
Ell Autocomm11
SQt Commands
110
Rows
lvl V .?
( Save )( Run )
UPDAIT LEVELl CUSTOMER
SET CUSTOMER till.ME = ' Unique G:.fi:s and Toy!! '
WHERE CUSTOMER_NOM = '796';
Results
-
nllc savecJ sat
1n •
H1 t rv
---'
1 r ow (!! ) up d a&ed .
0.01 seconds
FIGURE 6-4
UPDATE com mand to change the name of customer 796
Tl1e SELECT con1ma11d sl10\.v11 i11 Fig11re 6-5 sh ows tl1e da ta i11 tl1e table afte r the
cl1a11ge l1as bee11 111ade . It is a good id ea to 11se a SELECT co1111na11d to display the da ta.
yo11 cl1a11ged to verify tl1at tl1e co rrect 11pda te wa.s 111ad e .
Home
SQL Workshop
0 Autocommil
SQL Commands
jtli
Rows
Iv l V ,?
( Save )( Run )
SEU:Ci *
FROM :.EVE:Ll_CUSIO~;
Results
p ,
126
334
386
665
796
893
De
no
Toys Galore
Unique Gifts and Toys
1210.25
2345.75
879.25
678.9
124.75
All Season Gifts
935.75
The Everything Shop
Johnson's Oepartmen1 S1ore
Cricket Giff Shop
6 rows returned in 0.00 seconds
FIGURE 6-5
Hbl ry
Downlqag
7500
7500
7500
7500
7500
7500
15
45
30
-
30
45
15
LEVEL 1_CUSTOMER table after update
EXAMPLE 4
For each customer in the LEVELl_CUSTOMER table that is represented b)' sales rep 45
and has a balance over $2,000, increase the customer's credit limit to $8,000.
Updating Data
Tl1e 01tly diffe ren ce between Examples 3 and 4 is that Example 4 ttses a compottnd
condition to ide11tify tl1e ro\.v(s) to be ch anged . The UPDATE command appears in
Figt1re 6-6.
Home
SOL Workshop
6Zl Autocommit
SQL Commands
1-- I V ~
1<0
Rows
( Save ; ( Run )
OPOiUE LEVELl CUSTOMER
SET CREDIT LIMIT =8000
WHERE REP NUM = '45'
AND BAIANCE > 2000;
Results
~
piam
scrm
-
-
Saved SQL
History
l row( s ) updaced.
I
0.00 seconds
-
FIGURE 6-6
Using a compound condition in an update
Tl1e SELECT comma11d sho\.,,n in Figure 6-7 sho\.\'S the table afte r the update.
Home
SOL Workshop
6Zl Autocommil
Rows
SQL Commands
[to
I" I V ~
( Save ; ( Run )
SELECT *
fROM l.EVELl_CUSTOMER;
Results
l
p
126
Toys Galore
1210_25
7500
15
334
The Everything Shop
2345_75
8000
45
386
Johnson's Department Store
879.25
7500
30
665
Cricket Gift Shop
678_9
7500
30
Unique Gifts and Toys
124.75
7500
45
All Season Gifts
935.75
7500
15
796
893
6 rows returned in O 00 seconds
FIGURE 6-7
oown1oad
Credit limit increased for customer number 334
Yott also can ttse tl1e existi11g valtte in a colttmn and a calct1latio11 to ttpdate a value.
For example, \.Vl1en yott need to increase tl1e credit limit by 10 percent instead of cl1anging it to a specific valtte, yott can multiply tl1e existing c redit limit by 1 .10. The follo\.ving
SET clat1se mal{es tllis ch ange:
SET CREDIT LIMIT = CREDIT LIMIT * 1 . 10
ADDING NEW ROWS TO AN EXISTING TABLE
111 Cl1apte r 3, you ttsed tl1e INSERT command to add tl1e initial rows to the tables in tl1e
database. You also can ttse tl1e INSERT command to add additional rows to tables.
Chapter 6
EXAMPLE 5
Add customer number 907 to the LEVELl CUSTOMER table. The name is Glenn's
British Toys, the balance is zero, the credit limit is $7,500, and the rep number is 45.
Tl1e appropriate INSERT command is sl10\>vn in Fig11re 6-8. Because tl1e name
"Glenn's Britisl1 'f oys" contains an apostrophe, yo11 typ e t\>vo single q11otation marlts to
create tl1e apostrophe.
Home
SOL Workshop
0Autocommil
Rows
SQL Commands
1v I
j10
V .P
( Save ) ( Run )
INSER! !N!O 1£VEL1 COS!OMER
VALUES
( ' 907', •~l~!lJI• • ~ 3riri3h Toy3', 0 , 7S00, '45'): -
p II n
Results
s
---1
Values for
new row
S V d Q
1 row( s ) inse~red.
0.00 seconds
FIGURE 6-8
Inserting a row
Tl1e SELECT co111111and in Fig11re 6-9 sh ows that the ro\>v \>Vas successftilly add ed .
Home
SOL Wortcshop
0Autocommit
Rows
SQL Commands
!10
1v
IV .P
( Save ) ( Run )
SE.I.EC! •
fROM LEV.:Ll_CCJSTOMER;
Results
~
n
I
907
Glenn's Bmish Toys
126
334
Toys Galore
386
Johnson's Department Store
665
796
Cricket Gift Shop
879.25
678.9
Unique Gifts and Toys
124.75
893
All Season Gifts
935.75
The Everything Shop
7 rows returned in 0.00 seconds
FIGURE 6-9
0
1210.25
2345.75
7500
7500
8000
7500
7500
7500
7500
45
15
45
30
30
45
15
Download
Customer 907 added to LEVEL 1 CUSTOMER table
NOTE
Your output might be sorted in a different order from what is shown in Figure 6-9. If you need to sort the
rows in a specific order, use an ORDER BY clause with the desired sort key(s).
Updating Data
AUTOCOMMIT, COMMIT, AND ROLLBACK
Autocommit is tl1e defaitlt update mode and commits (1nal{es perma11e11t) eacl1 action
q11ery (INSERT, UPDATE , DELETE) as soon as tl1e 11ser exec11tes tl1e q11ery. Altl1011gl1 the
A11tocommit 1node is fine for most action queries, tl1ere are times \.\rl1en the user needs
better control over \.Vl1e11 a transaction is committed. Tl1is is partic11larly important in
m11lti-11ser database applications \.Vl1en more tl1an 011e perso11 cru1 11pdate tl1e database and
in applicatio11s \.Vl1e11 11sers are n11ming script files tl1at contain m11ltiple 11pdates. \iVl1en
yo11 need more control over wl1e11 transactions are co1nmitted, you sl1owd disable tl1e
Autocommit featt1re by clearing its cl1ecl{ box before executing a q11ery.
If yo11 disable the At1tocom1nit feat11re, q11eries tl1at incl11de 11pdates to table data are
only temporary a11d you can reverse (cancel) tl1em at any time during yo11r ct1rrent \.Vorl{
session. Updates become permanent a11tomatically wl1e11 you exit from tl1e DBMS. If you
are 11ot 11sing A11tocommit during your curre11t worl{ session, l1owever, yo11 can still
commit (per1nanently save yo11r cl1anges) by executing the CONIMIT command.
If yo11 decide that yo11 do not want to save tl1e cl1anges yo11 l1ave 1nade duri11g yo11r
c11rrent worl{ session, yo11 can roll bacli (reverse) the cl1anges by executing tl1e
ROLLBACK com1nand. A11y 11pdates made since yo11 ran the most recent COMMIT
command will be reversed \.\'l1en yo11 n111 tl1e ROLLBACI( command. If yo11 l1ave not ru11
tl1e COMJ.VIIT com1nand at all d11ring yo11r session, executing tl1e ROLLBACI( command
will reverse all 11pdates made during the session. Yo11 sho11ld 11ote that tl1e ROLLBACI(
command only reverses cha11ges made to tl1e data ; it does not reverse changes made to a
table's st1uct11re. For example, if yo11 cl1ange tl1e length of a cl1aracter col11mn, you cannot
11se the ROLLBACI( command to ret11rn tl1e col11111n le11gtl1 to its original state.
If yo11 determine tl1at an 11pdate \.Vas made incorrectly, yo11 ca11 11se tl1e ROLLBACI(
command to return tl1e data to its original state. If, on tl1e otl1er l1and, yo11 l1ave verified
tl1at tl1e update yo11 111ade is correct, yo11 ca11 11se the COMMIT conunand to make the
update permru1ent. You do tllis by typing CONTh1IIT after running tl1e 11pdate. Ho\\rever,
yo11 sl1011ld note tl1at the CONIM IT command is pern1anent; after exec11ting a COMNIIT
com1nand, 1umling tl1e ROLLBACI( command ca11not reverse the 11pdate.
ACCESS
USER
NOTE
Access does not support the COMM IT or ROLLBACK commands.
SQL SERVER
USER
NOTE
In SOL Server, the commands used to commit and roll back data are COMMIT TRANSACTION
and ROLLBACK TRANSACTION . By default, SOL Server is in Autocommit transaction mode. To
turn off the Autocommit feature in SOL Server Management Studio, select Options on the Tools menu,
select Query Execution, SOL Server, ANSI in the Options dialog box, place a check mark in the
SET IMPLICIT_TRANSACTION check box, and then click the OK button. To tum on Autocommit mode,
remove the check mark.
Chapter 6
TRANSACTIONS
A transaction is a logical t1nit of \.Vorlr. Yot1 can thin!{ of a transactio n as a seqt1en ce of
steps tl1at accomplisl1 a single taslr. Wl1en discussing transaction s, it is essential tl1at the
e11tire seqt1en ce be comple ted st1ccessft1lly.
For example, to enter an order , yot1 mt1st add tl1e corresponding order to tl1e
ORDERS table, and tl1en add eacl1 order lit1e in tl1e orde r to tl1e ORDER_LINE table.
Tl1ese mt1ltiple ste ps accomplish the sirigle taslr of ente ring an order . St1ppose you have
added tl1e order and tl1e first order line, bt1t yot1 are unable to enter tl1e seco11d order lit1e
for som e reason ; p erhaps tl1e item 011 tl1e orde r lit1e does 11ot exist . Tl1is problem \.\'Ottld
leave tl1e order in a partially ente red s tate, \\rl1icl1 is unacceptable. To prevent thls problem , yot1 wot1ld exect1te a rollbaclr, tl1t1s reversit1g tl1e insertion of tl1e order and the first
order line.
Yot1 can use tl1e CONlwlIT and ROLLBACI( commands to st1pport transaction s as
follo\.\rs:
•
•
•
Before begi11ning tl1e t1pdates for a transaction, commit any previot1s t1pdates
by exect1ti11g the COMMIT command.
Comple te tl1e t1pdates for tl1e tran saction. If a11y t1pdate ca1111o t be completed ,
ex ect1te tl1e ROLLBACI( command and discontint1e tl1e updates for tl1e ct1rrent transaction .
If yot1 ca11 comple te all updates su ccessft1lly, execute the CONINII T command
after completing tl1e fit1al t1pdate.
CHANGING AND DELETING EXISTING ROWS
NOTE
Because the following illustrate the use of the ROLLBACK command, the Autocommit feature must be
turned off. That is, the check mark must be removed from the Autocommit check box. If Autocommit
were still turned on, every update would be committed automatically as soon as it was performed, and
ROLLBACK would have no effect.
As you learned i11 Cl1apter 3, yot1 t1se tl1e DELETE co1nn1and to rem ove r o\.vs from a table.
lt1 Example 6, you will change data and the11 t1se tl1e DELETE co1nmand to delete a ct1stom er from tl1e LEVELl_CUST011ER table. In Example 7 , yot1 will execute a r ollback to
reverse tl1e t1pdates made it1 Exan1ple 6. In this case, the rollback \.Vill re turn tl1e ro\.V to its
previous state and reit1state the dele ted record.
EXAMPLE 6
In the LEVELl_CUSTOMER table, change the name of customer 665 to "Cricket Toy
Shop," and then delete customer 893.
Updating Data
Tl1e firs t part of Example 6 reqttests a name change for ct1stome r 665; the cotrunand
sl1own in Figi1re 6-10 mal{es this cl1a11ge. Note tl1at i11 Figi1re 6-10, tl1e ttser cleared tl1e
cl1ecl{ m arl{ from the At1tocommit cl1ecl{ box before n1nning the query.
Check mark removed
from Autocommit
check box
Home
SOL Workshop
SQL Commands
Rows
Autocommit
Iv IV ~
j10
( Save ) ( Run .)
-
UPDATE L!:7/ELl CUSTOMER
SEI CUSIOMER_NJI.ME = 'Crickec Toy Shop'
iIBER£ CUSTOMER_NUlf = ' 665 ' ;
Resutts
1 row(s) updaced.
0.03 seconds
Using an UPDATE command to change the name of customer 665
FIGURE 6-10
Tl1e second part of Example 6 reqttires dele ting cus tomer 8 93; tl1is command is
sl1ow11 in Figure 6-11. T o dele te d ata from the database, use tl1e DELETE com n1a11d . Tl1e
forma t for the DELETE com n1a11d is the v.ro rd DELETE followed by tl1e name of the table
from wllich the ro\.v(s) is to be dele ted . Next, 1.1se a Wl-IERE clat1se witl1 a condition to
select the r ow(s) to dele te. All rows satisfying tl1e condition will be dele ted .
Home
SOL Workshop
0 Autocommfl
Rows
SOL Commands
~
'"IV~
( Save ) ( Run )
OEU:.TE FROM LE.VELl CUSTOMER
lfflERE CUSTOME.R_NUM = '893';
Resutts
. ..
--~·-
--
:)l!Ved SUL
History
1 row (3) deleced.
0.00 seconds
FIGURE 6-11
Using a DELETE command to delete customer 893
Tl1e co1n1na nd s l10\.vn in Figure 6-12 displays tl1e d ata in the table, verifying the
ch a11ge and the dele tio11.
Chapter 6
Home
SOL Worl<sho!>
D Autocommil
SQL Commands
1
!to
Rows
..,
I V ,!?
( Save )( Run )
SELECT+
FROM LEV=:Ll_cus: OMER;
Results -
HI I ry
save SQL
I
907
Glenn's British Toys
0
7500
45
126
Toys Galore
The Everything Shop
386
Johnson's Department store
879.25
7500
8000
7500
15
334
1210 25
2345 75
45
30
665
796
Cricket Toy Shop
678.9
124.75
7500
7500
30
45
Unique Gifts and Toys
6 rows returned in O00 seconds
FIGURE 6-12
Resu lts of update and delete
Q11estion: What happens ,vhen you run a DELETE command that does not contain a
WI-IERE clause?
Ans,ver: Without a condition to specify which row(s) to delete, the query will delete all
rows from the table.
Executing a Rollback
Tl1e follo\J\7ing example executes a rollbaclr.
'
EXAMPLE 7
Execute a rollback and then display the data in the LEVELl_CUSTOMER table.
To exect1te a rollback, run the ROLLBACI( command, as sl1own in Figt1re 6-13.
RO LLBACK command
reverses all changes
since last COMM IT
Home
SOL Worlcshop
D Autocommit
Rows
SQL Commands
[lo
Iv IV ,!?
( Save ) ( Run )
ROLLBACK; _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __,
Results
s.atement processed.
0.03 seconds
FIGURE 6-13
Executing a rollback
Updating Data
Fig11re 6-14 shows a SELECT command for the LEVELl_CUSTOMER table after execttting tl1e rollbaclr. Notice that the name of c11stomer 665 l1as reverted to Criclret Gift
Sl1op and the row for c11sto1ner 893 l1as been reinstated. All ttpdates made prior to tl1e
previotts commit are still reflected in tl1e data.
Home
SQL WoJ1c;hop
D Autocommit
SQL Commands
Rows
I" I '1 ,?
110
( Save )( Run
SELECT •
f'ROM LEV""t.Ll_ CUS!Ol4ER;
Results
p
n
J
Customer name
before update
History
•
907
126
334
Glenn's British oys
Toys Galore
The Every1hin Shop
Johnson's Oep rtment Store
0
1210.25
2345.75
879.25
386
665
Cricket Gilt Shop
796
Unique Gilts and Toys
678.9
124.75
893
All Season Gifts
935.75
7500
45
7500
8000
15
45
7500
7500
30
30
7500
7500
45
15
7 rows returned in 0.01 seconds
FIGURE 6-14
Deleted row
re instated
Data in the LEVEL 1_CUSTOMER table after executing a rollback
ACCESS
USER
NOTE
If you are using Access to complete these steps, you will not be able to execute the ROLLBACK command. Consequently, your data for the remaining examples in this chapter will differ slightly from the
data shown in the figures-customer 665 will be named Cricket Toy Shop and customer 893 will not be
included.
NOTE
In the remaining examples in this chapter, the Autocommit feature is enabled, that is, there is a check
mark in the Autocommit check box. All updates are committed immediately without requiring any special
action on your part. In addition, it will no longer be possible to roll back updates.
CHANGING A VALUE IN A COLUMN TO NULL
Tl1ere are some special iss11es involved \.Vhen dealing wi tl1 nulls. Yot1 already l1ave seen
l1ow to add a row in wl1ich some of the values are nttll and 110\.\7 to select rows in \.\7hicl1 a
give11 col11mn is n11ll. You also 1nus t be able to cl1a11ge tl1e val11e in a col111ru1 in a11 existing
ro\.\7 to 1111ll, as sl10\.vn in Example 8. Re1nember tl1at to make tllis type of cl1ange, tl1e
affected colurm1 m11st accept n11lls. If you specified NOT NULL for the col11mn when yo11
created tl1e table , tl1en cl1anging a val11e i11 a column to 111111 is prollibited.
Chapter 6
EXAMPLE 8
Change the balance of customer 665 in the LEVELl_CUSTOMER table to null.
Tl1e command for cl1anging a value in a coluID11 to null is exactly \\7l1at it vvoitld be for
cha11ging a11y other vali1e. You sin1ply i1se the vali1e NULL as tl1e replacement value, as
show11 in Figure 6-15. Notice tl1at tl1e value NULL is not enclosed in siI1gle qi1otatio11
1narks. If it v\7ere, tl1e cominand \\70t1ld cl1ange tl1e balance to tl1e word NULL.
I
Home
SQL Commands
SQL Workshop
0 Autocommil
Rows
l--lV .f
110
( Save ) ( Run )
UPDATE L.."V'E:Ll CUSTOMER
,, Changes the "
I
value to nul l
SET llllI llNCT • -trn 'i<HL'IE CUSTOMER_NUM e '665' ;
-
Results
nbe
n-.n
~vrd SQL History
1 row(s) updac~d .
0.01 seconds
FIGURE 6-15
Changing a value in a column to null
Figi1re 6-16 sho\\'S tl1e data in the LEVELl_CUS'f OMER table after changing tl1e
BALANCE coli1mn vali1e for ci1stomer 665 to ni1ll. In Ora.c le llg, a ni1ll vali1e is
displayed as a hyphen , as sl1ovvn in Figi1re 6-16.
I' Home SOL Workshop SQL Commands
E21Autocommit
110
Rows
"1 V #
( Save )( Run )
SELEC: *
fROM ::.:EV!:Ll_CUSTOMER;
907
Glenn's Bnllsh Toys
0
7500
45
126
334
Toys Galore
The Everything Shop
1210.25
2345.75
7500
8000
15
45
386
Johnson's Department Store
879.25
30
665
796
Cricket Gift Shop
7500
7500
Unique Gifts and Toys
124.75
7500
893
All Season Gifts
935.75
7500
7 rows returned in 0.00 seconds
FIGURE 6-16
30
45
15
Download
BALANCE column for customer 665 is null
Updating Data
SQL SERVER
USER
NOTE
In SOL Server, the word "NULL" appears in the results when a column contains a null value.
CHANGING A TABLE'S STRUCTURE
One of tl1e most t1seful features of a relational DBMS is tl1e ease \.Vitl1 \.Vl1icl1 yot.1 ca11
cl1ange table s tri1ctures. In addition to addi11g ne\.v tables to tl1e database and deleting
tables tha t are 110 longer required, yot.1 can add new coli1mns to a table and change tl1e
physical cl1aracteristics of existi11g coli1m11s. Next, yot.1 will see l1ow to accomplisl1 tl1ese
cl1anges.
Yott can cl1ru1ge a table's stri1cti1re in SQL by using the ALTER TABLE command, as
illi1strated in tl1e following examples.
EXAMPLE 9
TAL Distributors decides to maintain a customer type for each customer in the
database. These types are R for regular customers, D for distributors, and S for special
customers. Add this information in a n ew column named CUSTONIER T\'PE in the
LEVELl CUSTOMER table.
To add a nev.r colt1rm1, tise tl1e ADD clause of tl1e ALTER TABLE co111ma11d. Tl1e format fo r tl1e ALTER TABLE co111ma11d is tl1e "''ords ALTER TABLE followed by tl1e 11a1ne of
tl1e table to be altered a11d a11 appropriate cla u se. Tl1e ADD clatise co11sists of tl1e \.Vord
ADD follo\.ved by tl1e n ame of tl1e colt1m11 to be added, followed by tl1e characteristics of
tl1e colt1m11 . Figt1re 6-17 shows tl1e appropriate ALTER TABLE cotnmand for tl1is exat11ple.
Home
SOL Workshop
0 Autocommil
Rows
SQL Commands
110
I.,, I V .?
( Save ) ( Run )
ALI•R IAB::.E u:vn1_cusr oMER - + - - - - - - - - - - - {
Table to alter
ADD COSIO!<!ER TYPE Cl@..R(l);
Column to
add
0.21 seconds
FIGURE 6-17
Adding a column to an existing table
Tl1e LE\TELl_CUSTONIER table 110w co11tains a colu1n11 11amed CUSTONIER_TYPE , a
CHAR columt1 \.Vith a length of 1. Any ne\.V rows added to the table 111ust i11clude values for
tl1e new colu11u1. Effective i11unediately, all existing ro\.vs also contain tllis 11e"'' colu11111 .
Tl1e data in at1y existi11g rov.r ,vill co11tain the 11ev.r coli11nn the 11ext tilne tl1e rov.r is
Chapter 6
t1pdated. Any time a row is selected for any reason , ho\.vever, tl1e system treats the row as
tl1oi1gl1 tl1e column is actt1ally present. Tl1t1s, to the t1ser , it seems as tl1oi1gh the structt1re
was cl1anged immediately.
For existing r o\.vs, yot1 mt1s t assign som e valt1e to tl1e CUS'fOMER_TYPE colt1mn. 'fhe
simplest approacl1 (from tl1e point of view of the DBMS, not the user) is to assig11 tl1e
valt1e NULL as a CUSTOMER_TYPE fo r all existing rov.1s. Tllis process reqt1ires the
CUSTOMER_'fYPE colt1mn to accept nt11l valt1es, and som e systems actt1ally i11sist on tl1is.
Tl1e defat1lt for Oracle, Access, a11d SQL Server is to accept nt11l valt1es.
To change tl1e vali1es in a 11e\.v colt1mn that \.Vas added t1sing an ALTER TABLE command, follo\.v tl1e AL'fER TABLE command witl1 an UPDA'f E command lille the one shown
in Figi1re 6-18, \.Vhich sets tl1e CUSTOMER_TYPE valt1e for all ro\.\7S to R.
I
Home
SOL Workshop
0 Autocommit
SQL Commands
J10
Rows
1v
IV .r?
( Save )( Run )
UPDATE L~Ll CUSTOMER
SET COSTOMtR_ TYPE = ' R ' ;
Results
C
Omitting the
WHERE clause updates
all rows
7 row (s ) updated .
0.01 seconds
FIGURE 6-18
Making the same update for all rows
'f l1e SELEC'f command shown in Figi1re 6-19 verifies that tl1e valt1e i11 tl1e
CUSTOMER TYPE colt1mn for all ro\.vs is R.
Home
SOL Workshop
EllAutocommil
Sch
SQL Commands
' v I V .r/
110
Rows
( Save ) ( Run )
SELECT*
fROM 1.EVELl_COSTOM• R;
Results
De
Sav d sa
907
Glenn's Bnllsh Toys
126
334
Toys Galore
HIS
ry
7500
45
R
7500
8000
15
45
R
The Every1hing Shop
0
1210.25
2345 75
386
Johnson's Oepartmen1 Store
879.25
7500
R
665
Cricket Gift Shop
7500
30
30
796
Unique Gifts and Toys
124.75
7500
45
R
893
All Season Gills
935.75
7500
15
R
7 rows returned In 0.01 seconds
FIGURE 6-19
Download
CUSTOMER TYPE set to R for all rows
R
R
Updating Data
EXAMPLE 10
Two customers in the LEVELl_CUSTOMER table have a type other than R. Change the
types for customers 334 and 386 to S and D, respectively.
Example 9 used a11 UPDATE command to assign type R to ever y customer . To chai1ge
individt1al types to som etlling o tl1er tl1a11 type R, t1se tl1e UPDATE co1runand. Figt1re 6-2 0
sl1ows tl1e UPDATE commai1d to cl1ange customer 334 to custom e r type S .
.
LHome
SOL WorkShop
~ Autocommit
Sch
SQL Commands
Rows
:--1v~
[10
( Save ) ( Run )
OPDA:"E k-vELl CUSTOMER
SET CUSTOMER TYPE= 'S'
INHERE CUSTOMER NtlM a ' 334 ' ;
Results
- -
·~·•
-
s r
:, v d SQL
History
1 ro,,.( s) updat:ed .
0.00 seconds
FIGURE 6-20
Updating customer 334 to customer type S
Figure 6-2 1 sl10\vs the UPDATE co1nmai1d to cl1ange custo1ner 386 to cus tom er type D.
1· Home
SOL WorkShop
Rows
0Autocommit
Sch
SQL Commands
--1 v ~
110
~ Save )( Run)
-
UPDATE L'VELl CUSTOMER
SET CUSTOMER TYPE= 'D'
IIBER! CUSTOMER_ NUM = '386';
Results
I
s
-
ved SQt History
1 row(s) updaced.
0.00 seconds
FIGURE 6-21
Updating customer 386 to customer type D
Tl1e SELECT com1n and sl1own i11 Fig11re 6-22 sl10\.vs the res11lts of tl1ese UPDATE
comn1ands. Tl1e c11stom e r type for ct1sto1ne r 334 is S and tl1e type for c11s tom er 386 is D.
Tl1e type for all otl1er ct1stom e rs is R.
Chapter 6
Home
SOL Workshop
0Autocommil
Sch
SQL Commands
Rows
110
;v
IV ,I?
( Save ) ( Run)
SELECT *
fROM LEV.:Ll_C{ISTOM~R;
Results
•
I
907
Glenn's Brillsh Toys
0
7500
45
R
126
334
Toys Galore
7500
8000
15
45
R
The Everything Shop
1210..25
2345.75
s
386
Johnson's Department Store
879.25
7500
30
0
665
796
Cricket Gift Shop
124.75
30
45
R
Unique Gilts and Toys
7500
7500
893
All Season Gifis
935.75
7500
15
R
7 rows returned in 0.01 seconds
1
FIGURE 6-22
•
R
Download
Customer types in the LEVEL 1_CUSTOMER table after updates
Figt1re 6-23 t1ses tl1e DESCRIBE com1nand to display the structure of tl1e
LEVELl_CUSTONIER table, \.vhicl1 nov., includes tl1e CUSTONIER_TYPE column .
Home
SOL Wooohop
0 Autocomm1l
Rows
Schema [PRATT/LAST : v I
SQL Commands
[To
Iv IV {l
( Save ) ( Run )
DESCRIBE
DESCRIBE LFVELl_CUSIOMER; + - - - - - - - - - - - - - 1
command
Describe
Object Type TABLE Object LEVEL1_CUSTOMER
•
••
LEVEL 1 CUSTOMER
New
CUSTOM ER_TYPE
CUSTOMER NUM
CHAR
3
CUSTOMER NAME
CHAR
35
BALANCE
NUMBER
8
2
✓
CREOIT LIMIT
NUMBER
8
2
✓
REP NUM
CHAR
2
✓
CUSTOMER TYPE
CHAR
1
✓
1
✓
column
FIGURE 6-23
1-6
Structure of the LEVEL 1 CUSTOMER table
ACCESS
USER
NOTE
In Access, use the Documenter tool to show the layout of a table.
SOL SERVER
USER
NOTE
In SQL Server, execute the following command to list all the columns in the LEVEL 1_CUSTOMER table:
Exec sp_ columns LEVELl_ CUSTOMER
Updating Data
EXAMPLE 11
The length of the CUSTO~IER_NAME column in the LEVELl_CUSTO~IER table is
too short. Increase its length to 50 characters. In addition, change the CREDIT_LIMIT
column so it cannot accept nulls.
You can cl1ange the characteristics of existi11g columns by 11sing the MODIFY clause
of the ALTER TABLE command. Fig11re 6-24 sl10\.,,s the ALTER TABLE command that
cha11ges the length of the CUST011ER_NANIE column from 35 to 50 characters.
l ~ome
SOL Workshop
E2I Autocommi\
SQL Commands
Rows
110
lvlV ,?
( Save )( Run )
ALIER TABLE LEVEI.l CUSTOMER
MODIFY CUS70MER_NAME CliAR(50 ) ;
~
Results
s r
--
a ea :>UL
History
Table al cered .
0 .12 seconds
FIGURE 6-24
Changing the length of the CUSTOMER_NAME column in the LEVEL 1_CUSTOMER
table
SQL SERVER
USER
NOTE
To change the characteristics of existing columns in SQL Server, use the ALTER COLUMN clause. The
following command changes the length of the CUSTOMER_NAME column in SQL Server:
ALTER TABLE LEVELl CUSTOMER
ALTER COLUMN CUSTOMER NAME CHAR ( 5 0) ;
ACCESS
USER
NOTE
The version of the ALTER TABLE command shown in Figure 6-24 is not available in Access; to modify
the table's structure, make the changes in Design view and save the table.
NOTE
You also can decrease the length of col umns, but you might lose some data currently in the col umn. For
example, if you decrease the length of the CUSTOMER_NAME column from 35 to 20 characters, only
the first 20 characters of the current customer names will be included. Any characters from position 21
on will be lost. Thus, you should only decrease column lengths when you are positive that you will not
lose any data stored in the column.
You can change the length of DECIMAL columns in the same manner that you change the length
of CHAR columns.
Chapter 6
Fig11re 6-25 sho,vs tl1e ALTER TABLE command to change tl1e CREDI'f_LIMIT
col11mn so it does not accept n11ll val11es.
j Home
SQL Workshop
0Autocommil
Rows
SQL Commands
:vlV ~
110
( Save )( Run )
ALTER TABLE LEVEl l CUSTOMER
MODIFY C!\EOII_ LIMII NO! troLL;
Results
"'" :,
IX".C noe
'!i V
SQL-H1story
!abl e ali:ered.
0.04 seconds
FIGURE 6-25
Chang ing the CREDIT_LIMIT column in the LEVEL 1_CUSTOMER table to reject
null values
Tl1e DESCRIBE com1na11d sho\\711 i11 Fig11re 6-26 sl10,vs tl1e revised str11ct11re of tl1e
LE\TELl_CUSTOMER table. The le11gtl1 of the CUSTOMER_NAME colum11 is 50 characters. Tl1e 111issi11g val11e of a cl1eck 1narlr i11 tl1e Nullable col111n11 for tl1e CREDIT_LINIIT
col11m11 i11dicates tl1at tl1e CREDIT_LIMIT col11rm1 110 longer accepts 111111 val11es.
Home
SOL Workshop
i;zJ Autocommll
Rows
SQL Commands
I10 I " ) V ~
No check mark indicates
t hat t he CREDIT_LIMIT column
will not accept null values
( Save ) ( Run )
DESCRIBE LEVELl_COSIO!-!ER;
r
Descnbe
Length changed to 50
Object Type TABLEObjed LEVEL1_CUSTOMER
•
I
LEVEL1 CUSTOMER
CUSTOMER NUM
CHAR
CUSTOMER NAME
CHAR
50
BALANCE
NUMBER
-
CREDIT LIMIT
NUMBER
REP NUM
CHAR
2
✓
CUSTOMER TYPE
CHAR
1
✓
1
✓
8
2
8
2
✓
1 -6
FIGURE 6-26
Revised structure of the LEVEL 1 CUSTOMER tabie
SQL SERVER
USER
NOTE
To change the CREDIT_LIMIT column to reject null values in SQL Server, use the following ALTER
COLUMN clause:
ALTER TABLE LEVELl CUSTOMER
ALTER COLUMN CREDIT LIMIT DECIMAL (8, 2) NOT NULL;
Updating Data
NOTE
You also can use the MODIFY clause of the ALTER TABLE command to change a column that currently rejects null values so that it accepts null values by using NULL in place of NOT NULL in the
ALTER TABLE command.
NOTE
If there were existing rows in the LEVEL1_CUSTOMER table on which the CRED IT_LIMIT column were
already null, the DBMS would reject the modification to the CREDIT_LIMIT column shown in Figure 6-25
and display an error message indicating that this change is not possible. In this case, you first must use
an UPDATE command to change all values that are null to some other value. Then you could alter the
table's structure as shown in the figure.
Making Complex Changes
I11 so1ne cases, yot1 1nigl1t 11eed to c l1ru1ge a table's s truc tttre i11 ways tl1at a.re beyo11d tl1e
capabilities of SQL or tl1at a re so co1nplex tl1at it \.Vot1ld talre lo11ger to 111ake the cl1a11ges
tl1a11 to r e-create tl1e table. Perl1aps yot1 11eed to eli1ni11ate 111t1ltiple colt11n11s, rearra11ge tl1e
order of several colt11m1s, or co111bi11e data fr o1n two tables i11to one. For exan1ple, if yot1
try to cl1a11ge a colt1m11 \\'itl1 a d a ta type of VARCH.AR to CHAR, SQL s till ttses V ARCHAR
\\rl1e11 tl1e table contai11s otl1e r va.riable-le11gtl1 colt1m11s. It1 tl1ese situa tio11s, yot1 can t1se a
CREATE TABLE co1nmru1d to describe tl1e 11ew table (\.vl1ich 1nust t1se a different na111e
tl1a11 tl1e existing table), and tl1e11 i11sert valties fr o1n tl1e existi11g table i11to it u si11g tl1e
INSERT com1na11d combi11ed \\'i tl1 ru1 appropriate SELECT com1na11d.
DROPPING A TABLE
As you learned in Cl1apter 3, you ca11 de le te a table tl1at is no lo11ger 11eeded by executing
tl1e DROP TABLE command.
EXAMPLE 12
Delete the LEVELl_CUSTOMER table because it is no longer needed in the TAL
Distributors database.
Tl1e co1n1na11d to delete tl1e table is sl10\.vn in Figure 6-27.
Chapter 6
•
Home
SOL Workshop
~ Autocommit
Rows
SQL Commands
110
lvl V .?
( Save ) ( Run )
DROP : ABLE LEVELl_ COSIOMER;
Results
p
s
e Sav
SQL
Hist ry
j! able dropped .
0.03 seconds
FIGURE 6-27
DROP TABLE command to delete the LEVEL 1 CUSTOMER table
\\The11 tl1e comma11d sl10\.v11 in Figure 6-27 is executed, tl1e LEVELl_CUST011ER table
and all its data are per111ane11tly re1noved fro111 the database.
Updating Data
Chapter Summary
•
To create a new table from an existing table, first create the new table by using the
CREATE TABLE command. Then use an INSERT command containing a SELECT
command to select the desired data to be included from the existing table.
•
Use the UPDATE command to change existing data in a table.
•
Use the INSERT command to add new rows to a table.
•
Use the DELETE command to delete existing rows from a table.
•
Use the COMMIT command to make updates permanent; use the ROLLBACK command to reverse any updates that have not been committed.
•
To change all values in a column to null, use the SET clause followed by the column
name, an equals sign, and the word NULL. To change a specific value in a column to
null, use a condition to select the row.
•
To add a column to a table, use the ALTER TABLE command with an ADD clause.
•
To change the characteristics of a column, use the ALTER TABLE command with a
MODIFY clause.
•
Use the DROP TABLE command to delete a table and all its data.
Key Terms
ADD clause
MODIFY clause
ALTER TABLE
roll back
Autocommit
ROLLBACK
commit
transaction
COMMIT
UPDATE
DELETE
Review Questions
1. Which command creates a new table?
2. Which command and clause adds an individual row to a table?
3. How do you add data from an existing table to another table?
4. Which command changes data in a table?
5. Which command removes rows from a table?
6. Which command makes updates permanent?
7. Which command reverses updates? Which updates are reversed?
8. How do you use the COMMIT and ROLLBACK commands to support transactions?
9. What is the format of the SET clause that changes the value in a column to null in an
UPDATE command?
Chapter 6
10. Which command and clause adds a column to an existing table?
11 . Which command and clause changes the characteristics of an existing column in a table?
12. Which command deletes a table and all its data?
C RITICAL
THINKING
13. Microsoft Access supports make-table queries. What is a make-table query? Which SOL
statement(s) are equivalent to make-table queries?
Exercises
T AL Distributors
Use SOL to make the following changes to the TAL Distributors database (see Figure 1-2 in
Chapter 1). After each change, execute an appropriate query to show that the change was
made correctly. If directed to do so by your instructor, use the information provided with the
Chapter 3 Exercises to print your output or to save it to a document.
1. Create a NONGAME table with the structure shown in Figure 6-28.
NONGAME
Column
Type
Length
l'fE1il_Nill-l
Clli\R
4
DJ;;SCRlP'l'ION
Cl L-\H.
30
ON_llAffD
DECI.Mi\L
4
C1\'fEGOR't'
C fIAR
3
PRfCE
DECIMAIJ
6
FIGURE 6-28
Decimal Places
Nulls Allowed?
Description
No
lten1 nu111ber (pri1nary key)
ltem description
0
Number of units oa band
Item category
2
I
I
Unit price
NONGAME table layout
2. Insert into the NONGAME table the item number, description, number of units on hand,
category, and unit price from the ITEM table for each item that is not in category GME.
3. In the NONGAME table, change the description of item number DL51 to "Classic Train Set.''
4. In the NONGAME table, increase the price of each item in category TOY by two percent.
(Hint: Multiply each price by 1.02.)
5. Add the following item to the NONGAME table: item number: TL92; description: Dump
Truck; number of units on hand: 10; category: TOY; and price: 59.95.
6. Delete every item in the NONGAME table for which the category is PZL.
7. In the NONGAME table, change the category for item FD11 to null.
8. Add a column named ON- HAND- VALUE to the NONGAME table. The on-hand value is a
seven-digit number with two decimal places that represents the product of the number of units
on hand and the price. Then set all values of ON_HAND_VALUE to ON_HAND * PRICE.
9. In the NONGAME table, increase the length of the DESCRIPTION column to 40 characters.
10. Remove the NONGAME table from the TAL Distributors database.
Updating Data
CRITICAL
THINKING
11 . Use the Internet to find the SOL command to delete a column in a table in Oracle. Write the
SOL command to delete the ON_HAND_VALUE column from the NONGAME table. Be
sure to cite your references.
Colonial Adventure Tours
Use SOL to make the following changes to the Colonial Adventure Tours database (Figures 1-4
through 1-8 in Chapter 1). After each change, execute an appropriate query to show that the
change was made correctly. If directed to do so by your instructor, use the information provided
with the Chapter 3 Exercises to print your output or to save it to a document.
1. Create a PADDLING table with structure shown in Figure 6-29.
PADDLING
Column
Type
Length
Decimal Places
Nulls Allowed?
Description
TRIP_ID
DECilvlAL
3
0
No
Trip ID (primary key)
TRTP_NA~ IE
CI-Ir\R
75
Trip name
STATE
Clli\R
2
Trip state
lJISTi\NCE
DECI~lJ\L
➔
0
Trip distance
.Nl.t\.,'\_GR.P_SIZE
DisCl~l.t\L
4
0
fdaximun1 nun1ber of people on trip
SE,\SON
CI-li\R
20
FIGURE 6-29
Season in ,vhich trip takes place
PADDLING table layout
2. Insert into the PADDLING table the trip ID, trip name, state, distance, maximum group size,
and season from the TRIP table for only those trips having type PADDLING.
3. For all trips located in Connecticut (CT), increase the maximum group size by two. Update
the PADDLING table accordingly.
4. Insert a new trip into the PADDLING table. The trip ID is 43, the trip name is Lake
Champlain Tour, the state is Vermont (VT), the maximum group size is 12, the distance is
16, and the season is Summer.
5. Delete the trip in the PADDLING table with the trip ID 23.
6. The distance for the Pontook Reservoir Tour trip has been increased to an unknown number. Change the PADDLING table to reflect this change.
7. Add to the PADDLING table a new character column named DIFFICULTY LEVEL that is three
characters in length. Then set the default difficulty level value for all rows to the value MOD.
8. Change the DIFFICULTY_LEVEL column in the PADDLING table to HRD for the Lake
Champlain Tour trip.
9. Change the length of the SEASON column in the PADDLING table to 25 characters.
10. Change the DIFFICULTY_LEVEL column in the PADDLING table to reject nulls.
11 . Delete the PADDLING table from the database.
C RITICAL
THINKING
12. Use the Internet to research another data type that you can use in Oracle for character
data, and then re-write the SOL command to create the PADDLING table using the other
data type. Be sure to cite your references.
Chapter 6
Solmaris Condominium Group
Use SOL to make the following changes to the Solmaris Condominium Group database
(Figures 1-9 through 1-13 in Chapter 1). After each change , execute an appropriate query to
show that the change was made correctly. If directed to do so by your instructor, use the information provided with the Chapter 3 Exercises to print your output or to save it to a document.
1. Create a LARGE_CONDO table with the structure shown in Figure 6-30. (Hint: If you have
trouble creating the primary key, see Figure 3-36 in Chapter 3.)
LARGE CONDO
Column
Type
Length
Decimal Places
Nulls Allowed?
Description
LOCA'l'ION_NU111
ogc1J.1AL
2
0
No
Location nu rnber (primary key)
UNIT_Nilll'l
Clli\R
J
No
Unit number (primary k1::y)
BDIUIS
DECTh·L\L
2
()
Number of bedrooms
BATIIS
011.:Cl!vlAL
2
()
Nun1bcr of bathroon1s
CONDO_Fl~E
DECIMAL
6
2
Monthly
condo fee
•
OvVNER_f•.,TlJt.1
CHi\R
:,
1
FIGURE 6-30
Number of condo o,vner
I
I
I
LARGE_CONDO table layout
2. Insert into the LARGE_CONDO table the location number, unit number, bedrooms, baths,
condo fee, and owner number for those condos whose square footage is greater than 1,500
square feet.
3. Solmaris has increased the condo fee of each large condo by $150. Update the condo fees
in the LARGE_CONDO table accordingly.
4. After increasing the condo fee of each large condo by $150 (Exercise 3), Solmaris decides
to decrease the condo fee of any condo whose monthly fee is more than $750 by one percent. Update the condo fees in the LARGE_CONDO table accordingly.
5. Insert a row into the LARGE_CONDO table for a new condo. The location number is 1, the
unit number is 605, the number of bedrooms is 3, the number of bathrooms is 3, the condo
fee is $775, and the owner number is FE182.
6. Delete all condos in the LARGE CONDO table for which the owner number is AN175.
7. The condo in location 1 and unit 503 is in the process of being remodeled and the number of
bedrooms is unknown. Change the bedrooms value in the LARGE_CONDO table to null.
8. Add to the LARGE CONDO table a new character column named OCCUPIED that is one
character in length. (This column will indicate whether the condo is currently occupied.) Set
the value for the OCCUPIED column on all rows to Y.
9. Change the OCCUPIED column in the LARGE_CONDO table to N for unit C06.
10. Change the CONDO_FEE column in the LARGE_CONDO table to reject nulls.
11 . Delete the LARGE CONDO table from the database.
C RITICA L
TH INKI NG
12. Use the Internet to research another data type that you can use in Oracle for numeric
values that store only whole numbers, and then re-write the SOL command to create the
LARGE_CONDO table using the other data type. Be sure to cite your references.
CHAPTER
DATABASE ADMINISTRATION
OBJECTIVES
•
Understand, create, and drop views
•
Recognize the benefits of using views
•
Use a view to update data
•
Grant and revoke users' database privileges
•
Understand the purpose, advantages, and disadvantages of using an
index
•
Create, use, and drop an index
•
Understand and obtain information from the system catalog
•
Use integrity constraints to control data entry
INTRODUCTION
There are some special issues involved in managing a database. Th is process, often called database
administration, is especially important when more than one person uses the database. In a business
organ ization, a person or an entire group known as the database administrator is charged with
managing the database.
In Chapter 6, you learned about one function of the database ad ministrator: chang ing the
structure of a database. In this chapter, you will see how the database administrator can give each
user his or her own view of the database. You will use the GRANT and REVOKE commands to
ass ign different database privileges to different users. You will use indexes to improve database
performance. You will learn how a DBMS stores information about the database structure in an
object called the system catalog and how to access that information. Finally, you will learn how to
specify integrity constraints that establish rules for the data in the database.
CREATING AND USING VIEWS
Most DBMSs st1pport tl1e c reatio11 of views. A vie \.v is a program 's or ru1 i11dividual t1ser's
pic tt1re of tl1e d a tabase. Tl1e e.xisti11g, pe rmru1e11t ta bles i11 a rela tio11al data b ase are called
base tables. A view is a de rived table b ecat1se tl1e da ta in it com es from 011e or m ore base
ta bles. To tl1e t1ser , a view appears to b e a11 actt1al table, bt1t it is 11o t. 111 1na11y cases, a
user ca11 exa1ni11e table data t1si11g a vie~,. Becat1se a vie w t1st1ally i11cli1des less i11forma tio11 tl1a11 tl1e ft1ll data base, its t1se ca11 re prese11t a great si1nplificatio11. Vie ~rs also provide
a 1neast1re of security, b ecat1se 01nittil1g se11sitive ta bles or colt11m1s fro111 a vie"'' re11de rs
tl1e1n t111available to a11yo11e accessing tl1e d a tabase tl1rot1gl1 tl1e vie\.\'.
Chapter 7
To l1elp yo11 11nderstand tl1e concept of a vie,v, st1ppose that Nlaria is interested in tl1e
ite1n n11mber , descriptio11, 11nits on l1and, and 11nit price of items in category TOY. She is
not interested in any other col11mns in the ITEM table, no r is sl1e inte rested iI1 any ro,,,s
tl1at corresp ond to items in o tl1e r categories. \Tiewing this data ,vottld be simple r for Matia
if tl1e other rows and col11mns were 11ot even present. Altho11gh you cannot cl1ange the
stn1ct11re of the ITEM table and omit som e of its ro,,,s just for Maria, yo11 can do tl1e next
best tl1ing. Yott can provide her with a vie,v that consists of only the ro,vs and colt.1mns
tl1a t sl1e 11eeds to access.
A view is defined by creating a defining query, " 'l1icl1 indicates tl1e ro\\'S a11d col11mns
to i11clt1de in the view. The SQL command (or the defini11g q11e ry) to c reate the view for
Nlaria is illustrated in Example 1.
EXAMPLE 1
Create a view named TOYS that consists of the item number, description, units on hand,
and unit price of each item in category TOY.
To c reate a view, use tl1e CREATE VIE,v command, ,vl1icl1 incl11des tl1e ,vords
CREATE VIE\\T, followed by tl1e name of tl1e vie\.v, tl1e ,vord AS, and tl1en a q11e ry. Tl1e
CREATE VIEW command sl1ow11 in Fig11re 7-1 creates a view of tl1e ITEM table that
contains only tl1e specified columns.
ORACLE' Application Express
•
Home
SOL Workshop
eZIAutocommil
Rows
t.::
• '
SQL Commands
j10
I.., l V .fl
( Save )
Run.>- - - . .
CREAI'E VIElil TOYS AS + - - - - - - - - ---!
SELECT ITEM_NUM, DESCRIPTION, ON_ IIANO, PRICE
fROM ITEM
[WHERE CATEGORY •
Name of - - - - - - - ;
'TOY ' ;
.
view
Defining
<-:Results
=-----::---=---:-::--=:===~~~~~~~-----;:,~~,::---'
--- q ue~
S.plain Descnbe Saved 'iQL ll1story
Viet.· created.
0.34 seconds
FIGURE 7-1
Creating the TOYS view
ACCESS
USER
NOTE
Access does not support the CREATE VIEW command. To create a view in Access, create a query to
define the view, and then save the query object in the database using the view's name (for example,
TOYS).
Database Administration
Given the c11rrent data i11 the TAL Distrib11tors database, the TOYS vie,v contains the
data sho\vn in Fig11re 7-2 .
TOYS
PART_NUM
DESCRIPTION
C::D33
ON - HAND
PRICE
\\Tood Block Set (48 Piece)
36
$89.49
DL51
C lassic Raihvay Set
12
$107.95
FDll
Rocking I-Iorse
8
$124.95
NL89
"\\food Block Set (62 Piece)
32
$119.75
T\V35
Fire Engine
30
$118.95
FIGURE 7-2
TOYS view
Tl1e data does not actually exist in this form , 11or will it ever exist it1 tl1is for111. It is
tempti11g to tllink tl1at vvl1en Maria uses this vie\\', tl1e query is executed and produces some
sort of temporary table, 11amed TOYS, that Maria ca11 access, but tl1is is not \Vhat actually
l1appens. l11stead, the query acts as a sort of window it1to tl1e database, as shown it1
Figure 7-3 . As far as Maria is conce1ned, tl1e entit·e database is j11st tl1e darker sl1aded
portio11 of the ITENI table. Nlaria ca11 see any change tha t affects tl1e darke r portio11 of the
ITEM table, but sl1e is unaware of a11y otl1er changes tl1at are made it1 the database.
ITEM
ITEM_NUM
DESCRIPTION
1\1174
Patience
BR23
STOREHOUSE
PRICE
9 G.t.{E
3
$22.99
Skittles
21 G.t.ffi
2
$29.99
C::D33
\Vood Block Set (48 piece)
36 TOY
]
$89.49
DL51
Classic Rai hvay Set
12 'fOY
3
$107.95
DR67
Giant Star Brain Teaser
24 PZL
2
$31.95
D\V23
J\ilancala
40 GJ\i[E
3
$50.00
FDll
Rocking Jlorse
8 'fOY
3
$124.95
Fl 124
Puzzle Gift Set
65 PZL
]
$38.95
KA12
C ribbage Set
56 G:t-.ffi
3
$75.00
JCD34
Pentominoes Brai11 Teaser
60 PZT;
2
$14.95
l<L78
Pick Up Sticks
110
G/\fE
1
$ I 0.95
:t-.1IT03
Zauberkasten Brain Teaser
45 PZL
1
$45.79
NL89
\Vood Block Set (62 piece)
32 TOY
3
$119.75
TR40
Tic Tac Toe
75 G:t-.1fE
?
$13.99
T\\'35
Fire Engine
30 'fOY
2
$118.95
FIGURE 7-3
ON _HAND CATEGORY
Maria's view of the ITEM table
\\Tl1en you create a q11ery tl1at it1volves a view, the DENIS cl1anges tl1e q11ery to one
tl1at selects data fro1n tl1e table(s) it1 tl1e database tl1at created the view. For example,
suppose Maria creates the q11ery shown it1 Figure 7-4.
Chapter 7
Home
SOL Workshop
0Autocommit
SELECT •
FROM TOYS ~
Rows
SQL Commands
Iv I /; ,?
110
( S ave ) ( Run )
::;::::D~ao..-ta_ s_e-:-le_ct_e__d-:---.._--_____j
-----------!
WHERE PRICE> 100;
Results
tJescribe
1:_ 11
Saved SQL History
DL51
Classic Railway Set
12
107.95
FD11
Rocking Horse
8
124.95
NL89
Wood Block Set (62 piece)
32
119.75
TW35
Fire Engine
30
118.95
4 rows returned in 0.00 seconds
FIGURE 7-4
from TOYS view
Download
Using the TOYS view
Tl1e DBMS does 11ot exec11te tl1e q11ery in tllis form. Instead, it merges tl1e qt1ery Maria
e11tered witl1 tl1e query tl1at creates tl1e TOYS view to for1n the query tl1at is act11ally executed.
\}\Tl_1e11 the DBMS merges tl1e q11ery tl1at creates tl1e view \vith Maiia's query to select ro\VS 011
\Vhich tl1e PRICE val11e is greater tl1an 100, the query tl1at the DB11S actiially executes is:
S ELECT ITEM NUM, DE SCRIPTION, ON HAND, PRI CE
FROM ITEM
WHE RE CATEGORY =
1
TOY
1
AND PRI CE > 100;
111 the qt1ery tl1at the DBNIS executes, tl1e FROM clause lists tl1e ITENI table ratl1er than the
TOYS vie\\', the SELECT clause lists colunn1s from tl1e ITENI table iI1stead of * to select all
columns from tlle TOYS view, and tl1e \\TI-IERE clat1se contaiI1s a compo11nd condition to select
only tl1ose items i11 tl1e TOY category (as Maria sees i11 tl1e TOYS vie\\7) and only tl1ose items witl1
PRICE values of greater than 100. Tllis 11e\v query is tlle one tl1at tl1e DENIS act11ally executes.
Maria, 110\vever, is una\vare that this activity is taking place. To Maria, it seems tl1at she is
really 11si11g a table 11ained TOYS. One advai1tage of this approacl1 is that because tl1e TOYS
view never exists in its O\VI1 right, ai1y 11pdate to tl1e ITENI table is irriniecliately available i11 the
TOYS vie\v. If tl1e TOYS vie\v were really a table, tllis iinmediate update wo11ld not be possible.
You also can assign colu1nn naines tl1at are different fron1 tllose in tl1e base table, as
ill11strated i11 tl1e next example.
EXAMPLE 2
Create a view named TYS that consists of the item number, description, units on hand,
and unit price of all items in category TOY. In this view, change the names of the
ITEM_NUM, DESCRIPTION, ON_HAND, and PRICE columns to INillvI, DSC, OI-1, and
PRCE, respectively.
"Then renammg colu1nns, yo1.1 i11clude tl1e new colt1nm names in parentheses follo,vi11g the
11aine of the view, as shown i11 Figt1re 7-5. In tl1is case, ai1yone accessing the TYS view will refer
to ITENI_NUNI as INUNI, to DESCRIPTION as DSC, to ON_I:--IAND as OH, and to PRICE as PRCE.
Database Administration
I
LHome
SQL Commands
SQl WoJllshop
\.
v1V .P
110
Rows
0 Autocommit
New names
for columns
( Save ) ( Run )
I!!
cru:.ATE VIEIN TIS (INUM, DSC, OH, PRCEf AS
SELECT IIEM_NUM, OESCRIPIION, ON_HANO, PRICE
FROM ITEM
WHERE CATEGORY = 'TOY ' ;
Results
'---"
t; ..
•
:}· •
ri
!)
~ved SQL
History
l iew c rea,:;ed.
0.01 seconds
Renaming columns when creating a view
FIGURE 7-5
If you select all colum11s from the TYS view, the outpt1t displays the 11ew colum11
names, as shovv11 in Figure 7-6.
I
Home
SOL Workshop
0Autocommil
Rows
SQL Commands
lvl V .P
110
( Save ) ( Run )
SELECT •
FROM TYS;
Results
-
E p m Descnbe Saved SQL History
il
I
•
1•11".1111111;_
CD33
Wood Bloek Set (48 piece)
36
89.49
DL51
Classic Railway Set
12
107.95
FD11
Rocldng Horse
8
124.95
NL89
Wood Block Sel (62 piece)
32
119.75
TW35
File Engine
30
118.95
5 rows returned in O.01 seconds
FIGURE 7-6
New column
names
)
Download
Data in the TYS view
ACCESS
USER
NOTE
To change column names in Access, use AS clauses in the query design (for example, SELECT
ITEM_NUM AS INUM, DESCRIPTION AS DSC, and so on).
Tl1e 'fYS view is an example of a row-and-column subset view beca.t1se it consists of a
st1bset of tl1e ro,vs and colt1mns in some base table-in this case, in tl1e I'fEM table.
Becat1se the defining qt1ery can be any valid SQL qt1ery, a view also can join two or more
tables or involve statistics. The next example illt1strates a view that joins two tables.
EXAMPLE 3
Create a vie,v named REP_CUST consisting of the sales rep number (named RNUM), sales rep
last name (named RLAST), sales rep first name (named RFIRST), customer number (named
CNUM), and customer name (named CNAME) for all sales reps and matching customers in the
REP and CUSTOMER tables. Sort the records by rep number and customer number.
Chapter 7
Tl1e co111111and to create this vie\\' appears ill Figure 7-7.
Home
SOL Workshop
SQL Commands
l vl~,?
110
Rows
~Autocommit
( Save )( Run )
CREl\l'E vrm REP cusr ( RNOM, RI.AST, RFIRSI, CNOM, CNAME) AS
SELECT RE.P.REP_NOM, LAST NAM;: FIRST_NAME, COSTOMER_NUM, CUSTOMER NAME
'
FROM REP, COSTOME.R
WHERE REP.REP- NOM = CUSTOMER .REP- NOM
ORDEA BY REP.REP_NUM, COSTOMER_NUM;
-
Results
E tplatn
-
View joins
two tables
Describe Savell SQL History
View creaced.
0.35 seconds
FIGURE 7-7
Creating the REP_CUST view
Given the current data ill the TAL Distributors database, the REP_CUST vie\\' contail1s tl1e data sl10\\rn in Figi1re 7-8.
I Home SOL Workshop
SQL Commands
0 Autocommlt
11s
'
Rows
I vi~,?
( Save)( Run )
S~CT •
FRO~ REP_COST;
Results
.....,
~1- an Describe Saved SQL
.r.. ... ' ■
•
•
.. !,
15
15
Campos
Rafael
Campos
Rafael
126
502
15
15
Campos
Rafael
Campos
30
HISlory
/ '"U:i,
Toys Galore
Cards and More
Cress Store
Rafael
713
893
Gradey
Megan
260
Brookings Direct
30
30
Gradey
Megan
Johnson's Department store
Gradey
Megan
386
665
30
45
Gradey
Megan
Kline's
nan
Hui
824
334
Tian
Hui
45
440
45
Tian
Hui
586
Hu)
45
Tian
796
12 rows returned in O 10 seconds
FIGURE 7-8
SQL
All Season Gills
Cridcel Gift Shop
The Everything Shop
Grove H1stoncal Museum Store
Alm011dton General store
Unique Grfls
Dowalosi!!
Data in the REP CUST view
SERVER
NOTE
SQL Server does not support the ORDER BY clause in a CREATE VIEW command. When you need to
order the query results, insert an ORDER BY clause in the SELECT command when you query the
view. For example, the following SELECT command retrieves all records in the REP_CUST view,
ordered by rep number and customer number:
SELECT*
FROM REP CUST
ORDER BY RNUM, CNUM
Database Administration
A view also can involve s tatistics, as ill11s trated in Example 4.
EXAMPLE 4
Create a view named CRED_CUST that consists of each credit limit (C REDIT_LIMIT)
and the number of customers having this credit limit (NUM_CUSTOMERS). Sort the
credit limits in ascending order.
Tl1e command sl1ovvn in Fig11re 7-9 creates this view.
Home
SOL Workshop
SQL Commands
11u
Rows
Ell Autocommit
lvl V .?
CREATE VIEl'I CRED CUST (CRTI>I!_LIMIT,
SELECI CREDII_LIMIT, COUNI(*)
FROM CUSTOMER
GROUP BY CREDIT LIMIT
ORDER BY CREDIT_LIMIT;
Results
•
saved SOL
(
~
( Save ) ( Run)
NOM_CUSTOMERS) AS
History
View crear.ed .
0.01 seconds
Creating the CRED_CUST view
FIGURE 7-9
Tl1e SELECT com111and shown in Fig11re 7-10 displays tl1e current data in the TAL
Distrib11tors database for tllis vievv.
Home
SQL Work:sllop
0 Autocommlt
Rows
SQL Commands
Iv IV 4
j10
( Save )( Run )
SELECT •
FROM CRED_CUST;
Results
i,- r
scr be
Saved SOL
History
-
CREDIT_UMIT
NUM_CUSTOMERS
5000
2
7500
10000
6
2
15000 - -
2_ _ _ __ ,
4 rows returned in 0.01 seconds
RGURE 7-10
Download
Data in the CRED CUST view
Tl1e 11se of views provides several benefits. First , vievvs provide data independence. \Vhen
tl1e database str11c tt1re cl1anges (by adding col11mns or changil1g the \\'ay objects are related ,
for example) in s11ch a vvay that the vie\.v s till can be de rived from existing data, the 11ser can
access and 11se tl1e sam e vie\.v. If adding extra col11mns to tables in tl1e d atabase is tl1e 011ly
change, and these col11mns are not req11ired by tl1e view's 11ser , the defining q11ery might not
Chapter 7
even n eed to be changed for the user to contintie tising tl1e vie\.v. If table relationsl1ips are
cl1anged, tl1e defining query 1nigl1t be different, but becatise tisers are not a\,,are of tl1e defining
query, they are tinaware of this difference. Users contintie accessing tl1e database tlu·o11gl1
tl1e same vie,v, as tl1011gh nothing has changed . For example, stippose custom ers are assigned
to territories, eacl1 territo ry is assigned to a single sales rep, a s ales rep can l1ave more tl1an
one territory, and a customer is represented by the sales rep \.vl10 covers tl1e ctistomer's
assigned territory. 'f o implem ent these ch anges, yott might choose to restrt1ctt1re tl1e data.b ase
as follo\.vs:
REP(REP NUM, LAST NAME , FIRST NAME , STREET, CITY,
STATE I POSTAL CODE I COMMISSION I RATE)
TERRITORY(TERR ITORY NUM, DE SCRIPTION, REP NUM)
CUSTOMER (CUSTOMER NUM, CUSTOMER NAME , STREET, CITY,
STATE , POSTAL CODE , BALANCE, CREDIT LIMIT, TERRI TORY NUM)
Asst11ning that the REP_CUST vie\.v sh own in Fig11re 7-8 is still reqtiired , yoti cotild
cl1ange tl1e defining qtiery as follows:
CREAT E VIEW REP CUST (RNUM, RLAST, RFIRST,
CNUM I CNAME) AS
S EL E CT REP. REP NUM, REP. LAST NAME, REP. FIRST NAME,
CUSTOMER NUM, CUSTOMER NAME
FROM REP, T ERRI TORY, CUSTOMER
WHERE REP. REP NUM = TERRITORY. REP NUM
AND TERRITORY.TERR ITORY NUM = CUSTOMER. T ERRITORY NUM;
Tl1is vie\.v's tiser still can re trieve tl1e number a.n d name of a sales rep togethe r \.Vith
tl1e nt1mber and name of eacl1 ct1s tomer the sales rep represents. Tl1e ttser is tina\vare,
110\.vever, of tl1e new strticture i11 tl1e database.
'fl1e second benefit of tising views is tl1at different tisers can see the same data in diffe rent \\rays thro11gl1 tl1eir own vie\.\'S. In otl1er \Vords, you can ct1s to1nize the display of
data to meet eacl1 ttser 's needs.
'fl1e final benefit of tising views is tl1at a vievv can contain only those coltimns
reqtiired by a give11 tiser. Tl1is practice has two advantages. Firs t , beca1.1se the view t1st1ally
contains fe\.ver col1.1mns than tl1e overall database and is concept1.1ally a si11gle table, r athe r
tl1an a collection of tables, a view grea.tly simplifies tl1e user 's pe rception of tl1e database.
Second , vie\vs provide a m eas1.1re of sect1rity. Colt1m11s tl1at are not inclt1ded in tl1e vie\v
are not accessible to the vie\\,'s tiser. For example, 01nitting tl1e BALANCE colt1n111 from a
view enst1res that tl1e vie\.,,'s user cai1not access any ct1stomer 's balance. Lilrevvise, r ovvs
tl1at are n ot inclt1ded in tl1e vie\.\' are no t accessible. A tiser of the TOYS view, for example, cannot obtai11 any information abottt items in the GME or PZL categories.
USING A VIEW TO UPDATE DATA
Tl1e benefits of 1.1sing views h old trt1e only wl1en vie\.vs are ttsed for rettieval purposes.
\\'11en 1.1pdati11g the database, the isst1es iI1volved in updating data throt1gh a view depend
on the type of view, as yott \.Vill see next.
Database Administration
Updating Row-and-Column Subset Views
Co11sider the ro\.v-a11d-colum11 subset vie\.\' fo r the TOYS vie"''· There are colum11s i11 tl1e
underlying b ase table (ITE11) that are 11ot prese nt in tl1e vie,v. If you atte111pt to add a r o\\'
witl1 tl1e da ta ( 1 CX85 1 , 1 Labryi11tl1 1 ,5,24.95) , the DB11S must deter111ine l1ow to ente r tl1e
data i11 those colu11111s fron1 tl1e ITENI ta ble tl1at are not included i11 tl1e TOYS vie\.V
(CATEGORY a11d ST OREHOUSE). 111 tllis case, it is clear "''h a t data to enter in tl1e
CATEGO RY column-accordi11g to the view definitio11, all rows ar e ca tegory TOY-but it
is 11ot clear wh a t d ata to enter i11 tl1e STO REHOUSE colum11. Tl1e only possibility "''ould b e
NULL. Tl1erefore, if every colu1nn 11ot included in a vie\.v ca11 accept nulls, you ca11 add new
ro\.\'S usi11g the INSERT co111111and . There is anotl1er problen1, 110\.,,ever. Suppose tl1e user
atte111pts to add a ro\.V to the TOYS view contai11iJ1g the d ata ( 1AH74 1 , 1 Dress Mal{er 1 ,5 ,29.95).
Because item 11umber AH74 already exists in the ITENI table , the system niust reject this
attempt. Because this item is no t in category TOY (and tl1er efo re is n ot i11 tl1e T OYS
view) , tllis rejection certai11ly \\'ill seem stra nge to the user , because the re is n o su cl1
item in the u ser 's vie\.v.
On the other h an d , updates or d ele tions cause 110 pa rticu la r problen1 in this view. If
tl1e descriptio11 of iten1 11un1ber DL51 ch anges from Classic Rail\\ray Set to Classic Ra ilroad
Se t, this cl1ange is m ade in tl1e ITEM tab le. If item number DL51 is dele ted , tllis dele tion
occurs i11 tl1e ITEM ta ble . On e surprising ch a11ge cou ld talre place, ho\\rever . Suppose that
tl1e CATEGORY colum11 is included in the TOYS view and a ttse r ch anges tl1e category of
item nu1nber DL51 fro1n TOY to GNIE . Because this ite1n ,vou ld 110 longer satisfy the c rite rion fo r being i11cluded i11 tl1e TOYS vie"v , item n u1n b er DL51 \.Vou ld disappear fro1n the
11ser 's vie\.\' !
Altl1ough tl1ere are pro blem s to overcome "''h e11 upda ting r ow-a11d-colurm1 subset
views, it see111s p ossib le to update the d ata base tl1ro11gh the T OYS view. This does n ot
1nea n tha t any ro\.v-and-colu11111 subset vie\.V is updata ble , 110\\rever. Consider the
REP_CRED vie\.V sl1own i11 Fig11re 7-1 1. (The DISTINCT op er ator is used to 0111-it duplicate
rO\\'S from tl1e view.)
I Home - SOL Work:shOc>
0Autocommit
'
Rows
SOL Commands
(10
'"IV 4
( Save ) ( Run )
CREA!! VTE\il REP CRED AS
StLECT DISTINCT CREDIT_LIMr!, Rl!:P_NOM
FROM CUSTOME:R
ORDER BY CREDIT_LIM!T, REP_NUM;
,.
Results
f Pia II Desc.1 oe S.Uve<I SQL
History
View creai;ed.
0.06 seconds
FIGURE 7-11
Creating the REP_ CRED view
••
Chapter 7
Fig11re 7-12 sh ows tl1e data in the REP_ CRED view.
Home
SOL Workshop
Rows
0 Aulocommi1
SQL Commands
, .., I fll ,?
j10
( Save ) ( Run )
SELECT*
FROM REP_CRED;
~
Results
---
-
SCI be
I
Saved SQL History
-
CREDIT_UMIT
REP_NUM
5000
15
5000
7500
45
15
7500
30
7500
45
10000
15
10000
15000
30
30
15000
45
9 rows returned in 0.19 seconds
FIGURE 7-12
Download
Data in the REP CRED view
Ho\v wo11ld yo11 add tl1e row 15000,' 15' to this vie\v? In tl1e 11nderlyi11g b ase table
(CUSTONIER), at least one custo1ner must be added vvhose cr edit li1nit is $ 15,000 and whose
sales re p 11umber is 15, but which cus tom e r is it? Yott cannot leave tl1e otl1er colt1mns 11ull in
tl1is case, becat1se 011e of them is CUSTOMER_NUNI, vvl1icl1 is tl1e b ase table's primary liey.
\\Tb.at \VOttld it 1nea11 to change tl1e r ow 7500,15 to 15000,15 ? Wot1ld it mean changing the
credit limit to $ 15 ,000 for each ct1s tome r re presented by sales rep n111nber 15 that curre11tly
l1as a credit limit of $ 7 ,500? \Vould it m ean cl1a11ging tl1e credit limit of one of tl1ese cus to1ners and deleting the rest ? \\Tha t would it m ea11 to dele te the row 7500,15? \\Tould it m ean
d ele ti11g all customers vvith credit limits of $ 7 ,500 and re presented by sales rep ntrmber 15,
or would it m ean assigni11g these c11stomers a different sales rep or a different credit li1nit?
Why does the REP_CRED view involve a n11mber of serious problem s tha t are n ot
present in the TOYS view? Tl1e basic reason is that the TOYS view incl11des, as on e of its
columns, tl1e prin1ary key of the ttnderlying base table , bt1t tl1e REP_CRED vie\v does 11ot .
A rovv-a11d-colt1mn s11bset vie"'' that contains the primary liey of the u11der lying base table
is updatable (subject, of cot1rse, to some of tl1e con cerns already disct1ssed).
Updating Views Involving Joins
In general , vie\vs that involve joins of base tables can cat1se problem s wh en ttpdating
data. Co11sider the rela tively simple REP_CUST vie'.v, for example, described ea.rlier (see
Fig11res 7-7 and 7-8). The fa.c t that som e columns in the 11nde rly ing base tables are 11ot
incl11ded in this view prese11ts som e of tl1e sam e problem s discussed earlier. 1\sst1ming that
yo11 can overcom e these problems by using nttlls, tl1ere are m ore seriotts problem s when
attempting to ttpdate the d atabase tl1ro11gh thls vievv. On the s11rface, ch anging the r ow
(' 15' , 'Campos ' , 'Rafael', '126' , ' T oys Galore') to (' 15 ' , 'Campos' , 1J11an ' , 1 126' , 'Toys
Galore'), might n ot appear to pose any problems other tl1an som e inconsistency in the data.
(In the n evv vers ion of tl1e ro'.v, the 11ame of sales rep 15 is J11an Campos; whereas in tl1e
second ro,v in the table, the name of s ales rep 15, the same sales rep , is Rafael Campos.)
Database Administration
Tl1e problem is act11ally mo re serio11s tl1an that- malti11g this change is no t possible.
Tl1e 11ame of a sales rep is stored only once in tl1e 11nderlying REP table. Cl1anging the
name of sales rep 15 from Rafael Ca1npos to J11an Campos in tllis 011e row of tl1e vievv
ca11ses th e change to be made to the single row for sales rep 15 in tl1e REP table. Beca11se
tl1e vievv simply displays data from the base tables, for eacl1 r ov,1 on wl1icl1 tl1e sales rep
number is 15, tl1e sales rep 11ame is 110"'' Juan Campos. In o tl1e r v,1o rds, it appears tl1at tl1e
same cl1ange h as been made in the other rovvs. In tl1is case, this cl1ange ens11res consistency in the data. In general, l1ovvever , tl1e 11nexpected changes ca11sed by an 11pdate are
not desir able.
Before concl11ding tl1e topic of views that involve joins, yo11 sho11ld note that all joins do
not c reate tl1e precedit1g problem . Wl1en tvvo base tables l1ave the same pritnary l{ey and the
primary lcey is 11sed as tl1e join col11mn, 11pdating tl1e database 11sing the vievv is not a
problem. For example, suppose tl1e act11al database co11tains two tables (REP_DENIO and
REP_FIN) instead of one table (REP). Fig11re 7-13 sl1ovvs tl1e data in the REP_DEMO table.
Home
SOL Workshop
0 Autocommil
Rows
SQL Commands
I.., IV 4>
110
( Save )( Run )
SD.ECI *
FROM R.EP_DEMO;
j~esults f pla n Oescr be Saved SOL History
15
Campos
Rafael
724 Vinca Dr
Grove
CA
90092
30
Gradey
Megan
632 Liatris St
Fullton
CA
90085
45
Tian
Hui
1785 Tyler Ave.
Northfield
CA
90098
60
Sefton
Janel
267 Oakley St
Congaree
CA
90097
Download
4 rows returned in 0.03 seconds
FIGURE 7-13
Data in the REP DEMO table
Fig11re 7-14 shows the data in tl1e REP_FIN table.
Home
SOL Workshop
0 Autocommil
Rows
SQL Commands
[10
1v I
V 4>
( Save )( Run )
SELECI *
FROM R.EP_FIN;
Results F plain Oescr be Sllved SOL History
-
-
REP_NUII
CoiMSSlON
RATE
15
23457.5
.06
30
41317
.08
45
27789.25
.06
60
0
.06
4 rows returned in 0.01 seconds
FIGURE 7-14
Download
Data in the REP FIN table
\\Tl1at v,1as once a si11gle table i11 tl1e o riginal TAL Dis tributo rs design has been divided
into two separate ta bles. Users v,1ho 11eed to see tl1e rep data it1 a sit1gle table ca11 use a
Chapter 7
view named SALES_REP that joins tl1ese two tables 11sing tl1e REP_NUM col11mn. Tl1e
defining q11ery for the SALES_REP vie\v appears in Fig11re 7-15 .
Home
SQL Wooohop
Schema ~
SQL Commands
/
21 Autocommit
Rows
1--IV .f
110
( Save )( Run )
Name of '
view
I
CREATE VIEt-l SALES REP AS·
SELECT REP DEMO.REP NUM, L.11.ST NAME, FIRSI_ NAME, STREET, CITY, STATE, POSIAL_ CODE, COML{ISSION, !lll.IE
FROM REP_DEM<>, REP_Fill :
WHERE REP_DEMO.REP_NOM = REP_FIN.REP_NUM;
Results [ ·plain Descnbc
__,
I Uy
Saved S•1L
.
View j oins
REP _DEMO and
REP_FIN tables
View creat.ed.
""
0.02 seconds
FIGURE 7-15
Creating the SALES_REP view
Tl1e data in the SALES_REP vie\v appears in Figt1re 7-16.
Home
SQL Workshop
ElJAutocommit
Rows
Schema PRATT/LA ST
SQL Commands
I" I V ,?
110
( Save )( Run )
SELECT 4
FROM SAJ.•S_REP;
Results
- pla n Describe
Saved SQL
History
J
15
Campos
Rafael
724 Vinca Dr.
Grove
CA
90092
23457.5
.06
30
Gradey
Megan
632 Liatrls Sl
FuUton
CA
90085
41317
.08
45
Tian
Hui
1785 Tyler Ave.
Northfield
CA
90098
2778925
.06
60
Sefton
Janet
267 Oakley St
Congaree
CA
90097
0
.06
4 rows returned in 0.01 seconds
FIGURE 7-16
Download
Data in the SALES REP view
It is easy to 11pdate tl1e SALES_REP view. To add a TO\\' , use an INSERT co1nmru1d to
add a r o\.,, to eacl1 11nderlying base table. To update data in a row, 1nalte the change in tl1e
appropriate base table . To dele te a ro\.V from tl1e vie\.v, dele te the co rresponding ro\.\'S from
bo tl1 11nderlying base tables.
Question: Ho,v would you add the ro,v (' 10' ,' Peters' ,'Jean',' 14 Brink' ,' I-Iolt' ,' CA',
1
90083 1 ,107.50,0.05) to the SALES_REP view?
Ans,ver: Use an INSERT command to add the row (' 10' ,'Peters', 'Jean' ,' 14 Brink' ,
' I-Iolt' ,' CA' ,'90083') to the REP_DEMO table, and then use another INSERT command to
add the row (' 10' ,107.50,0.05) to the REP_FIN table.
Database Administration
Question: I-low would you change the name of sales rep 30 to Geneen Gradey?
Answer: Use an UPDATE command to change the name in the REP_DEMO table.
Question: liow would you change Geneen's commission rate to 0.07?
Ans,ver: Use an UPDATE command to change the rate in the REP_FIN table.
Question: I-low would you delete sales rep 30 from the REP table?
Answer: Use a DELETE command to delete sales rep 30 from both the REP_DEMO and
REP_FIN tables.
Updates (addition s, changes, or deletions) to tl1e SALES_REP vie\.v do not ca11se a11y
problem s. 'fhe main reason that tl1e SALES_REP vie\.\' is 11pdatable and that other vie\.vs
involvin g joins migl1t n ot be 11pdatable-is tl1at this vie\.v is derived from joining two base
tables on the primary key of each table. In co11trast, tl1e REP_ CUS'f vie\.v is created by joining t\.vo tables by m atching the primary Irey of one table with a col11mn that is not the primary Irey in the otl1er table. \\Then n either of tl1e join col11mns in a view is a primary Irey
col11mn, 11sers \.Vill enco11nter eve11 more severe problems wh en attempting to malre updates.
Updating Views Involving Statistics
A vie\v that i11volves statis tics calculated from 011e or more base tables is the most troublesome
view wl1en atten1pting to update data. Consider tl1e CRED_CUST view, for example (see
Figure 7-10). Ho\.\' v.rould you add tl1e ro\.V 9000,3 to indicate tl1at tllere are three customers
tl1at l1ave credit li1nits of $9, 000 eacl1? Lilre\\rise, changing tlle ro\.v 5000,2 to 5000,5 mea11s you
are adding tlu·ee 11e\.v customers \.vitl1 credit limits of $5,000 eacl1, for a total of five customers.
Clearly tllese are impossible tasks; you caru1ot add ro\.vs to a view tl1at includes calculations.
DROPPING A VIEW
\\'11en a view is no longer n eeded, yo11 can remove it 11sing the DROP VIEW command.
EXAMPLE 5
The TYS view is no longer necessary, so delete it.
Chapter 7
Tl1e connnand to dele te a vie\V is DROP VIEW, as show11 i11 Figure 7-17.
Home
SOL Workshop
~Autocommit
SQL Commands
Rows
110
1vlV .P
( Save ) ( Run )
DROP VIE'R 1YS;
Results
- plain
Desalbe
Saved SOL History
'View dropped.
0.02 seconds
FIGURE 7-17
Dropping a view
ACCESS
USER
NOTE
Access does not support the DROP VIEW command. To drop a view, delete the query object you saved
when you created the view.
SECURITY
Security is tl1e prevention of t1nautl1orized access to a database. \\Titllin an organization,
tl1e database adnlinistrator determil1es tl1e types of access variot1s t1sers need to tl1e database. Some ttsers might need to retrieve and ttpdate ai1ytl1ing in the database. Other ttsers
1nigl1t 11eed to retrieve any data from tl1e database but not make any cha11ges to it. Still
otl1er users migl1t need to access only a portio11 of the database. For example, Bill migl1t
11eed to retrieve and update custo1ner data, but does not need to access data about sales
reps , orders, order li11es, or items. Valerie might need to retrieve ite1n data and notlling
else. Sam might need to retrieve and t1pdate data 011 items in the TOY category, but does
11ot need to retrieve data in any other categories.
After tl1e database admillistrator l1as determined tl1e access different t1sers of tl1e
database 11eed, tl1e DENIS enforces these access rtues by whatever security mecl1a11ism the
DBMS sttpports. Yott ca11 ttse SQL to enforce t\vo security mecl1anisms. Yott ah·eady have
seen that vie\vs fur11isl1 a certain a1nount of secttrity; when ttsers are accessi11g the database throttgh a vie\v, they ca11not access any data tl1at is 11ot inclttded in the vievv. The
1nai11 111ecl1anism for providing access to a database, ho\.\rever, is the GRANT command.
Tl1e basic idea of the GRANT com1nand is that the database admi11istrator can grant different types of privileges to ttsers and the11 revoke tl1em later, if 11ecessary. These privileges
i11cl11de the rigl1t to select, i11sert, update, and delete table data. Yott cai1 grant and revolie
ttser privileges t1si11g tl1e GRANT and REVOI<E co1nmands. Tl1e following exainples illustrate
variotts ttses of the GRANT co111111and when the na1ned ttsers already exist in the database.
NOTE
Do not execute the commands in this section unless your instructor asks you to do so.
Database Administration
EXAMPLE 6
User Johnson must be able to retrieve data from the REP table.
Tl1e follo\.ving GRANT co1n1nand permits a t1ser na1ned Jol111son to execute SELECT
commands for the REP table:
GRANT SELECT ON REP TO JOHNSON;
EXAMPLE 7
Users Smith and Brown must be able to add new items to the ITEM table.
Tl1e following GRANT co1nn1and permits t\.,,o users named Smith and Brown to execute
INSERT conunands for tl1e ITENI table. Notice tl1at a co1n1na separates tl1e user names:
GRANT INSERT ON ITEM TO SMITH, BROWN;
EXAMPLE 8
User Anderson must be able to change the name ai1d street address of customers.
Tl1e following GRANT command permits a t1ser named Anderson to exec11te UPDATE
commands involving the CUST01'1ER_NAME and STREE'f colt1mns in tl1e CUSTOMER
table. Notice tl1at the SQL command incl1.1des the col11mn names in parentheses before
tl1e ON clat1se:
GRANT UPDATE ( CUSTOMER NAME, STREET) ON CUSTOMER TO ANDERSON;
EXAMPLE 9
User Thompson must be able to delete order lines.
Tl1e follo\.\ring GRANT co1n1na11d per111its a t1ser 11a1ned Thompson to execute DELETE
co1ru11a11ds for the ORDER LINE table:
GRANT DELETE ON ORDER LINE TO THOMPSON;
EXAMPLE 10
Every user must be able to retrieve item numbers, descriptions, and categories.
Chapter 7
Tl1e GRANT co1runa11d to i11dicate tl1at all users cai1 retrieve data t1sing a SELECT
conuna11d i11clt1des tl1e \.Vord PUBLIC, as follo\,rs:
GRANT SELECT (ITEM NUM, DESCRIPTION, CATEGORY) ON ITEM TO PUBLIC;
EXAMPLE 11
User Roberts must be able to create an index on the REP table.
You \.Vill lear11 abot1t it1dexes and their t1ses in the next sectio11. Tl1e follo\.vil1g GRANT
command per1nits a t1ser 11amed Roberts to create an index 011 tl1e REP table:
GRANT INDEX ON REP TO ROBERTS;
'
EXAMPLE 12
User Thomas must be able to change the structure of the CUSTOMER table.
Tl1e followi11g GRANT comm and permits a t1ser named Thomas to exect1te ALTER
commands for the CUSTOMER table so h e can change tl1e table 's s trt1ctt1re:
GRANT ALTER ON CUSTOMER TO THOMAS;
EXAMPLE 13
User Wilson must have all privileges for the REP table.
Tl1e GRANT co1nma11d to i11dicate tl1at a t1ser l1as all privileges i11cludes tl1e ALL
privilege, as follo\.vs:
GRANT ALL ON REP TO WILSON;
Tl1e privileges tl1at a database ad1ni11istrator can grai1t are SELECT to retrieve data,
UPDATE to cl1ange data, DELETE to delete data , INSERT to add 11e\.\r data , INDEX to create a11 i11dex, a11d ALTER to cl1a11ge tl1e table strt1ctt1re. Tl1e database ad1ni11istrator t1st1ally assig11s privileges. Nor111ally, wl1e11 tl1e database ad111inistrator gr a11ts a partict1lar
privilege to a user , the user ca1111ot pass that privilege along to other users. \\Tl1en the user
11eeds to be able to pass tl1e privilege to otl1er t1sers, tl1e GRANT com111and 1nust i11clt1de
tl1e WITII GRJ\.i~T OPrION clause. Tllis clause gra11ts tl1e i11dicated privilege to tl1e t1ser
and also pern1its tl1e user to grant tl1e san1e privileges ( or a subset of tl1em) to o tl1er users.
Tl1e database ad111i11istrator t1ses tl1e REVOl(E com1na11d to revolre privileges fro1n
t1sers. Tl1e for1nat of tl1e REVOI<E com1na11d is esse11tially the sa111e as tl1at of tl1e GRANT
com1na11d, bt1t \.Vitl1 two differe11ces: tl1e word GRANT is replaced by tl1e word RE\TOICE,
a11d tl1e word TO is replaced by tl1e word FROM. 111 addition, tl1e clat1se \\TITH GRANT
Database Administration
OPTION obvio11sly is n ot m eaningful as part of a REVOIIB command. Incidentally, the
revol{e cascades, so if Jol1nso11 is gr anted privileges \\TITH GRANT OPTION and tl1en
Jol1nson gr ants these sam e privileges to Smitl1, revoltit1g tl1e privileges from Joh11son
revol{es Smith's privileges at tl1e sam e time. Example 14 ill11strates the 11se of the
REVOI(E con1mand .
EXAMPLE 14
User Johnson is no longer allowed to re trieve data from the REP table.
Tl1e follo\.vi11g REVO l(E co1n111ru1d revol{es the SELECT privilege for tl1e REP table
from tl1e 11ser n a1ned Jol111so11:
REVOKE SEL E CT ON REP FROM JOHNSON;
Tl1e d atabase ad1ni11istrator ca11 also apply tl1e GRANT and REVOIIB co1111na11ds to
viev.rs to restrict access to only certai11 ro\.\'S \.Vitl1i11 tables.
INDEXES
\,\Tl1en yo11 q11e ry a data base, yo11 a re 11s11ally sea rcl1i11g fo r a r o\.V (or collection of ro\.vs)
tl1a t satisfies som e condition . Examining every r o\.v in a table to find the on es you n eed
often tal{es too m11ch time to be practical, esp ecially i11 tables with tho11sands of ro\.vs.
Fortunately, yo11 can create and 11se an index to speed up tl1e searching process significantly. An i11dex in SQL is si1n ilar to an index iI1 a bool{. \,\,T}1en you \.Vant to find a discu ssion of a given topic in a bool{, yo11 co11ld scan tl1e e11tire bool{ from sta rt to finisl1, lool{ing
for refer en ces to tl1e topic you n eed . More than lli{ely, h o\.\rever , you \.VOttld n ot l1ave to
resort to this tech 11iqu e. If tl1e bool{ l1as a good index , you could 11se it to ide ntify the
pages on \.Vhicl1 yo11r topic is disc11ssed .
111 a DBMS, tl1e mai11 m ecl1anism fo r inc reasing the effic iency v.ritl1 wh ich data is
retrieved from tl1e database is tl1e index . Concept11ally, tl1ese indexes are very m11cl1 lil{e
tl1e index in a b ool{. Con sider Fig11re 7-18, for example, whicl1 sh ows tl1e CUSTOMER
ta ble for TAL Distrib11tors togetl1er \.Vitl1 on e extra col11mn n runed ROW_NUNIBER. This
extra col11mn gives tl1e location of tl1e row in the table (c11sto1ner 126 is tl1e firs t ro\\' in
tl1e ta ble and is on ro"'' 1 , c11s tom er 260 is on row 2, and so on ). The DBMS-no t the
user-autom atically assign s and 11ses tl1ese row n11mbers, a nd tl1at is \.vhy yo11 do not
see tl1em .
Chapter 7
CUSTOMER
ROW_NUM
CUSTOMER_NUM
CUSTOMER_NAME
STREET
C ITY
STATE
POSTAL_ CODE
BALANCE CREDIT _LIMIT REP_NUM
1
126
Toys Galore
28 Laketon St.
l•'u.llton
90085
$1,210.25
$7,500.00 15
2
260
Rroukin~ Direct
452 Columhus Or. Grove
90092
$575.00
$10,000.00 30
3
JJ4
The Everything
Shop
342 ~lagee St.
Conga ree
CA
CA
CA
90097
$2,3-15. 75
$7,500.00 45
-I
386
Johnson's
Dcrn1 r1111c111
Store
12-1 l\lain St.
Northfield
CA
90098
$8~ ( 9 .2~
$7,500.00 30
5
440
Grove
3456 Cenrr:il Ave.
Fullton
CA
90085
$.145.00
$5,000.00 45
167 Ila.le Sr.
Alcsa
CA
9010-1
$5,025.75
$5,000.00 15
3345 Devon Ave.
Alrnondton CA
90U5
$3,456.75
$15,000.00 45
CA
90092
$678.90
CA
90097
90098
$4,23-1. <>0
$12-1.75
$ 7,500.00 30
$10,000.00 15
$7,500.00 -15
90104
90085
$2 ,-175.99
$935.75
I listorical
Musewn Store
6
502
7
586
s
665
71.'.l
796
Cricket Gitt Shop
Cre~.s Store
Unique Gifts
372 Oxford St.
Grove
12 Rising S1u1 Ave. Congaree
786 P:issmo,·e St. Norchlield
824
Kline's
S9J
t\JJ Season Giits
945 Gill ,arn St.
Ales,1
382 \\'ildwood Ave. l•'ullton
9
]()
11
I 12
FIGURE 7-18
Cards and More
Ahnonclton
General Store
CA
CA
CA
$15,000.00 .10
$7 500.00 15
CUSTOMER table with row numbers
To access a c1.1sto1ner's ro"v 1.1sing its ci1stomer 11umber, yot1 might create and use an
index, as sl1o"v11 in Figure 7-19. The index l1as t\,VO colu111ns: the first colt11nn contains a
ci1stomer 11umber, and the second coliu1111 co11tains the 11umber of tl1e ro"v on whicl1 tl1e
ct1stomer 11umber is fou11d. To fit1d a ct1stomer, loo!{ up the customer's number i11 tl1e fit·st
coli1mn in the i11dex. The vali1e in tl1e second coli11nn indicates \,Vllich row to retrieve
from the CUSTOMER table, then tl1e ro"v for tl1e desired ci1sto111er is retrieved.
CUSTOMER_NUM Index
CUSTOMER_NUM ROW_NUMBER
126
1
260
2
33-!
3
386
4
440
502
586
665
713
796
5
824
893
FIGURE 7-19
6
7
'
'
8
9
IO
11
12
Index for the CUSTOMER table on the CUSTOMER NUM column
Becat1se ct1sto1ner 11t11nbers are t1niqt1e, there is 01tly a si11gle row nt1111ber in this
i11dex. Tllis is 11ot al"vays the case, l1o"vever. St1ppose yoi1 11eed to access all ci1sto1ners
v.ritl1 a specific credit li111it or all ct1stomers represe11ted by a specific sales rep. Yot1 1nigl1t
Database Administration
choose to crea te and t1se an index on tl1e CREDIT LIMI'f colt1m11 and an index on tl1e
REP_NUM colt1mn, as sl1own in Figure 7-20. In the CREDIT_LIMIT index, the first colt1mn
contains a credit limit and tl1e seco11d colt1mn contait1s tl1e nt1mbers of all ro\\'S 011 \Vl1icl1
tl1at credit limit appears. The REP_NUM index is similar, except tl1a t the firs t colt1mn
contains a sales rep nt1mber.
CREDIT_LIMIT Index
REP_ NUM Index
CREDIT_LIMIT ROW_NUMBER
I
-
REP _NUM ROW_NUMBER
$5,000.00 5,6
$7,500.00 1,3, 4,8, 10, 12
30
1,6, 9, 12
2,4,8, 11
$1 0,000.00 2,9
45
3,5, 7, 10
$15,000.00 7, 11
FIGURE 7-20
15
I
'
I
Indexes for the CUSTOMER table on the CREDIT- LIMIT and REP- NUM columns
Q11estion: I-low would you use the index shown in Figure 7-20 to find every customer
with a .$10,000 credit limit?
Ans,ver: Look up $10,000 in the CREDIT_LIMIT index to find a collection of row numbers (2 and 9). Use these row numbers to find the corresponding rows in the CUSTOMER
table (Brookings Direct and Cress Store).
Question: I-low would you use the index shown in Figure 7-20 to find every customer
represented by sales rep 30?
Answer: Looli up 30 in the REP_NUM index to find a collection of row numbers (2, 4, 8,
and 11). Use these row numbers to find the corresponding rows in the CUSTOMER table
(Brookings Direct, Johnson's Department Store, Cricket Gift Shop, a.n d Kline's).
Tl1e actual strt1cture of an index is more complicated tl1an wl1at is sl1own in the figures. Fortunately , yot1 do 11ot have to \Vorry abot1t the details of 1nanipula ting a11d t1sing
indexes because the DBMS manages the1n for yo11-yot1r o nly job is to determine tl1e colum11s on \Vhicl1 to bt1ild tl1e indexes. Typically, yot1 can create a11d mai11tait1 an index for
any colt1mn or combmation of colt1mns in any table. After c reating an index, the DBMS
t1ses it to speed ttp data re trieval.
As you wot1ld expect , the t1se of any index has adva11tages and disadvantages. An
important advantage was already mentioned: an mdex makes certain types of retrieval
more efficient.
Tl1ere are two disadvantages wl1en t1sing indexes. First, an index occt1pies storage
space. Using this space for an index, however, is technically t1nnecessary becat1se any
Chapter 7
retrieval tl1at yot1 can malre t1sing an index also can be m ade \.Vitl1ot1t the index ; the index
just speeds tip the re trieval. The second disadva11tage is tl1at the DBMS mt1st t1pdate the
index \.Vl1e11ever corresponding data in the database is t1pdated. vVitl1out tl1e index, tl1e
DBMS "''Ot1ld not need to malre tl1ese t1pdates. The main qt1estion tl1at yot1 must aslr when
co11side ring wl1etl1er to crea te a given il1dex is tl1is: do the benefits derived during
retrieval ot1t\.veigh the additional storage reqt1ired and tl1e extra processing involved in
t1pdate operations? In a very large database, yot1 might find that indexes are essential to
decrease the time reqt1ired to re trieve records. h1 a small database, 110\.\reve r, an index
migl1t not provide any significant be 11efits.
Yot1 can add and drop indexes as n ecessary. Yott can crea.te an index afte r the database is bt1ilt ; it does 11ot need to be created at tl1e sam e time as tl1e database. Lilrewise,
when an existing index is no longer necessary, you can drop it.
Creating an Index
Suppose some users at TAL Dis tributors 11eed to display custo1ner records order ed by balance. Otl1er users 11eed to access a cus tomer 's na1ne using the customer's 11u111ber. In
addition, som e users 11eed to produce a report in \\rhicl1 customer records are lis ted by
credit li1nit in descendi11g order . V\Tithit1 the group of custo1ners l1avi11g the same credit
limit, the custom er records mus t be order ed by name.
Eacl1 of the previous r eqt1il·ements is carried out m ore efficie ntly wl1en you create the
appropriate il1dex. Tl1e co111111a11d used to create a11 index is CREATE INDEX, as illustrated il1 Example 15 .
EXAMPLE 15
Create an index named BALIND on the BALANCE column in the CUSTO~IER table.
Create an index named REP- NAME on the combination of the LAST- NAME and
FIRST- NAME columns in the REP table. Create an index named CRED- NAME on
the combination of the CREDIT- LIMIT and CUSTO~R- NAME columns in the
CUSTO~R table, with the credit limits listed in descending order.
Tl1e CREATE INDEX co1nma11d to create the it1dex 11runed BALIND appears il1 Figure 7-21 .
Tl1e com111ru1d lists tl1e 11a1ne of tl1e il1dex ru1d tl1e table 11ame 011 \.Vl1icl1 tl1e il1dex is to be
created . Tl1e colt1m11 on "''l1ich to c reate tl1e il1dex-B1\LANCE--is listed il1 pare11tl1eses.
Home
SQL Workshop
E21Autocomm11
Rows
SQL Commands
110
1--1v.?
( Save )( Run )
CREJI.IE INDEX BALIND ON CUSTOl€R (BAL.l\.NCE) ;
Results [ p 111 Descnbe saved SOL
History
--'
Index creai:ed.
,0.10 seconds
FIGURE 7-21
Creating the BALIND index on the BALANCE column
Database Administration
The CREA'fE INDEX command to create tl1e i11dex named REP NAME 011 the combinatio11 of tl1e LAST_NANIE and FIRST_NAME col11mns in the REP table appears in Fig11re 7-22.
I l Home
SQL Commands
SQL Wol'IIShop
6Zl Autocommll
I1H
Rows
lvlV~
( Save ) ( Run )
-
CRD.IE INDEX REP NJI.ME ON REP ( L.1>..ST IP.ME, FIRST NAME ) ;
-
Results
plain
Oescnbe
saved SOL
-
H story
Index creaced .
0.01 seconds
FIGURE 7-22
Creating the REP_NAME index on the LAST_NAME and FIRST_NAME columns
Tl1e CREATE INDEX colllln and to c rea te tl1e inde x named CRED NAME on the
combina tion of the CREDIT- LIMIT a nd CUSTOMER- NAME col11mns in the CUSTOMER
ta ble appears in Figure 7-23. \Vhe11 yo1111eed to index a col11mn in descending orde r , the
col1.1mn name is follo\.ved by tl1e DESC op erator .
Home
SQLWorllshop
6Zl Autocommit
SQL Commands
Rows
110
!vlV~
( Save ) ( Run )
-
-
CREATE INDEX CRED NAME ON CUSTOMER(CREDIT Ln1IT DESC, CUSTOMER NAME) ;
-
Results _ plam Oescnbc Saved SQL History
Descend ing
order
Index crear.ed.
10.03 seconds
FIGURE 7-23
Creating the CRED_NAME index on the CREDIT_LIMIT and CUSTOMER_NAME
columns
\\The n cus tom er s are listed 11sing tl1e CRED_NAME inde x , the records appear in
descending order by cr edit limit. Within any c redit limit, the c11s tom er s are listed
alpl1abe tically by 11ame.
ACCESS
USER
NOTE
Access supports the creation of indexes in both SOL view and Design view. You can write a CREATE
INDEX command in SOL view. You can also open the table containing the column(s) on which you want to
create an index in Design view, and click the Indexes button or use the Indexes property to create the index.
Dropping an Index
Tl1e co111111a11d 11sed to drop ( dele te) a11 i11dex is DROP INDEX, \.Vl1icl1 co11sists of tl1e
\.Vords DROP INDEX follo,ved by tl1e 11a111e of tl1e i11dex . To dele te tl1e CRED_NAME il1dex
on the CUSTOMER table, for ex ample, the co1111nand is:
DROP INDEX CRED NAME;
Chapter 7
Tl1e DROP INDEX command pe rma11ently deletes the index. CRED_NANIE \.Vas tl1e
index tl1e DBMS t1sed when lis ting cu stom er records in descending order by credit limit
at1d then by ct1s to1ne r name \.Vithin credit limit. The DENIS still can list ct1stomers i11 tllis
order; h owever , it cannot do so as efficiently without the index.
SQL SERVER
USER
NOTE
The SQL Server command to drop an index requires that you qualify the index name. To delete the
CRED_NAME index on the CUSTOMER table, for example, the command is:
DROP INDEX CUSTOMER . CRED NAME;
Creating Unique Indexes
\\'11en yot1 sp ecify a table's primary l{ey, tl1e DBMS at1tomatically e11sures tl1at tl1e valt1es
entered in the p1imary l{ey colt1m11(s) are u11iqt1e. For example, the DBMS rejects an
attempt to add a second cus tom er \\'h ose 11t1mbe r is 126 in tl1e CUSTONIER table because
cu stomer 126 already exists. Tht1s, you do 11o t need to tal{e a11y special action to mal{e
sure tl1at valt1es in the primary l{ey column ai·e unique; tl1e DBMS does it for yot1.
Occasionally, a n o11primary l{ey colunn1 migl1t s tore uniqt1e values. Fo r example, in
tl1e REP table, tl1e primary l{ey is REP_l\TUM. If tl1e REP table also contains a column for
Social Secu1ity nt1mbe rs, the values ill tllis colt1mn also mt1st be uniqt1e b ecat1se n o two
people can l1ave tl1e same Social Sect1rity 11umber. Because the Social Security number
colum11 is 11ot tl1e table's primary l{ey, l1owever , you 11eed to tal{e special actio11 i11 order
for tl1e DBMS to en st1re that tl1e re are no duplica te valt1es in tl1is colt1m11.
To ensure tl1e t1niqt1e11ess of values in a 11onprimary key column, yot1 can create a
1111ique index by u sing tl1e CREATE UNIQUE INDEX comn1at1d. To create a t1nique index
11atned SSN on tl1e SOC_SEC_NUM colt1mn i11 the REP table, for exatnple, the comma11d is:
CREAT E UNIQUE INDEX SSN ON REP ( SOC S E C NUM) ;
Tl1is t1nique index l1as all tl1e prop erties of indexes already disct1ssed, along \.Vitl1 one
additional property: tl1e DBMS rejects a11y t1pdate that cat1ses a duplicate value in tl1e
SOC_SEC_NUM colt1mn. In tllis case, tl1e DBNIS r ejects tl1e addition of a re p wl1ose Social
Security 11t1mbe r is tl1e same as tl1at of a.nothe r r ep already in tl1e database.
SYSTEM CATALOG
I11forn1atio11 about tl1e tables ill the d atabase is l{ept ill tl1e system catalog (catalog) or tl1e
data dictionary. Tllis sectio11 describes tl1e types of ite1ns ke pt ill tl1e catalog a11d the \\ray
i11 wl1ich you ca11 qt1e ry it to access i11formatio11 abot1t tl1e d atabase s trt1c ture.
Tl1e DBMS auto111atically 1nai11tai11s tl1e systen1 catalog, \\'hicl1 co11tai11s several tables. The
catalog tables yot1 "''ill co11sider i11 tllis basic introductio11 are SYSTABLES (iI1for111atio11 abot1t
tl1e tables lu10\.v11 to SQL), SYSCOLlTh1INS (illformatio11 abot1t tl1e colt1m11s "''itl1i11 these
tables), a11d SYSVIEWS (i11for1natio11 abot1t tl1e vie\\'S that l1a,,e bee11 created). It1dividual SQL
imple1ne11tatio11s 1nigl1t t1se diffe re11t na1nes for tl1ese tables. 111 Oracle, tl1e eqt1ivale11t tables
are 11a1ned DBA_TABLES, DBA_TAB_COLlTh1INS, and DBA_VIEWS.
Database Administration
Tl1e system catalog is a relational data base of its ow11. Conseqt1ently, yot1 can t1se tlle
same types of qt1eries to retrieve information that yot1 can t1se to retrieve data in a relational database. You can obtain information abot1t tl1e tables in a relational database, tl1e
coli1mns tl1ey contaiI1, and tl1e views bt1ilt on tl1em from tl1e system catalog. Tl1e following
examples illustrate tllis process.
NOTE
Most Oracle users need privileges to view system catalog data, so you might not be able to execute
these commands.
ACCESS
USER
NOTE
In Access, use the Documenter to obtain the information discussed in this section, rather than querying
the system catalog.
SQL SERVER
USER
NOTE
In SOL Server, use stored procedures to obtain the information discussed in this section. To display
information about the tables and views in a database, use the sp_tables procedure. For example, the
following command displays all the tables and views in the current database:
EXEC sp_ tables
The sp_columns stored procedure displays information about the columns in a particular table. The following command displays the column information for the REP table:
EXEC sp_ columns REP
EXAMPLE 16
List the name of each table for which the owner ( creator of the table) is PRATT.
Tl1e co1111na11d to lis t tl1e table 11runes ov.1ned by PRATT is as follo\\1S:
SELECT TABLE NAME
FROM DBA TABLES
WHERE OWNER = PRATT ;
1
1
Tl1e \VHERE clat1se restricts tl1e tables to only tl1ose ow11ed by PRATT. 111 respo11se to
tl1is co1n1nand, Oracle \Vill prodt1ce a list of all tl1e appropriate tables.
Chapter 7
EXAMPLE 17
List the name of each view o,vned b y P~~TT.
Tl1is command is similar to tl1e con1m a11d in Example 16. Ra ther tha n TABLE_NAME ,
tl1e coli1mn to be selected is n amed VIE,v - NAME . Tl1e selectio11 is from DBA- ,TJE,VS
ratl1er tha 11 DBA TABLE. Tl1e command is tl1t.1s:
S EL E CT VIEW NAME
FROM DBA VI EWS
WHERE OWNER
= P RATT' ;
1
EXAMPLE 18
For the CUSTOMER table owned by PRATT, list each column and its data type.
Tl1is com111and selects from the DBA_TAB_ COL1TuINS table:
S EL E CT COLUMN NAME , DATA TYPE
FROM DBA TAB COLUMNS
WHERE OWNER = ' P RATT'
AND TABLE NAME = 'CUSTOMER' ;
EXAMPLE 19
List each table owned by PRATT that contains a column named CUSTOMER_NUM.
In tl1is case, the COLUMN_NAME col1.1mn is t.1sed iI1 tl1e ,\THERE clat.1se to restric t tl1e
rovvs to those on vvllich the colt.1mn n am e is CUST OMER NUM. The command is:
S ELE CT TABL E NAME
FROM DBA- TAB- COLUMNS
1
WHERE OWNER= P RATT
AND COLUMN NAME =
1
1
CUSTOMER NUM ' ;
Update of the System Catalog
,\Then users c reate, alte r , or drop tables o r create o r drop indexes, tl1e DBMS updates
tl1e syste m catalog auton1atically to r eflect tl1ese cl1anges. Users sh ou ld n ot execute
SQL queries to update tl1e catalog d irectly because this might produce i11consis tent
i11formation . For exa111ple , wl1en a user deletes tl1e CUST OMER_N1TuI colun1n in the
DBA_TAB_COLUMNS table , the DENIS wot.1ld 110 lo11ger h ave any lu1ovvledge of this column , v,,hich is tl1e CUST OMER table's prilnary Irey, yet all the rov,,s in the CUSTOMER
table v.rou ld s till contai11 a cu sto1ne r number . The DENIS might 110w treat those cus tom er
Database Administration
n11mbers as names, beca11se as far as the DBMS is concerned , the col11mn named
CUSTONIER NAME is tl1e firs t col11mn i11 tl1e CUST011ER table.
INTEGRITY CONSTRAINTS IN SQL
An integ1ity constraint is a 1ule fo r tl1e data in tl1e database. Examples of integrity co11s traints in the TAL Distrib11tors database are as follo\\TS:
•
•
•
A s ales rep's n11mber must be 1111ique.
Tl1e sales rep 1111mber for a custom er m11st 1natcl1 tl1e 1111mber of a sales rep
c11rrently in tl1e database. For example, because ther e is 110 sales rep n11mber
11, a c11stom e r cannot be assig11ed to sales rep 11.
Categories for items m11s t be GNIE, TOY, or PZL because tl1ese are tl1e only
valid categories.
If a user enters data in the da tabase tl1at violates any of tl1ese integ1ity constraints,
tl1e database develops serious proble1ns. For example, t\\TO sales reps \\Tith tl1e sam e number, a custom er \\Tith a nonexis te11t sales rep, o r an item i11 a 11onexistent category wo11ld
compromise the integrity of data in the database. To manage tl1ese types of problem s,
SQL provides integrit1' support, the process of specifying and e11for cing integrity co11s traints fo r a database. SQL l1as clauses to support three types of i11tegrity co11straints that
you can specify witllin a CREATE TABLE or an 1\LTER TABLE comma11d. The only diffe rence be t,veen tl1ese two commands is tl1at an ALTER TABLE command is follo\\Ted by
tl1e word ADD to i11dicate that you are addi11g the constraint to tl1e list of existing co11s traints. To cl1a11ge a11 integrity constraint after it has been created , j11st enter the 11ew
constraint, wl1icl1 ilnmediately tal{es tl1e place of tl1e o riginal.
Tl1e types of co11strai11ts supported in SQL are p1imary keys, foreign keys, and legal
values. In 1nost cases, yo11 specify a table's prilnary l{ey vvl1e11 you create the table. To add
a prin1ary l{ey after cr eating a table, you ca11 11se tl1e ADD PRD1IARY IffiY cla11se of tl1e
ALTER TABLE command. For example, to indicate tl1at REP_NUM is the pri1nary l{ey for
tl1e REP table, the ALTER TABLE command is:
ALTER TABL E REP
ADD PR IMARY KE Y (REP NUM) ;
Tl1e PRIMARY ICEY clause is PRINIARY ICEY followed by the column 11ame that 1nal{es
up the primary key in parentheses. ~'11en tl1e p1imary l{ey contains m or e tl1an 011e colu1n 11, u se commas to separate the column 11ames.
ACCESS
USER
NOTE
To specify a table's primary key in Access, open the table in Design view, select the column(s) that
make up the primary key, and then click the Primary Key button on the ribbon.
A foreign key is a coluID11 i11 011e table \\rl1ose values 111atcl1 tl1e p1imary key i11 a11otl1er
table. ( 0 11e example is tl1e CUSTOMER_l\Tl.JM colunm i11 the ORDERS table. \ Talues i11 tl1is
colu1n11 are required to match those of tl1e prilnary l{ey i11 the CUSTOMER table.)
Chapter 7
EXAMPLE 20
Specify the CUSTOMER_mI column in the ORDERS table as a foreign key that must
match the CUSTOMER table.
\\Tl1en a table co11tains a foreigi1 key , you identify it using the ADD FOREIGN IIBY
clause of the ALTER TABLE co1111nand. In this clause , you specify the colu11m that is a
foreign key and tl1e table it matches. The ge11eral for1n for assignil1g a foreigi1 Irey is FOREIGN I<EY, the colu1nn nan1e(s) of tl1e foreign key, the REFERENCES clause, and tl1en
tl1e table name that tl1e foreign key must match, as shown in Figure 7-24.
Column )
name
Home
SOL Workshop
0Autocomrnit
SQL Commands
Rows
110
lvlV -?
( Save )( Run )
ALTER TABLE ORDERS
•
ADD FOREIGN 1<2Y (CUSTOMt:R NUM) REITRENCES CUSTOMER;
FIGURE 7-24
/
Name of
associated
table
'\
SOL Adding a foreign key to an existing table
ACCESS
USER
NOTE
To specify a foreign key in Access, open the Relationships window, relate the corresponding tables on
the matching column, and then select the option to enforce referential integrity.
After creati11g a foreign key, tl1e DBMS rejects any update that violates tl1e foreign lrey
co11straint. For example, the DBMS rejects tl1e INSERT co1nmand sho\\1n in Figt1re 7-25
because it attempts to add a11 order for v\1hicl1 tl1e custo1ner nu1nber (261) does not 111atcl1
any customer in tl1e CUSTOMER table.
I
Invalid customer
number
~
Home
SOL Workshop
0Autocommil
Rows
SQL Commands
110
1 v 1 V .(/
Schema IPRATTILASTI .., I
( Save )( Run )
INSERT INTO ORDERS
VJI.LOES
('51624', ' 10 - 15- 2015','261');
Results l:,.punn
[.;
Error
message
Savi:u :><.IL History
• ORA-022 91 : integ-rity conatraint (PRATT/I.AST . SYS_C007338) vio1&ted - parent key not found
j0.00 seconds
FIGURE 7-25
Violating a foreign key constraint when adding a row
Database Administration
Tl1e DBMS also rejects the DELETE command in Fig11re 7-26 beca11se it attempts to
dele te c11s tom er n11mber 334; ro\vs in the ORDERS table for \\rl1ich the c11stom er n11mbe r
is 334 \Vo11ld no longer 1natcl1 any ro\\' in tl1e CUSTOMER table.
Home
SQLWooohop
0 Autocommit
110
Rows
oa.en: FROM CUSTOMER
~H.ERE CUSTOMER_N1JM ;
Results
..-,.., Ian
n
Error
message
Schema IPAATTILAi>TI v I
SQL Commands
' 33 4 ' ;
•
Jv f v .f
( Save )( Run )
Command to d elet e a
customer wit h orde rs
-
')
er~ Soved SOL History
ORA-02292: int<>grity constraint (PRATT/I.AST .SYS C007338) violated - child record round
I
0.02 seconds
FIGURE 7-26
Violating a foreign key constraint when deleting a row
Note tl1at the error m essages shown in Fig11res 7-25 and 7-26 i11cl11de the \Vords
parent and chilcl. \\'11en yo11 specify a fo re ign l{ey, the table contaiI1ing the fo reign l{ey is
the child, and the table refer enced by the fore ign l{ey is tl1e parent. For example, the
CUSTOMER_NUM col11mn in the ORDERS table is a foreign l{ey tl1at refer ences tl1e
CUSTOMER table. For this foreign l{ey, the CUS'fOMER table is the parent, and the
ORDERS table is tl1e child . The erro r m essage shown in Fig11re 7-25 indicates tl1at the re
is n o parent fo r the order (ther e is no c11stom er n11mbe r 261). Tl1e error m essage shown
in Figure 7-26 indicates that the re are child r ecords (rows) for c11s tome r 334 (c11s tom er
334 has o rders). Tl1e DB11S rejects both 11pdates beca11se they violate refer ential
integrity.
EXAMPLE 21
Specify the valid categories for the ITEM table as GME, PZL, and TOY.
You use tl1e CHECI( clause of tl1e ALTER TABLE co111111a11d to e11s11re tl1at only legal
values satisfying a particular condition are allowed in a given coluID11. Tl1e general form of
tl1e CHECI<. clause is the \Vord CHEC I<. followed by a co11dition . If a user enters data tl1at
violates tl1e condition , the DBMS rejects tl1e update automatically. For example , to e11sure
tl1at the 011ly legal values for tl1e CATEGORY coluID11 are GME, PZL, o r TOY, use 011e of
tl1e followiI1g versions of the CHECI<. cla11se:
CHECK (CATEGORY IN ( 1GME 1 I
1
PZL 1 I
1
TOY 1 )
)
Chapter 7
or
CHECK (CATEGORY =
1
GME 1 OR CATEGORY =
1
PZL 1 OR CATEGORY =
1
TOY 1 )
'fl1e AL'fER TABLE command shown in Fig11re 7-27 11ses the first version of the
CHECI<. clause.
IHome SQL Wooo.hop SQL Commands
Rows
0Autocommil
11ti
Schema [PRATT1LAsr1v I
[vi~.?
( Save ) ( Run )
ALTER IABLE ITEM
A.OD CHECK (CATEGORY IN ( ' GME',
Results
~
'PZL', 'IOY' l ) ;
Oescnbe Saved ~ 'I!
plain
i~torv
,
Table ali;ered.
'
Valid categori es are
GM E, PZL, and TOY
}
0.01 seconds
FIGURE 7-27
Adding an integrity constraint to an existing table
No\-\7 the DBiVIS \.Vill reject the 11pdate sl1o'v\7n in Fig11re 7-28 beca11se the command
attempts to cl1ange the category for an item to MAG, \.Vl1icl1 is an illegal val11e.
Home
1,0
Rows
0Autocornmit
Schema ~
SQL Commands
SOL Wooo.hOP
[v)~,I
( Save ) ( Run )
UFDAIE IITM
SET C..~IEGORY s
Command to change an item'~
~ category to an invalid va lue
'MAG'
WHERE IIDI_NUM = '!(1,78';
Results
(:Jn
m
~('.I"
Error
message
TT/LA ST[..,)
Saved SOl
History
CIRA- 02290: check conatrilint (PRATT/LAST . SYS_C007339) vioJ.ated
0.01 seconds
FIGURE 7-28
Update that violates an integrity constraint
ACCESS
USER
NOTE
Access does not support the CHECK clause. To specify a validation rule in Access, open the table in
Design view, and then enter an expression in the column's Validation Rule property to limit the values
that users can enter into the column.
Database Administration
Chapter Summary
•
A view contains data that is derived from existing base tables when users attempt to
access the view.
•
To create a view, use the CREATE VIEW command, which includes a defining query
that describes the portion of the database included in the view. When a user retrieves
data from the view, the DBMS merges the query entered by the user with the defining
query and produces the query that the DBMS actually executes.
•
Views provide data independence, allow database access control, and simplify the
database structure for users.
•
You cannot update views that involve statistics and views with joins of nonprimary key
columns. Updates for these types of views must be made in the base table.
•
Use the DROP VIEW command to delete a view.
•
Use the GRANT command to give users access privileges to data in the database.
•
Use the REVOKE command to terminate previously granted privileges.
•
You can create and use an index to make data retrieval more efficient. Use the
CREATE INDEX command to create an index. Use the CREATE UNIQUE INDEX command to enforce a rule so only unique values are allowed in a nonprimary key column.
•
Use the DROP INDEX command to delete an index.
•
The DBMS, not the user, chooses which index to use to accomplish a given task.
•
The DBMS maintains information about the tables, columns, indexes, and other system elements in the system catalog (catalog) or data dictionary. Information about
tables is kept in the SYSTABLES table , information about columns is kept in the
SYSCOLUMNS table, and information about views is kept in the SYSVIEWS table. In
Oracle, these same tables are named DBA_TABLES, DBA_TAB_COLUMNS, and
OBA VIEWS.
•
Use the SELECT command to obtain information from the system catalog. The DBMS
updates the system catalog automatically whenever changes are made to the database. In Access, use the Documenter to obtain information about the database
objects. SOL Server uses stored procedures to obtain information from the system
catalog.
•
Integrity constraints are rules that the data in the database must follow to ensure that
only legal values are accepted in specified columns and that primary and foreign key
values match between tables. To specify a general integrity constraint, use the
CHECK clause . You usually specify primary key constraints when you create a table,
but you can specify them later using the ADD PRIMARY KEY clause . To specify a
foreign key, use the ADD FOREIGN KEY clause.
Chapter 7
Key Terms
ADD FOREIGN KEY
foreign key
ADD PRIMARY KEY
GRANT
base table
index
catalog
integrity constraint
CHECK
integrity support
child
parent
CREATE INDEX
CREATE UNIQUE INDEX
REFERENCES
CREATE VIEW
REVOKE
row-and-column subset view
data dictionary
security
database administration
SYSCOLUMNS
database administrator
SYSTABLES
OBA- TAB- COLUMNS
system catalog
OBA TABLES
SYSVIEWS
OBA VIEWS
unique index
defining query
view
DROP INDEX
WITH GRANT OPTION
.
DROP VIEW
Review Questions
1. What is a view?
2. Which command creates a view?
3. What is a defining query?
4. What happens when a user retrieves data from a view?
5. What are three advantages of using views?
6. Which types of views cannot be updated?
7. Which command deletes a view?
8. Which command gives users access privileges to various portions of the database?
9. Which command terminates previously granted privileges?
10. What is the purpose of an index?
11 . How do you create an index? How do you create a unique index? What is the difference
between an index and a unique index?
12. Which command deletes an index?
13. Does the DBMS or the user make the choice of which index to use to accomplish a given
task?
Database Administration
14. Describe the information the DBMS maintains in the system catalog. What are the generic
names for three tables in the catalog and their corresponding names in Oracle?
15. The CUSTOMER table contains a foreign key, REP_NUM, that must match the primary key
of the REP table. What type of update(s) to the CUSTOMER table would violate the foreign
key constraint?
16. Which command do you use to obtain information from the system catalog in Oracle?
17. How is the system catalog updated?
18. What are integrity constraints?
19. How do you specify a general integrity constraint?
20. When would you usually specify primary key constraints? Can you specify them after creating a table? How?
21 . How do you specify a foreign key in Oracle?
C RITICAL
THINKING
C RITICAL
THINKING
22. Use the Internet to find information about referential integrity. Write two or three paragraphs
that describe what referential integrity is and include an example of how referential integrity
is used in the TAL Distributors database. Be sure to cite the URLs that you use.
23. Use the Internet to find information about a data dictionary. Write a one-page paper that
describes other types of information that can be stored in a data dictionary. Be sure to cite
the URLs that you use.
Exercises
T AL Distributors
Use SOL to make the following changes to the TAL Distributors database (see Figure 1-2 in
Chapter 1). After each change, execute an appropriate query to show that the change was
made correctly. If directed to do so by your instructor, use the information provided with the
Chapter 3 Exercises to print your output or save it to a document. For any exercises that use
commands not supported by your version of SOL, write the command to accomplish the task.
1. Create a view named MAJOR_CUSTOMER. It consists of the customer number, name, balance, credit limit, and rep number for every customer whose credit limit is $10,000 or less.
a. Write and execute the CREATE VIEW command to create the MAJOR CUSTOMER
•
view.
b. Write and execute the command to retrieve the customer number and name of each
customer in the MAJOR CUSTOMER view with a balance that exceeds the credit
limit.
c. Write and execute the query that the DBMS actually executes.
d. Does updating the database through this view create any problems? If so, what are
they? If not, why not?
2. Create a view named ITEM_ORDER. It consists of the item number, description, price,
order number, order date, number ordered, and quoted price for all order lines currently
on file.
Chapter 7
a.
b.
Write and execute the CREATE VIEW command to create the ITEM ORDER view.
Write and execute the command to retrieve the item number, description, order number, and quoted price for all orders in the ITEM_ORDER view for items with quoted
prices that exceed $100.
c.
Write and execute the query that the DBMS actually executes.
d.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
3. Create a view named ORDER TOTAL. It consists of the order number and order total for
each order currently on file. (The order total is the sum of the number of units ordered
multiplied by the quoted price on each order line for each order.) Sort the rows by order
number. Use TOT AL AMOUNT as the name for the order total.
a. Write and execute the CREATE VIEW command to create the ORDER TOTAL view.
b. Write and execute the command to retrieve the order number and order total for only
those orders totaling more than $500.
c.
d.
Write and execute the query that the DBMS actually executes.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
4. Write , but do not execute, the commands to grant the following privileges:
a. User Ashton must be able to retrieve data from the ITEM table.
b.
Users Kelly and Morgan must be able to add new orders and order lines.
c.
d.
User James must be able to change the price for all items.
User Danielson must be able to delete customers.
e.
All users must be able to retrieve each customer's number, name, street, city, state,
and postal code.
f.
g.
User Perez must be able to create an index on the ORDERS table .
User Washington must be able to change the structure of the ITEM table.
h.
User Grinstead must have all privileges on the ORDERS table.
5. Write , but do not execute, the command to revoke the privilege given to user Ashton in
Exercise 4a.
6. Perform the following tasks:
a. Create an index named ITEM INDEX1 on the ITEM- NUM column in the ORDER- LINE
table.
b.
c.
d.
Create an index named ITEM INDEX2 on the CATEGORY column in the ITEM
table.
Create an index named ITEM INDEX3 on the CATEGORY and STOREHOUSE columns
in the ITEM table.
Create an index named ITEM INDEX4 on the CATEGORY and STOREHOUSE
columns in the ITEM table . List categories in descending order.
7. Delete the index named ITEM INDEX3.
8. Write the commands to obtain the following information from the system catalog. Do not
execute these commands unless your instructor asks you to do so.
Database Administration
a.
List every table that you own.
b.
List every column in the ITEM table and its associated data type.
9. Add the ORDER_NUM column as a foreign key in the ORDER_LINE table.
10. Ensure that the only legal values for the CREDIT_LIMIT column are 5000, 7500, 10000,
and 15000.
CRITICAL
THINKING
11 . Toys Galore currently has a credit limit of $7,500. Because Toys Galore has an excellent
credit rating, TAL Distributors is increasing the company's credit limit to $10,000. If you
run the SOL query in Exercise 1 after the credit limit has been increased, would Toys
Galore still be included in the view? Why or why not?
Colonial Adventure Tours
Use SOL to make the following changes to the Colonial Adventure Tours database (Figures 1-4
through 1-8 in Chapter 1). After each change , execute an appropriate query to show that the
change was made correctly. If directed to do so by your instructor, use the information provided
with the Chapter 3 Exercises to print your output or save it to a document. For any exercises
that use commands not supported by your version of SOL, write the command to accomplish
the task.
1. Create a view named MAINE_TRIPS. It consists of the trip ID, trip name, start location,
distance, maximum group size, type, and season for every trip located in Maine (ME).
a. Write and execute the CREATE VIEW command to create the MAINE TRIPS view.
b.
c.
d.
Write and execute the command to retrieve the trip ID, trip name, and distance for
every Biking trip.
Write and execute the query that the DBMS actually executes.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
2. Create a view named RESERVATION_CUSTOMER. It consists of the reservation ID, trip
ID, trip date, customer number, customer last name, customer first name, and phone
number.
a. Write and execute the CREATE VIEW command to create the RESERVATION
CUSTOMER view.
b. Write and execute the command to retrieve the reservation ID, trip ID, trip date, and
customer last name for every reservation in the RESERVATION_CUSTOMER view
with a trip date of September 11 , 2016.
c.
Write and execute the query that the DBMS actually executes.
d.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
3. Create a view named TRIP INVENTORY. It consists of the state and the total number of
trips for each state. Use UNITS as the column name for the total number of trips for each
state. Group and order the rows by state.
a. Write and execute the CREATE VIEW command to create the TRIP INVENTORY
.
view.
Chapter 7
b.
c.
d.
Write and execute the command to retrieve the state and units for each state having
more than 1O trips.
Write and execute the query that the DBMS actually executes.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
4. Write, but do not execute, the commands to grant the following privileges:
a. User Rodriquez must be able to retrieve data from the TRIP table.
b. Users Gomez and Liston must be able to add new reservations and customers to the
database.
c. Users Andrews and Zimmer must be able to change the price of any trip.
d. All users must be able to retrieve the trip name, start location, distance, and type for
every trip.
e. User Golden must be able to add and delete guides.
f.
User Andrews must be able to create an index for the TRIP table.
g.
Users Andrews and Golden must be able to change the structure of the CUSTOMER
table.
User Golden must have all privileges on the TRIP, GUIDE, and TRIP_GUIDES
tables.
h.
5. Write , but do not execute, the command to revoke all privileges from user Andrews.
6. Create the following indexes:
a. Create an index named TRIP- INDEX1 on the TRIP- NAME column in the TRIP
table.
b.
Create an index named TRIP INDEX2 on the TYPE column in the TRIP table.
c.
Create an index named TRIP- INDEX3 on the LAST- NAME and FIRST- NAME
columns in the CUSTOMER table.
7. Delete the index named TRIP INDEX3.
8. Write the commands to obtain the following information from the system catalog. Do not
execute these commands unless your instructor asks you to do so.
a. List every column in the GUIDE table and its associated data type.
b. List every table that contains a column named TRIP_ID.
c.
List the table name, column name, and data type for the columns named TRIP_ID,
TRIP_NAME, and TYPE. Order the results by table name within column name. (That
is, column name is the major sort key and table name is the minor sort key.)
9. Add the CUSTOMER_NUM column as a foreign key in the RESERVATION table.
10. Ensure that the only legal values for the TYPE column in the TRIP table are Biking,
Hiking, or Paddling.
C RITICAL
THINKING
11 . The maximum group size for a trip must be greater than one. Use the Internet to research
the CHECK clause, determine how to add this constraint to the TRIP table, and then write
the SOL command to make this change to the TRIP table. Be sure to cite your
references.
Database Administration
Solmaris Condominium Group
Use SOL to make the following changes to the Solmaris Condominium Group database
(Figures 1-9 through 1-13 in Chapter 1). After each change , execute an appropriate query to
show that the change was made correctly. If directed to do so by your instructor, use the
information provided with the Chapter 3 Exercises to print your output or save it to a document.
For any exercises that use commands not supported by your version of SOL, write the
command to accomplish the task.
1. Create a view named SMALL_CONDO. It consists of the location number, unit number,
bedrooms, baths, condo fee , and owner number for every condo whose square footage is
less than 1,100 square feet.
a. Write and execute the CREATE VIEW command to create the SMALL CONDO view.
b. Write and execute the command to retrieve the location number, unit number, and
condo fee for every condo in the SMALL_CONDO view with a condo fee of $400 or
more.
c. Write and execute the query that the DBMS actually executes.
d.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
2. Create a view named CONDO_OWNERS. It consists of the location number, unit number,
square footage , bedrooms, baths, condo fee, and owner's last name for every condo in
which the number of bedrooms is three.
a. Write and execute the CREATE VIEW command to create the CONDO OWNERS
.
view.
b. Write and execute the command to retrieve the location number, unit number,
condo fee , square footage , and owner's last name for every condo in the
CONDO_OWNERS view with a condo fee of less than $500.
c.
d.
Write and execute the query that the DBMS actually executes.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
3. Create a view named CONDO_FEES. It consists of two columns: the first is the square
footage , and the second is the average fee for all condos in the CONDO_UNIT table that
have that square footage . Use AVERAGE_FEE as the column name for the average fee.
Group and order the rows by square footage.
a. Write and execute the CREATE VIEW command to create the CONDO FEES view.
b. Write and execute the command to retrieve the square footage and average fee for
each square footage for which the average fee is greater than $500.
c.
d.
Write and execute the query that the DBMS actually executes.
Does updating the database through this view create any problems? If so, what are
they? If not, why not?
4. Write , but do not execute, the commands to grant the following privileges:
a. User Oliver must be able to retrieve data from the CONDO UNIT table.
b. Users Crandall and Perez must be able to add new owners and condo units to the
database.
Chapter 7
c.
Users Johnson and Klein must be able to change the condo fee of any unit.
d.
All users must be able to retrieve the unit number, condo fee, and owner number for
every condo unit.
User Klein must be able to add and delete service categories.
User Adams must be able to create an index on the SERVICE REQUEST table.
e.
f.
g.
h.
Users Adams and Klein must be able to change the structure of the CONDO_UNIT
table.
User Klein must have all privileges on the LOCATION, OWNER, and CONDO_UNIT
tables.
5. Write , but do not execute, the command to revoke all privileges from user Adams.
6. Create the following indexes:
a.
b.
c.
Create an index named OWNER INDEX1 on the STATE column in the OWNER
table.
Create an index named OWNER- INDEX2 on the LAST- NAME column in the
OWNER table.
Create an index named OWNER INDEX3 on the STATE and CITY columns in the
OWNER table. List the states in descending order.
7. Delete the OWNER INDEX 3 index from the OWNER table .
8. Write the commands to obtain the following information from the system catalog. Do not
execute these commands unless your instructor specifically asks you to do so.
a. List every column in the CONDO_UNIT table and its associated data type.
b.
List every table that contains a column named OWNER_NUM.
9. Add the OWNER_NUM column as a foreign key in the CONDO_UNIT table.
10. Ensure that the only legal values for the BDRMS column in the CONDO_UNIT table are
1, 2, or 3.
C RITICAL
THINKING
11 . In Question 9, you added owner number as a foreign key in the CONDO_UNIT table.
Identify all foreign keys in the Solmaris Condominium Group database and write the
corresponding SOL commands.
C H A PTER
•
•
S L FUNCTIONS AND
PROCEDURES
OBJECTIVES
•
Understand how to use functions in queries
•
Use the UPPER and LOWER functions with character data
•
Use the ROUND and FLOOR functions with numeric data
•
Add a specific number of months or days to a date
•
Calculate the number of days between two dates
•
Use concatenation in a query
•
Embed SOL commands in PUSOL and T-SOL proced ures
•
Retrieve single rows using embedded SOL
•
Update a table using embedded INSERT, UPDATE, and DELETE
commands
•
Use cursors to retrieve multiple rows in embedded SOL
•
Manage errors in procedures containing embedded SOL commands
•
Use SOL in a language that does not support embedded SOL commands
•
Use triggers
INTRODUCTION
You already have used fu nctions that apply to groups (such as SUM and AVG). In th is chapter, you
will learn to use functions that apply to values in individual rows . Specifically, you will see how to
use functions with characters or text, numbers, and dates. You will learn how to concatenate values
in a query. You will embed SOL commands in PUSOL and T-SOL procedures to retrieve rows and
update data. You will examine the different ways to manage errors in procedures. Finally, you will
learn how to create and use cursors and triggers.
USING SQL IN A PROGRAMMING ENVIRONMENT
SQL is a powerful nonprocedural lang11age it1 v\7hicl1 you cormnunicate tasks to tl1e computer using silnple co1n1n ands. As i11 other 11011procedural languages, you ca11 accomplish
Chapter 8
m an y taslts 11sing a single comma11d. Altho11gl1 SQL and o the r nonproced11ral la.n guages
are well eq11ipped to store and query data, so1netimes yo11 migl1t need to comple te taslts
tl1a t are beyond the capabilities of SQL. In s11ch cases, yo11 n eed to use a proced11ral
lang11age.
A procedural language is 011e in \vhicl1 yo11 mus t give tl1e computer tl1e systematic
process for accomplishing a taslt. PL/SQL , \Vl1icl1 was developed by Oracle as ru1 exten sion
of SQL, is an example of a. proced1.1ral la11guage. This cl1apter 11ses PUSQL to ill11s trate
110\\' to 11se SQL in a programming enviro11ment by embedding SQL commands in another
lang11age. Tl1e examples il1 tl1is cl1apter illu strate 110\\' to use en1bedded SQL commands to
retrieve a single ro\v, insert n e\.v rows, 11pdate and delete existing ro\vs, and re trieve
m11ltiple ro\\'S. In the process, yo11 \Vill create stored procedures tl1at are saved and are
available fo r 11se at a11y time.
T-SQL , wl1icl1 s tands for Transact-SQL, is anotl1er extension of SQL. T-SQL is tl1e
proced11ral lang11age tl1at SQL Server 11ses. Yo11 can pe rforn1 taslts, s11cl1 as re trievi11g a
single r ow, inserting new ro\vs, a11d re trieving multiple ro\vs, using T-SQL i11 SQL Ser ver.
Altl1011gl1 tl1e lang11age syntax is sligl1tly diffe rent in T-SQL wl1en co1npa red to PUSQL,
tl1e f11nc tionality and tl1e resu lts are the sam e.
Y011 can11ot embed SQL commands in Access programs tl1e \Vay yo11 cru1 in PL/SQL
ru1d T-SQL. The re are \\rays to 11se tl1e commands, 110\veve r, as yo11 \vill lea r11 later il1 tl1is
cl1apte r.
NOTE
This chapter assumes that you have some programming background and does not cover programming
basics. To understand the first part of this chapter, you should be familiar with variables, declaring
variables, and creating procedural code, including IF statements and loops. To understand the Access
section at the end of the chapter, you should be familiar with Function and Sub procedures, and the
process for sequentially accessing all records in a recordset, such as using a loop to process all the
records in a table.
ACCESS
USER
NOTE
If you are using Access, you will not be able to complete the material in this chapter that deals with
PUSQL and T-SQL procedures. Be sure to read this information so you will understand these important concepts. You will, however, be able to complete the steps in the "Using SQL in Microsoft Access" section.
USING FUNCTIONS
You already l1ave 11sed aggregate f1111ctio11s to p erform calc11latio11s based 011 gro11ps of
records. For exa1nple, SUM(BALANCE) calc11lates the s11m of tl1e balances on all records
tl1at satisfy the condition in the \\THERE cla11se. \\Tl1en yo11 11se a GROUP BY clause, tl1e
DBMS ,vill calc11late the s11m fo r each record in a gro11p.
SQL also incl11des fu11ction s that affect si11gle records. S01ne f11nc tion s affect cl1arac ter
data and o the rs le t yo111nanipulate 11umeric d ata. Tl1e s11pported SQL ft1nctions vary
SOL Functions and Procedures
between SQL implem entation s. 'fhis section will illtts trate som e comtnon ft1nction s. For
additional information abotit tl1e ft111ctions your SQL implem entatio11 sttpports, const1lt
tl1e program's doct1mentation .
Character Functions
SQL i11clt1des several func tions that affect character data. Example 1 illus trates the use of
tl1e UPPER fu11c tion.
EXAMPLE 1
List the rep number and last name for each sales rep. Display the last name in uppercase
letters.
Tl1e UPPER ft111ction displays a valtte i11 ttppercase lette rs; for example, tl1e ft111c tio11
UPPER(LAST_NAME) displays the last 11a1ne Ca1npos as C1\MPOS. (Note tl1at tl1e UPPER
ft111c tio11 sitnply displays tl1e last 11a111e i11 ttpp ercase le tte rs; it does 11ot cl1a11ge tl1e last
11ame stored il1 the table to ttppe rcase le tte rs.) Tl1e itetn il1 pare11tl1eses (LAST_NAME) is
called tl1e argument for tl1e ft1nc tio11 . Tl1e valtte prodt1ced by tl1e ft111ction is the rest1lt of
displayi11g all lo\\7ercase letter s i11 tl1e valt1e s tored i11 tl1e LAST_NAME colt11n11 i11 uppercase le tters. Tl1e qt1ery a11d its rest1lts are sl1own i11 Figt1re 8 -1 .
ORACLE' Application Express
Home
••
AppllcaUon Buil<ler ,..
Home'
SOL Workshop
!;21 Autocommit
Rows
SQL Commands
I10
I v I (; {/
( Save ) -..;.;Ru;;:;,.n;.....-____
SELECT REP_NUM, UPPER(LAS: _NAME) - - - - - - - - - <
FROM REP;
Results I: pla n
"'y-- - - - - - - - l
A rgument
Saved SQL History
L..----=======::\,. UPPER funct ion ,;- - - - - i
15
CAMPOS
30
GRADEY
45
60
TIAN
~---;,------l
SEFTON
4 rows returned in 0.01 seconds
FIGURE 8-1
Team Development•
Last names displayed
in uppercase letters
Download
Using the UPPER function to display character data in uppercase letters
Yott can ttse fttnc tions in \\THERE clattses as well. For example, tl1e condition
UPPER(LAST_NAME) = 'CAMPOS' wottld be ttue for 11ames lilre Campos, CAMPOS, and
CaMpOS, becattse tl1e rest1lt of applyin g the UPPER ft111c tion to an y of these values \VOttld
rest1lt in tl1e valtte CAMPOS.
To display a valtte in lo\vercase letter s, yott can use tl1e LOWER func tion. SQL Server
sttpports botl1 tl1e UPPER and LO\\TER func tion .
Chapter 8
ACCESS
USER
NOTE
In Access, the UCASE function displays a value in uppercase letters and the LCASE function displays a
value in lowercase letters. For example, if the value stored in the LAST_NAME column is Campos,
UCASE(LAST_NAME) would result in the value CAMPOS and LCASE(LAST_NAME) would result in the
value campos.
Number Functions
SQL also i11cludes f11nc tions tha t affect 1111me ric data. Tl1e ROUND ft1nc tion , wl1ich ro11nds
val11es to a specified 1111mber of decimal places, is illustrated in Example 2.
EXAMPLE 2
List tl1e item number and price for all items. Round the price to the nearest whole dollar amount.
A f1111c tio11 ca11 l1ave m ore tl1a11 011e argu111e11t. Tl1e ROUND f1111ctio11, wl1icl1 ro11nds a
11u111eric value to a desired 11umbe r of deci1nal places, l1as two arg11me11ts. Tl1e first arg111ne11t is tl1e val11e to b e rou11ded ; tl1e seco11d arg111nent i11dicates tl1e n111nber of decin1al
places to "''l1icl1 to r ou11d the res11lt. For example , ROUND(PRICE,O) \.Vill ro1111d tl1e val11es
i11 tl1e PRICE colu1n11 to zero deci1nal places (a "''l1ole 1111111ber). If a price is 24.95, tl1e
res11lt \.Vill be 25. If tl1e price is 24.25, 011 tl1e otl1er l1a11d, tl1e res11lt \.Vill be 24. Fig11re 8-2
sh o\.VS tl1e query a11d res11lts to rot111d val11es i11 tl1e PRICE colt11n11 to zero deci111al places.
Tl1e co1np11ted colt1m11 ROUND(PRICE,O) is 11a111ed ROUNDED_PRICE.
l
Home
SQL Wooo.hop
E21Autocommit
Rows
SQL Commands
Iv I~ I/
J20
( S ave ) ( Run )
SELECT IIEM_ NUM, ROOND( PRICE ,O) AS ROUNDED_ PRICE
FROM ITEM;
Results
er u
I
Saved SOL
H1s1ory
ROUND
function
!lOlllllOIEO_PRIC:E
AH74
23
BR23
30
C033
89
DL51
108
DR67
32
OW23
50
FD11
125
FH24
39
KA12
75
KD34
15
Kl.78
11
MT03
46
NL89
120
TR40
14
TW35
119
Price values rounded to
zero decimal p laces in a
column named
ROUNDED_PRICE
15 rows returned in 0.01 seconds
FIGURE 8-2
Download
Using the ROUND function to round numeric values
SOL Functions and Procedures
Ratl1er than rot1nding ( t1sing the ROUND ft1nc tion), yot1 migl1t n eed to trt1ncate
(remove) everytl1i11g to tl1e rigl1t of tl1e decimal poi11t. To do so, t1se the FLOOR ft1nction,
\\rhicl1 l1as only 011e argt1ment. If a price is 24.95, for exa1nple, ROUND(PRICE,O) \\'Ot1ld
rest1lt in 25, \\rh ereas FLOOR(PRICE) \\'Ottld resttlt in 24. SQL Server st1pports botl1 the
ROUND and the FLOOR ft1nctions. 11icrosoft Access st1pports 01u y the ROUND ft1nction.
Working with Dates
SQL uses fu11ctio11s and calculatio11s for manipulating dates . To add a specific 11umber of
1nontl1s to a date, you can use tl1e ADD_MONTHS function as illttstrated i11 Example 3.
EXAMPLE 3
For each order, list the order number and the date that is two months after the order
date. Name this date FUTURE DATE.
Tl1e ADD_lvIONTHS fu11c tio11 l1as two argu111e11ts. Tl1e first argt1me11t is tl1e date to
\\'l1icl1 yot1 "'' a11t to add a specific 11t1mber of mo11tl1s , and tl1e seco11d argu111e11t is tl1e
11umber of 1no11tl1s. To add t\VO 111011ths to tl1e order date , for example, tl1e expressio11
is ADD_MONTI-IS(ORDER_DATE,2) as illt1stra ted i11 Figt1re 8-3.
Home
SQL Worl<shoj)
0 Aulocommit
Rows
SQL Commands
! v I I, .(?
(2°
( Save ) ( Run )
SELECT ORDER_ NUM, ADO_ HONTBS {ORDER_ DA!E, 2) AS <UIURE DAIE
FROM ORDERS;
ADD_MONTHS
Results
E piam
sc
51610
12/12/2015
51613
12/13/2015
51614
12/13/2015
51617
12/15/2015
51619
12/15/2015
51623
12/15/2015
51625
12/16/2015
saved SQL
~
+-----i
function
Two months added to
each order date in a
column named
FUTURE_DATE
8 rows returned in 0.01 seconds
FIGURE 8-3
HISIOI''
Download
Using the ADD_MONTHS function to add months to a date
ACCESS
USER
NOTE
To add a number of months to a date in Access, use the DATEADD() function, which has three
arguments. The first argument includes the interval of time to be added; the letter "m" indicates
that months will be added. The second argument includes the number of intervals to be added.
The third argument includes the date to be manip ulated. For example, to add two months to the
dates stored in the ORDER_DATE column, the appropriate function would be DATEADD(m, 2,
ORDER_DATE).
Chapter 8
SQL SERVER
USER
NOTE
To add a number of months to a date in SOL Server, use the DATEADD() function, which has three
arguments. The first argument includes the interval of time to be added; the letter "m" indicates that
months will be added. The second argument includes the number of intervals to be added. The third
argument includes the date to be manipulated. For example, to add two months to the dates stored in
the ORDER_DATE column, the appropriate function would be DATEADD("m", 2, ORDER_DATE).
EXAMPLE 4
For each order, list the order number and the date that is seven days after the order
date. Name this date FUTURE DATE.
'f o add a specific n11mbe r of days to a date , yo11 do not need a ft1nc tion . Y011 can add
tl1e n11mbe r of days to the order date as ill11strated in Fig11re 8-4. (Yo11 can also s11btract
dat es in the same way.) This me thod \.,,orlrs in Oracle, Access, and SQL Ser ver.
lHome SOL Wooo.hop SQL Commands
0 Autocommit
Rows
110
I.., 1t, ,R
( Save )( Run )
SELECT ORDER_NUM, OJIDER_ DATE+7 AS fUIURL_DATE - - - --
FROM ORDERS;
Results
1c
ptun
Expression t hat ad ds
seven days to the
order d ates
l
51608
10/19/2015
51610
10/19/2015
51613
10/20/2015
51614
10/20/2015
51617
>~+----!
10/22/2015
51619
10/2212015
51623
10/22/2015
51625
10/2312015
8 rows returned in 0.00 seconds
FIGURE 8-4
--
Seven d ays added
to each order date
Download
Adding days to dates
EXAMPLE 5
For each order, list the order number, today's date, the order date, and the number of
days between the order date and today's date. Name today's date TODAYS_DATE and
name the number of days between the order date and today's date DAYS_PAST.
Yo11 can use the SYSDATE f11nc tio11 to obta in today's date, as shown in Fig11re 8 -5.
Tl1e com1n and in the fig11re 11ses SYSDATE to display today's da te and also uses SYSDATE
in a comp11tation to de te rmine the 11umber of days betwee11 tl1e order da te and today's
date. Tl1e val11es for DAYS_PAST incl11de decimal places. Yo11 co11ld remove these decimal
SOL Functions and Procedures
places by u sing the ROUND o r FLO OR f11nc tions , if desired . In Fig11re 8-5, the res11lts are
rounded to two decim al places.
Home
SQL Workshop
6Zl Autocommil
Rows
SQL Commands
Iv I~ ,(/
[20
( Save ) ( Run )
Expression to
calculate the number
of days between today's
date and the order date
SELECT O!UlER_NUM, SYSDATE AS TODAYS_ DATE, ORDER_DA'IE,
ROOND (SYSDATE - ORDER_ DAIE,2 ) AS DAYS_ PAST
FROM ORDERS ;
Results
~xr,
1
.>..scnbe
Saved SOL History
••
51608
11/10/2015
10/12/2015
29.53
51610
11/10/2015
10/12/2015
29.53
51613
11/ 10/2015
10/13/2015
28.53
51614
11/ 10/2015
10/13/2015
28.53
51617
11/10/2015
10/15/2015
26.53
51619
11/ 10/2015
10/ 15/2015
26.53
51623
11/10/2015
10/15/2015
26.53
51625
11/ 10/2015
10/16/2015
25.53
8 rows returned in 0.01 seconds
FIGURE 8-5
>,+---H
Number of days
between today's
date and the
orde r date
Download
Calculating the number of days between two dates
ACCESS
USER
NOTE
In Access, use the DATE() function to obtain today's date, rather than SYSDATE. The DATE () function
has no arguments, so you would write DATE() in place of SYSDATE.
SQL SERVER
USER
NOTE
In SQL Server, use the GETDATE() function to obtain today's date, rather than SYSDATE. The
GETDATE () function has no arguments, so you would write GETDATE () in place of SYSDATE.
CONCATENATING COLUMNS
Som e times yo11 11eed to concatenate, or combine, t\o,ro or m ore cl1ar acter columns iI1to
a single expression "' rl1e 11 displaying them in a query; the process is called concatena.tion.
To co11caten ate columns, you type t,vo vertical lin es (II) b etween the colum11 n a1nes, as
illtis trated in Example 6.
EXAMPLE 6
List the number and name of each sales rep . Concatenate the FIRST_NAME and LAST_NAME
columns into a single value, with a space separating the first and last names.
To con caten ate tl1e FIRST_NAME and LAST_NAME col11mns, tl1e expression is
FIRST NANIEIILAST NA.NIE. \Vhe11 the fiI·st 11ame doesn 't i11cl11de sufficie11t cl1aracters to fill
Chapter 8
tl1e \Vidtl1 of tl1e coli1mn (as d ete rmined by tl1e ni1mber of characters specified in the CREATE
TABLE co1nmand), SQL inserts extra spaces. For example, \vl1en tl1e FIRST_NAME coli1mn is
12 cl1aracters in length, the first 11ame is Mary, and the last name is Jol1nson , tl1e expression
FIRST_NANIEIILAS'f _NA11E is displayed as Nlary, followed by eight spaces, and then Johnson.
To r em ove the extra spa ces follo\ving tl1e first name vali1e, yoi1 i1se tl1e RTRLVI (right trim)
ft1nctio n. Vl l1en yoi1 apply tl1is ft1nction to tl1e vali1e in a colurm1, SQL displays tl1e original
vali1e and rem oves any spaces inserted at tl1e end of the vali1e. Figi1re 8-6 sh o\vs tl1e qi1ery and
oi1tpi1t \\'itl1 tl1e extra spaces rem oved . For sales re p 15, for example, this command trims tl1e
first naine to "Rafael," conca te11ates it \Vitl1 a single sp ace, and tl1en concate11ates the last
name "Can1pos."
J
l
Home
SOL Wooo.hop
SQL Commands
Rows
0 Autocommit
-
JvlV .f
120
( Save ) ( Run)
SELECT REP_ NUM, RTRIM(fIRSI_ NAME) 11 ' ' I IRIRIM(LASI NAME) AS REP_ NAME
FROM REP;
•
Resuns F plain r
_,
.
·'jp
I '
RTRIM ~ •. ,
/
. function
~
• ••
ca
;:I
15
Rafael campos
30
Megan Gradey
45
Hui nan
, 60
Concatenation
symbol
Concatenated names
Janel Sefton
I
4 rows returned in 0.01 seconds
FIGURE 8-6
Download
Concatenating two columns and using the RTRI M function
'
Q&A
Question: Why is it necessary to insert a single space character in single quotation marks
in the query?
Answer: Without the space character, there would be no space be tween the first and last
names. The name of sales rep 15, for example, would be displayed as "RafaelCampos."
ACCESS
USER
NOTE
In Access, use the & symbol to concatenate columns. It is not necessary to trim the columns because
Access will trim them automatically. The corresponding query in Access is:
SE L E CT REP NUM, FIRST NAME&'
1
&LAST NAME AS REP NAME
FROM REP;
SQL SERVER
USER
NOTE
In SQL Server, use the + symbol to concatenate columns. The corresponding query in SQL Server is:
SELECT REP NUM, RTRIM (FIR ST NAME)+ 1 1 +RTRIM (LAST NAME) AS REP NAME
FROM REP;
SOL Functions and Procedures
STORED PROCEDURES
In a clienUserver system, tl1e database is sto red on a compt1te r called the server and t1sers
access tl1e database tl1rot1gl1 clients. A client is a compt1ter that is con11ected to a netv,,orlr
a11d l1as access through tl1e server to tl1e database. Every time a user executes a qt1ery,
tl1e DBMS must dete1mine tl1e best "''ay to process the query and provide tl1e results. For
example, tl1e DBMS mt1s t d etermine whicl1 i11dexes are available and whetl1er it can use
tl1ose i11dexes to malre tl1e processing of tl1e qt1ery more efficient.
\\Tl1en yot1 anticipate rt1nni11g a particttlar qt1ery often, yot1 can improve overall performance by saving tl1e query in a file called a stored procedure. The stored procedt1re is placed
on the server . The DBNIS compiles tl1e s tored procedt1re (tra11slating it into macl1it1e code)
a11d c reates an execution plan, wlticl1 is tl1e most efficient "''ay of obtaining tl1e rest1lts. From
tl1at poit1t on , users exect1te tl1e compiled, optimized code in tl1e s tored procedure.
Another reason for saving a que ry as a s tored procedt1re, even \vhen you are not
worlring in a client/server syste1n, is co11ve11ience. Rather tl1an retyping tl1e entire qt1ery
eacl1 time yot1 need it, yot1 can t1se the s tored procedt1re. For example, st1ppose yot1 frequently exect1te a qt1e ry that selects a sales rep witl1 a given nt1mber and then displays
tl1e concate11ation of the first 11ame and last 11ame of tl1e sales rep . Instead of typit1g tl1e
query eacl1 time yot1 ~rant to display a sales rep's name, yot1 ca11 save tl1e qt1ery in a
stored procedt1re. Yot1 wottld tl1e11 only need to rt1n the stored procedt1re "''hen yot1 "''ant
to display a sales rep's name.
ACCESS
USER
NOTE
Although Access does not support stored procedures, you can achieve some of the same convenience
by creating a parameter query that prompts the user for the arguments you would otherwise use in a
stored procedure.
I11 Oracle, yot1 create stored procedures usi11g a language called PUSQL. You create
and save the procedt1res as script files.
Retrieving a Single Row and Column
Exa1nple 7 illt1s trates us it1g a sto red procedt1re to retrieve a single r ow at1d colu1n11 fron1 a
table.
EXAMPLE 7
Write a PL/SQL procedure that takes a rep number as input and displays the corresponding rep name.
Figt1re 8 -7 shows a procedt1re to find the name of the rep wl1ose number is s tored in
tl1e I_REP_l\11..JNI argume11t. Becat1se the restriction involves tl1e p1imary key, the query
will produce only one row of outpt1t. (Yot1 will see l1ow to handle qt1e ries whose results ca11
contain multiple rows later it1 this chapter .) Tl1e comma11d sl1own in Figt1re 8-7 is stored
Chapter 8
in a script file and is displayed in the Script Editor. To create tl1e procedttre, yo11 \.VOttld
run tl1e script file . Ass11ming that tl1e script file does not contai11 any errors, Oracle \.Vo11ld
tl1e11 create tl1e proced11re and it \.Vo11ld be available for 11se.
Home
SQl WorkshOp
SOL Scripts
Script Editor
Procedure
name
Script Name DISPLAY_REP_NAME
( Cancel )
Argument
( Rnd & Replace ) ( Undo )( Redo )
Local
variables
CREATE OR REPLACE PROCEDURE DISP_REP_ITT\M.E (I_REP_NUM I N REP.REP_N1.1M\ TYPE) AS
I LAST NAME
REP.LAST NAME\TYPE ;
1-----l~ I - fIRST NAME
REP.fIRST NAME\TYPE ;
-
-
-
BEGIN
SELECT LAST_ NAME: , fIRST _ NAME
INTO I_LAST_NAM£ , I _fIRST_NAME
rROM REP
lilll'£.R£ REP NUM = I REP NUM ;
-
1
Co mmand to select
LAST_NAME and
FIRST_NAM E and p lace
t hem in local vari ables
- -
DBMS_OUTPUT. PUT_ LINE (RTR:M (I_fIRST_ NAME) I I ' ' I I RTR I'! (I _LAST_NAME ));
END;
I
Expression to outp ut
the rep's name
FIGURE 8-7
Procedure to find a rep's name given the rep's number
NOTE
PUSQL commands, like SOL commands, are free-format and can include blank lines to separate important sections of the procedure and spaces on the lines to make the commands more readable.
Tl1e CREATE PROCEDURE co1nmand in the stored proced11re ca11ses Oracle to create
a proced11re named DISP_REP_NAME. By i11cl11ding tl1e optional OR REPLACE cla11se in
tl1e CREATE PROCEDURE co1runand, you can 11se tl1e co1n1na11d to modify an existi11g
procedure. If yo11 01nit tl1e OR REPLACE cla11se, yo11 \.VOttld need to drop tl1e procedure
and then re-create it in order to cl1ange the proced11re later.
Tl1e first line of tl1e coIDinand co11tains a single arg111nent, I_REP_NUM. Tl1e \.Vord IN
follo\.ving the single arg111nent name i11dicates tl1at I_REP_l\TUM \.Vill be 11sed for i11p11t. That
is, tl1e 11ser mt1st enter a value for I_REP_NUM to use the procedure. Otl1er possibilities
are OUT, \Vl1ich i11dicates tl1at the proced11re "''ill set a val11e for the arg11ment, a11d INOUT,
\\rllich indicates that tl1e 11ser \.Vill enter a val11e tl1at the procedure can later cha11ge.
Variable 11ames in PUSQL m11st start \Vith a le tter a11d can contain le tters, dollar signs,
1111derscores, and n11mber signs, b11t caimot exceed 30 c l1aracters. \\Then declari11g variables, yo111nust assign the variable a data type, j11st as yo11 do i11 tl1e SQL CREATE TABLE
cormnand. Yott can ens11re that a variable has the same data type as a particttlar column in
a table by 11si11g tl1e %TYPE attrib11te. To do so, yo11 incl11de the 11ame of the table, follo\.ved
by a period and the name of the col11m11 , and the11 %TYPE. \Vhen yo11 11se %TYPE, you do
11ot enter a data type beca11se tl1e variable is a11tomatically assigned tl1e same type as tl1e
corresponding col11mn. In the first line of the script file sho\.vn in Fig11re 8 -7, assigning the
SOL Functions and Procedures
variable I_REP_NUM the same type as tl1e REP_NUM colt1mn in the REP table is written as
REP.REP NUM%TYPE .
Tl1e first li11e of tl1e CREATE PROCEDURE comn1and e nds witl1 tl1e \vord AS and is
followed by the commands in tl1e proced11re. Tl1e commands on lines 2 and 3 declare the
lo cal variables tl1e procedure req11ires. 111 Fig11re 8-7, lit1es 2 and 3 create two variables
named I_LAST_NAME and I_FIRST_NAME. Bo tl1 variables are assigned da ta types t1sing
%TYPE.
Tl1e procedural code , wl1ich contains the commands tl1at specify the procedure's
f11nc tion , appears bet\veen the BEGIN and El\TD comn1ands. In Fig11re 8-7, tl1e proced11ral
code begins \Vitl1 the SQL command to select tl1e las t name and first 11ame of the s ales rep
\Vhose n11mbe r is s tored iI1 I_REP_NUM. The SQL command uses tl1e INTO cla11se to place
tl1e res11lts in tl1e I- LAST- NAME and I- FIRST NAME variables. The next command 11ses
tl1e DBNIS_OUTPUT.PUT_LINE procedure to display tl1e concate11atio11 of tl1e trimmed
I- FIRST - NAME a11d I- LAST- NANIE variables. Notice tl1at a semicolon e11ds eacl1 variable
declaration , command, and tl1e \Vord END. Tl1e slasl1 (/) at tl1e end of tl1e proced11re
appears 011 its own line. In som e Oracle environme11ts, tl1e slash is optional. 1\ good practice is to include tl1e slasl1, even wl1en it's not necessary, so yo11r proced11re \Vill always
worlr correctly.
NOTE
DBMS_OUTPUT is a package that contains multiple procedures, including PUT_LINE. The SQL Commands page automatically displays the output produced by DBMS_OUTPUT. In the SQL Command Line
environment, you first have to execute a SET SERVEROUTPUT ON command to display the output.
To call (or 11se) tl1e procedt1re from the SQL Commands page, type the \Vord BEGIN,
followed by tl1e nain e of tl1e procedure including the desired value for the argt1ment in
pai·entheses, followed by the \Vord END, a semicolon, and a slash o n a separate li11e. To
11se tl1e DISP_REP_NANIE proced11re to find tl1e n ame of sales rep 3 0, fo r example, type
tl1e com1nand shown in Fig11re 8 -8.
l
Home
SQ!. Worllshop
E2l Autocommit
f1WS
Value for argument
(sales rep number 30}
SQL Convnands
l20
I., I (; .fl
Save
BEGIN
DISP_ REP_NA.'!E ( ' 30') ; - - - - - - - - - - -~
EtlD;
I
Results
L plam
Describe
saved SOL H1sto
Command to use the
DISP_REP_NAME
procedure
Megan Gradey + - - - - - - - - ,
Scacemenc processed.
0.02 seconds
FIGURE 8-8
Procedure resu lt
(name of sales rep 30}
~ - - - - - - - ---'
Using the DI SP_REP_NAME procedure within an SOL command
Chapter 8
ERROR HANDLING
Procedt1res mt1st be able to l1andle co11ditions tl1at can arise when accessing the database.
For example , the t1ser enters a rep nt1mber and tl1e DISP_REP_NAME procedure displays
tl1e corresponding rep's name. Vl l1at l1appens wl1e11 tl1e t1ser enters an invalid rep nt1mber? This situation rest1lts in the error message sl10\.vn in Figure 8-9 becat1se Oracle will
not fit1d any last name to display.
Home
SOL Workshop
0Autocommil
SQl Commands
1211
Rows
1--1~-?
( Save ) ( Run )
BEGIN
DI SP_REP_NAME'. ( ' 31 ' ) , -
/ Invalid rep"
number
END;
I
-
Results
plain
~
Oescnbe saved SOL History
ORA-01403 : o.o data foood _
message
FIGURE 8-9
"'
/.System error
System error that occurs when a user enters an invalid rep number
You ca11 include tl1e EXCEPT ION clause sl10\\7n in Figt1re 8 -10 to ha11dle processing an
invalid rep nt1mber . \\Tl1en a t1ser enters a rep nt11nber that does not 1natcl1 a11y rep nt1mber in tl1e REP table , tl1e NO_DATA_FOlThTD condition 011 line 13 \\7ill be trt1e . v\Tl1en tl1e
NO_DAT A_FOUND co11dition is tn1e, tl1e procedure displays tl1e "No rep \\7itl1 tllis 11t1n1ber :" 1nessage follo\\7ed by tl1e invalid rep 11umber .
Home
SOL Wor1cshop
SOL Scripts
Script Editor
I
Script Name DISPLAY_REP_NAME
Cancel
( Find & Replace ) ( Undo ) ( Redo )
CREATE OR IIBPLACE PROCEDURE DISP_REP_NJIJ.-iE ( I _REP_NUM IN REP.REP_NUMITYPE ) AS
2
I L.l\ST NAME
REP.LAST NAME\TYPE;
3
I FIRST NAME
REP. FIRST NJ\ME\TYPE;
•I
Tests fo r
s
BEGIN
SELECT LAST_NAME, FIRST_NAME
NO_DATA_FOUND
6
INTO I _ LAST_ NAME , I_FI RST_ NAME
7
condition
8
FROM REP
WHERE REP NUM e I REP NUM;
9
1
l
DBMS OUTPUT.PUT LINE( RIPIM ( l_FIRSI_NAME ) 11 ' 'I I RIRI~ ( _LASI_NAME));
12 EXCEPTION
.i.3
WHEN NO DATA FOUND THEN - - - - - - - - - - - - '
14
DBMS_OUTPUT . PUT_LINE ('No r ep wit:h t:hi" number : 'I II_RE P_NUM) ;
-
15
lf
E.ND;
17
I
EXCEPTIO N
clause
Action to t ake
when no data
is found
FIGURE 8-10
PL/SOL procedure with error handling
SOL Functions and Procedures
\\Tl1e n yott ttse this version of the procedttre and e nter an invalid re p nttmber , yott
\\'ill see tl1e e rro r m essage from tl1e procedttre (Figttre 8-11) ins tead of tl1e syste m error
m essage (Figure 8 -9).
I[Home
SOL Wor1cshot>
li'.l Autocommit
SQL Commands
Rows
[tti
EJ V ~
( Save )( Run)
BEGIN
DISP_REP_~ ( ' 31'); -
Invalid rep
number
END;
I
Results -: plain ~scribe Savell SQL
No r ep wich ctus nwube r: 31
History
Error message from
the procedure
)
Scatement processed .
0.00 seconds
FIGURE 8-11
Error message that occurs when a user enters an invalid rep number
Tl1e DISP_REP_NAME procedure must l1andle an e 1Tor tl1a t resttlts wl1e n a ttser e11ter s a n
invalid re p ntttnbe r . The re are otl1e r types of e11·ors tl1a t procedures mus t l1andle , dependii1g
on tl1e processing reqttired . For example, a tiser might e nter a commissio11 rate i11 a procedttre
to find tl1e name of tl1e sales re p ,vl10 l1as tl1a t commission ra te. \\Tl1e n tl1e ttser e nters the
rate 0.06, tl1e procedure \vill display tl1e TOO_MMTY_ROWS e rror because Rafael Campos,
Htti Tian, and Janet Sefton l1ave this same co1nmissio11 rate-tl1e procedure fi11ds tl1ree
rows ins tead of on e. Yott can m a11age this e rror by ,vriting a \\THEN clatise that contai11s a
TOO_Mf\NY_RO\VS condition , follo,,,ing tl1e EXCEPTION clattse i11 the procedttre. Yott cat1
\,r1ite b otl1 \\THEN cla ttses in tl1e same procedttre or in separate procedures. \\Tl1en adding botl1
\\THEN clauses to tl1e sa1ne procedure, l1owever , the EXCEPTION clatise appears 011ly once.
USING UPDATE PROCEDURES
111 Cl1apter 6, you lear11ed h o\\' to use SQL co1nn1ands to update data. You can ttse tl1e same
co111ma11ds \Vitllin procedures. A procedure tl1at updates d ata is called an update procedure.
Changing Data with a Procedure
Yott can use at1 ttpdate procedure to cl1ange a r o\V in a table, as illtts trated in Example 8.
EXAMPLE 8
Change the name of the customer whose number is stored in I_CUSTOMER_NUM to the
value currently stored in I_CUSTO:tvIER_NAME.
Tllis procedttre is s i1nilar to the procedttres ttsed i11 previotts examples witl1 two main
differ e11ces: it ttses an UPDATE command ins tead of a SELECT command, and tl1e re are t\vo
argume nts, I_CUSTOMER_NUM and I_CUSTOMER_N1\ME. Tl1e I_CUSTOMER_NUM
argt11ne nt s tores tl1e c us tom e r 11t1mbe r to be ttpdated and tl1e I_CUSTONIER_NAME argument
s tores tl1e 11e\v value for the c ttStome r name. The procedttre appears in Figt1re 8 -12.
Chapter 8
I[
SOL Scripts
SCfipt Editor
Script Name l cHANGE_CUST_NAME
I
Home
l
SQL Wor1csll0p
( Cancel )( Download
( Find & Replace ) ( Undo ) ( Redo )
CREATE OR REPLACE PROCEDURE CHG- CUST- NAME (l_CUSTOMER_NOM IN CUSTOMER . CUSTOMER_NUM\TYPE,
I_CUSTOMER_NAME Ill CUSTOMER. CUSTOMER_NAME\TYPE) •AS
BEGIN
UPDATE CUSTOMER
SET CUSTOME R NAME; I CUSTOMER NAME
WHERE CUSTOMER- NUM = I - CUSTOMER- NUM ;
-
-
-
A rg uments
- END;
I
FIGURE 8-12
Using a procedure to update a row
\\Tl1en yo11 r11n this proced11re , yo11 will 11eed to ft1r11isl1 val11es fo r tvvo argu1ne11ts.
Fig11re 8 -13 11ses this proced11re to chai1ge tl1e 11a1ne of c11s to111er 260 to Brookit1gs
Family Store.
Home
SOL Wor1csll0p
E2l Autocommit
Rows
Schema IPAATT/LAST I
SQL Commands
120
!vi~,#
( Save )( Run )
...
CHG COSI NA.."i£('260 ' ,'Brooking9 Fl!l!lily Score');
BEGIN
- -
END;
A rgument t hat
st ores t he new name
'
I
-
Results £: .p! I
-
rlbe Saved SOL History
A rgument t hat st ores
the customer number
S~atemeo~ processed .
0.01 seconds
FIGURE 8-13
Using a procedure to update the name of customer 260
Deleting Data with a Procedure
J11st as you would expect , if yo11 can 11se an update procedure to cl1ange a row in a table,
yot1 can also use on e to dele te a row from a table, as illus tra ted in Example 9.
EXAMPLE 9
Delete the order whose number is stored in I_ORDER_NUM from the ORDERS table, and
also delete each order line for the order whose order number is currently stored in the
variable from the ORDER LINE table.
If you attempt to delete the order in the ORDERS table firs t , referential integrity \.\7ill
prevent tl1e dele tion because matching ro\.VS \.\7ould still exist in tl1e ORDER_LINE table, so
it is a good idea to d ele te the orders fro111 tl1e ORDER_LINE table first . The procedure to
dele te a11 order a11d its related order lli1es appears in Figure 8-14. This procedure contail1s
two DELETE comn1ands. The first con1mand deletes all o rde r li11es in the ORDER LThTE
SOL Functions and Procedures
table on \.Vhicl1 tl1e order nt1mbe r m atches the val1.1e stored in the I O RDER NUM
argi1ment. Tl1e second cormnand deletes the order i11 the ORDERS table \.\1l1ose orde r
number ma tcl1es tl1e valt1e stored in tl1e I_ORDER_NUM a rgi1ment.
Home
SOL Workshop
SOL Saipts
Script Editor
I
Argument that stores the
order number to delete
Script Name DELETE_ORDER
( Find& Replace )( Undo )( Redo )
CREATE OR REPLACE PROCEDURE DEL ORDER (I_ORDER_NUM IN ORDERS.ORDER_ NUM\TYPE) AS
BEGIN
DELETE
FROM ORDER LINE
liHERE ORDER NOM • I ORDER NUM ;
--
1
-
Command to delete
all rows in the ORDER_LINE
table that match the entered
order number
-
DELETE
FROM ORDERS
}
liRERE ORDER_ NUM = I _ OROER_ NUM;
-
------,
l
.. ~ END;
•
I
Command to delete the
row in the ORDERS table that
matches the entered
order number
FIGURE 8-14
Procedure to delete a row and related rows from multiple tables
Figi1re 8 -15 sl1ows tl1e t1se of tl1is procedt1re to delete orde r ni1mbe r 51610. Even
tl1oi1gl1 tl1ere are two DELETE commands in the procedt1re, the user enters the
order nt1mber only once.
I Home SOL Workshop SQL Convnands
~
0Autocommit
Rows
110
1--1~.?
( Save )( Run )
BEG!N
OEL_ORDER( ' 51610');
END;
I
Results r plam Describe
.....I
•
saved SQL
History
S&e&emenc processed .
0.00 seconds
FIGURE 8-15
Using the procedure to delete an order
SELECTING MULTIPLE ROWS WITH A PROCEDURE
Tl1e procedt1res yot1 have seen so far inclt1de commands tl1at retrieve individt1al ro\.vs.
Yot1 can use an UPDATE or a DELETE con1mand in PUSQL to t1pda te or dele te mt1ltiple
rows. 'fhe commands are exect1ted and tl1e updates or dele ti ons occt1r. Then the
procedt1re can move on to tl1e next taslt.
Chapter 8
\\Tl1 at h appen s \>Vl1en a SELECT command in a procedi1re re trieves mi1ltiple rows?
For example, si1ppose tl1e SELECT com1nand r etrieves tl1e ni1mber and n am e of eacl1
ci1stom er re prese11ted by tl1e sales re p \\rl1ose ni1mbe r is stor ed in I_REP_NUM. Tl1ere is a
problem- PUSQL can process only on e record at a time, bt1t tl1is SQL comtnand re trieves
more than 011e r ow. vVl1ose ni1mber and n am e is placed in I_CUST01'.1ER_i\TUNI and
I- CUST OMER- NAME \.vl1en tl1e com 1n and r etrieves mor e than one ci1s tom er ro\\,? Sl1011ld
yoi1 m alle I_CUST OMER_NUM and I_CUS'f OMER_NAME arrays capable of h olding mi1ltiple ro\.\'S a11d , if so, wl1at sl1011ld be the size of these a rrays? Fo rti1nately, you can solve
tl1is problem by 11s it1g a ci1rsor .
Using a Cursor
A cursor is a p ointer to a ro\.V it1 tl1e collectio11 of ro\.VS re trieved by an SQL co1n1nand .
(This is not tl1e san1e cursor tl1at you see 011 your computer scr een .) The cursor advances
on e ro\\' at a ti1ne to provide sequential, on e-record-at-a-time access to the retrieved ro,,,s
so PL/SQL ca11 process the rows. By u sing a cursor , PUSQL ca11 process the set of
retrieved rows as tl1011gl1 tl1ey ...,,ere r ecords in a seque11tial file.
To use a cursor , you m us t fir st declare it , as illustrat ed it1 Exai11ple 10.
EXAMPLE 10
Retrieve and list the number and name of each customer represented by the sales rep
whose number is stored in the variable I_REP_NUM.
Tl1e first s tep it1 11si11g a ci1rsor is to declai·e tl1e ci1rsor and describe tl1e associated
q11e ry i11 tl1e decla ration sectio11 of the proced11re. 111 tl1is example, ass111ning tl1e cursor is
11am ed CUSTGROUP, tl1e com1na11d to declai·e tl1e c11rsor is:
CURSOR CUSTGROUP IS
SEL E CT CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER
WHERE REP NUM
= I RE P NUM;
Tl1is com1nand d oes 11,ot cause tl1e query to be exec11ted at this tilne; it orily d eclares a
ct1rsor 11a med CUSTGROUP and associa.tes tl1e cursor \.Vitl1 tl1e il1dicated quer y. Usi11g a
c11rsor i11 a proced11re il1volves three co1ru11a11ds: OPEN, FETCH, a11d CLOS E. Tl1e OPEN
com1nand op e11s tl1e c11rso r a11d ca11ses tl1e q11e ry to be exec11ted , 111alru1g tl1e r esults
available to tl1e procedt1re. Exec11ting a FETCH com111a11d adva11ces tl1e c11rsor to tl1e 11ext
rO\\' il1 the set of r ows retrieved by tl1e q11er y and places tl1e co11te11ts of tl1e ro\.v i11 tl1e
i11dicated varia bles. Fi11a1ly, tl1e CLOSE com111a11d closes a cursor a11d deactivates it. Data
retrieved by the exec11tio11 of tl1e q11ery is 110 lo11ger availa ble. Tl1e ct1rsor could b e op e11ed
agai11 later and processi11g co11ld begi11 agai11.
Tl1e OPEN, FETCH, a11d CLOSE com111a11ds 11sed il1 processil1g a c11rsor are a11alogo11s
to tl1e OPEN, READ , and CLOSE com1na11ds 11sed il1 processi11g a seq11e11tial file.
SOL Functions and Procedures
Opening a Cursor
Prior to ope11it1g the cursor, there are 110 rows available to be fetcl1ed. 111 Figure 8 -16, tllis is
i11dicated by tl1e absence of data i11 tl1e CUSTGROUP portio11 of the figure. Tl1e rigl1t side of
tl1e figure illustrates tl1e variables into wllich tl1e data ,vill be placed (I_CUSTOMER_Nl.Th1I
and I_CUSTONIER_NAME) and tl1e value CUSTGROUPo/4NOTFOUND. Once tl1e cursor has
been opened a11d all tl1e records have bee11 fetcl1ed, tl1e CUSTGROUPo/4NOTFOUND val11e is
set to TRUE. Procedures using tl1e cursor can use this value to indicate ,,,hen tl1e fetchi11g of
ro,,,s is complete.
CUSTGROUP
CUSTOMER
NUM
-
I CUSTOMER
CUSTOMER NAME
NUM
-
-
I CUSTOMER NAME
-
-
FALSE
row to
be fetched
11 0
FIGURE 8-16
CUSTGROUP
%NOTFOUND
Before OPEN
Tl1e OPEN co1nmand is ,vritten as follo,vs:
OPEN CUSTGROUP;
Fig11re 8 -17 sho,vs the res11lt of openi11g the CUSTGROUP c11rsor. In the fig11re, assume
tl1at I_REP_:t\TlJM is set to 15 before the OPEN command is exec11ted; tl1ere are no,v three
ro,,,s avail able to be fetcl1ed. No ro,vs l1ave yet been fetcl1ed, as i11dicated by the absence
of val11es in I- CUSTOMER- NUM and I- CUSTONIER- NAME. CUSTGROUPo/4NOTFOUND is
still F1-\ LSE. The c11rsor is positioned at tl1e first ro,v; tl1at is, tl1e next FETCH co1nmand
ca11ses the co11tents of the first ro,v to be placed in tl1e indicated variables.
CUSTGROUP
CUSTOMER-
I CUSTOMER
CUSTOMER- NAME
NUM
NUM
126
Toys Galore
502
Cards and More
713
Cress Store
893
All Season
Gi fts
FIGURE 8-17
•
-
next row t o
be fetched
I CUSTOMER NAME
-
-
CUSTGROUP
%NOTFOUND
FALSE
After OPEN, but before first FETCH
Fetching Rows from a Cursor
To fetch (get) the next ro,,, from a cursor, use the FETCH com111a11d. The FETCH com111and
is written as follo,vs:
FETCH CUSTGROUP INTO I CUSTOMER NUM, I CUSTOMER NAME;
Note that tl1e INTO clause is associated witl1 tl1e FETCH com111ai1d itself and 11ot ,vitl1
tl1e query used i11 tl1e cursor defi11ition. Tl1e execution of tl1is query could produce
Chapter 8
m11ltiple rovvs. The exec11tion of the FE'fCH command produces only a single row, so it is
appropriate that tl1e FETCH con1mand causes data to be placed in tl1e i11dicated variables.
Fig11res 8-18 thro11gh 8 -22 sl1ovv tl1e result of five FETCH commands. Tl1e first fo11r
fe tches are s11ccessf11l. In ea.c h case, the data fro1n the appropriate r o,v in the c11rsor is
placed i11 tl1e indica ted variables and CUSTGROUP%NOTFOUND is s till FALSE. Tl1e fiftl1
FETCH command is diffe re11t , ho\\rever , beca11se tl1ere is no more data to fe tcl1. In tl1is
case, tl1e contents of the variables are left 11nto11ched and CUS'fGROUPo/4NOTFOUND is
set to TRUE.
CUSTGROUP
CUSTOMER NAME
I - CUSTOMER
NUM
I - CUSTOMER- NAME
126
Toys Galore
126
Toys Galore
502
Cards and More
713
Cress Store
893
All Season
Gifts
I - CUSTOMER-
I - CUSTOMER- NAME
CUSTGROUP
%NOTFOUND
502
Cards and More
FALSE
I - CUSTOMER-
I - CUSTOMER- NAME
CUSTGROUP
%NOTFOUND
CUSTOMER
NUM
-
FIGURE 8-18
-
.
CUSTGROUP
%NOTFOUND
FALSE
next row to
be fetched
After first FETCH
CUSTGROUP
CUSTOMER
NUM
-
CUSTOMER NAME
-
126
Toys Galore
502
Cards and More
713
Cress Store
893
All Season
Gifts
FIGURE 8-19
NUM
o(
next row to
be fetched
After second FETCH
CUSTGROUP
CUSTOMER-
CUSTOMER- NAME
NUM
NUM
126
Toys Ga l ore
502
Cards and More
713
Cress Store
893
All Season
Gifts
FIGURE 8-20
71 3
o(
After th ird FETCH
next row to
be fetched
Cress Store
FALSE
SOL Functions and Procedures
CUSTGROUP
CUSTOMER-
I - CUSTOMER-
CUSTOMER NAME
-
NUM
126
Toys Galore
502
Cards and More
7 13
Cress Store
893
All Season
Gifts
NUM
893
•
FIGURE 8-21
I - CUSTOMER- NAME
All Season
Gifts
CUSTGROUP
%NOTFOUND
FALSE
next row to
be fetched
After fourth FETCH
CUSTGROUP
CUSTOMER
NUM
-
I - CUSTOMER-
CUSTOMER NAME
-
126
Toys Galore
502
Cards and More
713
Cress Store
893
Al l Season
Gifts
I - CUSTOMER- NAME
NUM
893
All Season
Gi fts
CUSTGROUP
%NOTFOUND
TRUE
more
• no
rows to be
fetched
FIGURE 8-22
After attempting a fifth FETCH (CUSTGROUP%NOTFOUND is TRUE)
Closing a Cursor
Tl1e CLOSE comma11d is written as follov,,s:
CLOSE CUSTGROUP;
Figure 8-23 shows the rest1lt of closi11g the CUSTGROUP ct1rsor. Tl1e data is no lo11ger
available.
CUSTGROUP
CUSTOMERNUM
CUSTOMER NAME
-
<
FIGURE 8-23
no rows to
be fetched
After CLOSE
Writing a Complete Procedure Using a Cursor
Figt1re 8 -24 sl1ows a complete procedure using a ct1rsor. Tl1e declaration portion contai11s
tl1e CUSTGROUP ct1rsor definition. Tl1e procedural portion begins witl1 tl1e co1mna11d to
Chapter 8
open tl1e CUSTGROUP c11rsor . Tl1e statements between the LOOP a11d END LOOP comma nds crea te a loop tl1at begins by fetcl1i11g tl1e 11ext row from tl1e c11rsor and placing tl1e
res11lts in I CUSTOMER NUM and I CUSTOMER NAME. Tl1e EXIT command tests tl1e
condition CUS'fGROUP%NOTFOUND. If tl1e condition is t1ue , tl1e loop is terminated . If
tl1e condition is no t trite , the DBMS_OUTPUT.PUT_LINE commands display the contents
of I CUSTOMER NUM a11d I CUSTOMER NAME.
Cancel
Sctipl Name !DISPLAY_REP_CUST
( Find & Replace )( Undo )( Redo )
CREATE OR REPLACE PROCEDURE DISP_REP_CUST(I_RE P_NUM -:rN REP .REP_NUM\TYPE) AS
I CUSTOMER NUM CUSTOMER.CUSTOMER NUM-%TYPE;
I CUSTOMER NAME CUSTOMER.CUSTOMER NAME\TYPE;
-
-
-
CURSOR CUSTGROUP IS
SELE.CT CUSTOMER_ NUM, CUSTOMER_NAME >-1FROM CUSTOMER
WHERE REP NUM = I REP NOM;
-
-
---!
-
Command to fetch a
row from the cursor
BE.GIN
•
OPEN CUSTGROUP;
LOOP
FETCH CUSTGROUP INTO I_CUSTOMER_NUM, I_CUSTOMER_NAME;
EXIT WHEN CUSTGROUP\NOTFOUND; - - - - - - - - - - - - - - - - - - - - - i - .
DBMS_OUIPUT.PUT_LINE ( I_CUSTOMER_ NUMI I ' 'I I I _ CUSTOMER_ NAME);
END LOOP;
Command to
d isplay the results
CLOSE CUSTGROUP;
END;
~
I
FIGURE 8-24
Command to determine
whether a row was
successfully fetched
Procedure with a cursor
Fig11re 8-25 sh ows tl1e res11lts of ttsing the proced11re . After the user enters 15 as the
val11e for the rep 1111mber, the proced11re displays tl1e n11mber and 11ame of each c11sto1n er
of sales rep 15 .
Home
SOL Wor1cshop
E2l Autocommlt
SQL Commands
Rows
110
l vlV .P
( Save
)C Run l
/
BEGIN
DISP_REP_CUS1( '15') _
/
END;
I
Results
-
15 entered as the
argument for the
rep number
uplam Oescnbe Saved SQL History
•
126 Toys GaJ.ore
502 Cards and More
713 Cres3 Si:;ore
S93 AJ.l Season Gifts.
Customers of rep 15
Statement processed .
0.01 seconds
FIGURE 8-25
Resu lts of using the procedure
-
SOL Functions and Procedures
Using More Complex Cursors
Tl1e query fo rmulatio11 tl1at defi11ed tl1e cursor in Example 10 vvas s traigl1tforward. An y
SQL query is legitimate it1 a cursor defi11ition. lt1 fact, the 1nore complicated the require111ents for re trieval, tl1e m ore 11umerous tl1e b e11efits derived by the program111e r vvl10 uses
embedded SQL . Consider tl1e query i11 Exa111ple 11.
EXAMPLE 11
For each order that contains an order line for the item whose item number is stored in
I_ITEM_NUM, re trieve the order number, order date, customer number , and the number,
last name, and first name of the sales rep wh o represents the customer.
Openit1g and closing the cursor is do11e exactly as sl1ow11 in Example 10. Tl1e only
differ e11ce in tl1e FETCH comma11d is tl1at a different set of varia bles is used it1 tl1e INTO
cla11se. Thus, the only real difference is tl1e c11rsor definition. Tl1e proced11re sl1ov,,n in
Fig11re 8-26 contain s tl1e appropriate cursor definitio11 .
( Cancel )( Download )
Script Name IDISPLAY_ITEM_ORDERS
( Deh
( Find & Replace )( Undo )( Redo )
CREATE OR REPLACE PROCEDURE DISP_ ITEM_ ORDERS (I _ ITEM_NUM IN ITEM.ITEM_NUM\TYPE) AS
I - ORDER- NUM ORDERS.ORDER- NUM\TYPE;
I ORDER DATE ORDERS.ORDER DATE\TYPE;
I CUSTOMER NUM ORDERS. CUSTOMER NUM\TYPE;
I REP NUM REP.REP NUM\TYPE;
- NAME REP . LAST
I - LAST
NAME\TYPE;
I FIRST NAME REP.FIRST NAME\TYPE;
CURSOR ORDGROUP IS
SELECT ORDERS.ORDE:R_NUM, ORDER_DATE, ORDERS.CtJSTOMER_NUM, CUSTOMER.REP_NUM, LAST_NAME, FIRST NAME
FROM ORDE:R_LINE, ORDERS, CUSTOMER, REP
. WHERE ORDER LINE.ORDER NUM = ORDERS.ORDER NUM
.~ AND ORDERS.CUSTOM.ER
NtJM = CUSTOM.ER.CUSTOMER NUM
AND CUSTOMER .REP NUM = REP.REP NUM
AND ITEM NUM = I ITEM NUM;
~
BEGIN
_ OPEN ORDGROUP;
LOOP
FETCH ORDGROUP INTO I_ORDER_NUM, I_ORDER_DATE, I_CUSTOMER_NUM, I_REP_NUM,
I_LAST_NAME, I_FIRST_NAME;
EXIT WHEN ORDGROUP\NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I_ORDER_NUM);
DBMS_OUTPUT.PUT_LINE(I_ORDER_DATE);
DBMS_OUTl?UT. PUT_LINE (I_CUSTOMER_NUM);
DBMS_OUTPUT.PUT_LINE(I_REP_NUM);
DBMS_OUTPUT.PUT_LINE(I_LAST_NAME);
DBMS_OUTPUT.PUT_LINE(I_FIRST_NAME);
E.ND LOOP;
CLOSE ORDGROUP;
-
-
-
-
END;
I
FIGURE 8-26
Procedure with a cursor that involves joining multiple tables
Tl1e res11lts of 11si11g tl1is proced11re to display the res11lts fo r ite1n FDll are sl1ow11 in
Fig11re 8-2 7 .
Chapter 8
11 Home
SOL Workshop
0Autocommit
Rows
SQL Convnands
1--1~#
110
( Save )( Run )
BEGIN
DISP ITEM ORDERS('FDll');
END;
-
-
I
Results
-
£ plilin Descnbe
Saved SOL History
51 614
10/13/2015
260
30
Gradey
Megan
5 1 619
10/15/2015
126
15
Campos
Rafael
Statement processed .
0.01 seconds
FIGURE 8-27
Resu lts of using the procedure to display orders containing item FD11
Advantages of Cursors
Tl1e re trieval reqt1ire1ne11ts i11 Exa1nple 11 are st1bsta11tial. Beyo11d codi11g tl1e precedi11g
ct1rsor defi11itio11, the progranuner doesn 't 11eed to "'rorry abot1t tl1e 111echa11ics of obtai11i11g
tl1e n ecessar y data or pla.c ing it in the right order , becat1se this happen s at1tomatically
wl1e11 tl1e ct1rsor is opened. To the progra111111er , it see1ns as if a seqt1ential file already
exis ts tl1at co11tail1s tl1e correct data, sorted il1 tl1e rigl1t order. This assumptio11 leads to
tl1ree main advantages:
1.
2.
3.
Tl1e codi11g il1 tl1e procedt1re is greatly si1nplified .
111 a 11ormal program, tl1e prograrrune r must deter111i11e the 1nost efficient \\ray
to access tl1e data. In a program or procedt1re usi11g emb edded SQL, tl1e
optimizer de ter1ni11es the best way to access the data . Tl1e progra1nmer is11't
concer11ed witl1 tl1e best \\ray to retrieve tl1e data. In addition, ,vl1en an
u11derlying stn1cture chru1ges (for example, an additional i11dex is c reated),
tl1e opti1nizer de termines tl1e best \Vay to execute the query \Vitl1 tl1e 11ew
s trt1c tt1re. Tl1e progr am or procedure does 11ot l1ave to cl1ange at all.
\\Tl1e11 tl1e database strt1ctt1re cl1anges it1 st1cl1 a \Vay tha t the 11ecessary inforn1ation is still obtainable using a different query, the 011ly cha11ge required in the progran1 or procedure is tl1e cursor definitio11. The procedttral code is n ot affected .
USING T-SQL IN SQL SERVER
SQL Server ttses an exte11ded version of S QL called T-SQL (Tra11sact-SQL). You can use
T-SQL to create s tored procedttres a11d use cursors. The reasons for creati11g a11d using
stored procedttres a11d ct1rsors are identical to tl1ose disct1ssed i11 the PUSQL sectio11.
Only tl1e coID1nru1d syntax is differ e11t.
SOL Functions and Procedures
Retrieving a Single Row and Column
111 Exa111ple 7 , you lear11ed l1ow to \\Trite a procedure in PL/SQL tl1at takes a rep 11umber as
i11put a11d displays tl1e correspondi11g rep 11ame. Tl1e follo\\Ting code sho\\TS 110\\Tyou would
create the s tored procedure il1 T-SQL:
CREATE PROCEDURE usp_ DISP_REP_NAME
@repn um c h ar ( 2)
AS
SEL E CT RTRIM (FIRST NAME ) + 1 1 +RTRIM (LAST NAME )
FROM REP
WHERE REP_NUM = @repn um
Tl1e CREATE PROCEDURE co111111and in the stor ed procedure cat1ses SQL Ser ver to
create a procedure na1ned usp_DISP_REP_NAME. Tl1e usp_ prefLx identifies tl1e procedure
as a user-s to red procedure. Although usil1g the prefix is optional , it is an easy way to differentiate user-sto red procedures from SQL Server syste1n-stored procedures. Tl1e argument for tl1is procedure is @repnum. In T-SQL, you must assigi1 a data type to parameters.
All argu1n ents start witl1 tl1e at (@) sig11. Argume11ts sh ould have tl1e s ame data type and
lengtl1 as the particular colu11111 it1 a table tha t tl1ey represe11t. In the REP table, REP_NUNI
was defu1ed ,vitl1 a CHAR da ta type and a lengtl1 of 2. Tl1e CREATE PROCEDURE com1nand e nds with the \\Tord AS follo\ved by the SELECT con1mai1d that comprises the
proc edure.
To call tl1e procedure, use tl1e EXEC com111and and il1clude any argu1nents in single
quotes. Tl1e procedure to find the 11ame of s ales rep 30 is:
1
EXE C usp_ DISP_REP_NAME 30
1
Tl1e result of executing tllis procedt1re is the sa1ne as that sho\\T11 i11 Figure 8-8.
Changing Data with a Stored Procedure
111 Example 8, yot1 learned ho\V to \\Trite a procedt1re in PUSQL tl1at cl1anges tl1e nam e
of a custom er . Tl1e follo\,ring co1nmands sl10\v yot1 110\v to c reate the s tored procedt1re i11
T-SQL:
CREAT E PROCEDURE usp_ CHG_ CUST_NAME
@c u stn um c h ar (3) ,
@custn ame c h ar ( 35)
AS
UPDAT E CUSTOMER
SET CUSTOMER NAME = @custn ame
WHERE CUSTOMER NUM = @custn um
Tl1e procedt1re l1as t\vo argi1ments, @ct1stnt1m and @ct1stna1ne, and t1ses an UPDATE
com1nand ins tead of a SELECT con1mand. To execi1te a sto red procedure witl1 two
argi11nents, separate the argi11nents \Vitl1 a com111a as sl1own il1 tl1e follo\ving co1nmand:
1
EXE C usp_ CHG_CUST_ NAME 260
1
,
' Brook i n gs Famil y Store '
Chapter 8
Deleting Data with a Stored Procedure
111 Exainple 9, you lear11ed ho"v to "''rite a procedure i11 PUSQL tl1at dele tes a11 order
11umber fro1n botl1 the ORDER_LINE table and the ORDERS ta ble. The followil1g
com1na11ds sh o"v ho\.v to c reate tl1e stored procedure in T-SQL:
CREAT E PROCEDURE usp_ DEL _ ORDER
@ordernum char(5)
AS
DEL ET E
FROM ORDER LINE
WHERE ORDER NUM
= @ordernum
DEL ET E
FROM ORDERS
WHERE ORDER NUM
= @ordernum
Using a Cursor
Ct1rsors serve the same purpose in T-SQL as they do i11 PUSQL and worlr exactly tl1e
same \.Vay. Yott need to declare a ci1rsor, open a ci1rsor, fetcl1 rows from a ci1rsor, and
close a ci1rsor . The 011ly differe11ce is in the command sy11tax. Tl1e following T-SQL
code performs exactly th e same taslr as tl1at sho\.vn in Example 10:
CREAT E PROCEDURE usp_ DISP_REP_CUST
@repnum c h ar ( 2)
AS
DE CLARE @custnum char ( 3)
DE CLARE @custname c h ar(35)
DE CLARE mycursor CURSOR READ_ONLY
FOR
SEL E CT CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER
WHERE REP_NUM
= @repnum
OPEN mycursor
F ETCH NEXT FROM mycursor
INTO @custnum, @custname
WHILE @@FETCH STATUS
=0
BEGIN
PRINT @custnum+ 1 1 + @custname
F ETCH NEXT FROM mycursor
INTO @custnum, @custname
END
CLOSE mycursor
DEALLOCATE mycursor
SOL Functions and Procedures
Tl1e procedure ttses one arg11ment, @repnttm . It also 11ses two variables and each
variable m11st be declared using a DECLARE stateme 11t. You also d eclare tl1e c11rsor b y
giving it a name, describing its properties, and associating it \Vith a SELECT statement .
Tl1e cttrsor property, READ_ONLY, m eans that tl1e c11rsor is 11sed for re trieval p11rposes
o nly. Tl1e OPEN, FETCH, and CLOSE com1na nds perform exactly tl1e same taslrs in TSQL as they do in PI/SQL. Tl1e OPEN command opens tl1e c11rsor and ca11ses the query
to be exec11ted . The FETCH command advances tl1e c11rsor to the n ext row and places
tl1e conte11ts of tl1e r o\v in the indicated variables. The CLOSE com1nand closes a c11rsor
and the DEALLOCATE co1nmand dele tes tl1e c11rsor . Tl1e DEALLOCATE comma11d is
no t 11ecessary bttt it does enable tl1e 11ser to 11se the same c11rsor name \Vitl1 anotl1er
procedure.
Tl1e \\THILE loop \Vill repeat 11ntil tl1e val11e of tl1e system variable @@FETCH_STATUS
is not zero. Tl1e PRINT command \Vill 011tp11t tl1e val11es s tored i11 @cus tn11m and @custname variables.
Using More Complex Cursors
T-SQL also can l1andle more complex queries. Tl1e T-SQL code for Example 11 is shown
belo\v:
CREAT E PROCEDURE usp_ DI SP_ ITEM_ ORDERS
@itemnum char (4)
AS
DE CLARE @ordernum c h ar ( 5)
DE CLARE @orderdate date
DE CLARE @custnum char ( 3)
DE CLARE @repnum char ( 2)
DE CLARE @l ast name char ( 15)
DE CLARE @firs tname char ( 15)
DE CLARE mycursor CURSOR READ_ ONLY
FOR
SEL E CT ORDERS . ORDER NUM, ORDER DATE , ORDERS . CUSTOMER NUM, CUSTOMER . REP NUM,
LAST NAME, FIRST NAME
FROM ORDER LINE, ORDERS, CUSTOMER , REP
WHERE ORDER LINE. ORDER NUM = ORDERS. ORDER NUM
AND ORDERS. CUSTOMER NUM = CUSTOMER. CUSTOMER NUM
AND CUSTOMER . REP NUM =REP. REP NUM
ANDITEM NUM = @itemnum
OPEN mycursor
FETCH NEXT FROM mycursor
INTO @ordernum, @orderdate, @custnum, @repnum, @l astname, @f irstname
Chapter 8
WHILE @@FETCH STATUS
=0
BEGIN
PRINT @ordernum
PRINT @orderdate
PRINT @custnum
PRINT @lastname
PRINT @firstname
F ETCH NEXT FROM mycursor
INTO @ordernum, @orderdate, @custnum, @repnum, @l as t name, @firstname
END
CLOSE mycursor
DEALLOCATE mycursor
USING SQL IN MICROSOFT ACCESS
Not every programining la.11gt1age accepts SQL comma11ds as readily as PL/SQL and
T-SQL. In Nlicr osoft Access, programs are vvritten in \Tist1al Basic, \Vllich does not st1pport
embedded SQL commands directly in tl1e code. \\T11en the SQL command is s tored in a
string variable, l1owever, yot1 can t1se tl1e D0Cmd .Rt111SQL command to n1n tl1e comma11d. Tl1e procedure in wl1icl1 yot1 place tl1e SQL command ca11 i11clt1de argt1ments.
Deleting Data with Visual Basic
To delete tl1e sales rep whose numbe r is 60, tl1e co1nn1and is:
DEL ET E FROM REP WHERE REP NUM =
1
60
1
;
\\Then yot1 "''rite tllis type of co1nn1and, yot1 t1sually do11' t k110,v i11 a.d vance the specific
sales rep nt1mber tl1at yot1 vvant to delete; it would be passed as a11 argtunent to tl1e procedure co11tainiI1g this DELETE co1n1na11d. In the followi11g example, tl1e sales r ep number
is stored i11 an argttment 11a1ned I_REP_NUNI.
EXAMPLE 12
Delete from the REP table the sales rep whose number currently is stored in I_REP_NUM.
Statem ents in the procedt1re t1st1ally c reate the appropriate DELETE command , t1sing
tl1e valtte in any necessary argt1ments. For example , when the command is s tored in tl1e
variable named s trSQL (whi ch mtts t be a string variable) a.n d tl1e rep nttmber is s tored in
tl1e argt1ment I_REP_NUM, tl1e follovving command is appropriate:
strSQL =
11
DEL ET E FROM REP WHERE REP NUM = ' 11
strSQL = strSQL & I
strSQL
= strSQL &
11 1 11
REP NUM
SOL Functions and Procedures
Tl1e first command sets the s trSQL stri11g varia ble to DELETE FR01vl REP \VHERE
REP_NUM = ' a11d c rea tes everytl1ing n ecessary in tl1e con1mand tip to a nd including the
single quo tatio n 1narlr preceding tl1e re p nu1nbe r . Tl1e seco11d comma11d 11ses co11cate nation (&). It cl1anges s trSQL to the res11lt of the previo11s val11e con caten a ted ,vith the val11e
in I_REP_l\TlJM. \i\Tl1 en I_REP_NUM contai11s tl1e val11e 60 , for example , tl1e command
wo11ld be DELETE FROM REP \\THERE REP_NUM = ' 60. The final comma nd sets s trSQL
to tl1e r es11lt of tl1e val11e already c reated , con ca ten a ted ,vith a single q11otation marlr. The
command is no,v comple te.
Figure 8-28 sl10,vs a co1nple ted proced11re to acco1nplisl1 tl1e necessary dele tion in
Access. Y011 e nte r this proced11re in tl1e lvlic rosoft Vis11al Basic window. In tl1e program ,
tl1e Dim s ta te me nt c reates a string varia ble named s trSQL. The n ext three commands set
strSQL to the appropria te SQL command. Finally, tl1e DoCn1d .R11nSQL comma nd tuns tl1e
SQL command s tored i11 strSQL.
4 file ;_dit View !nsert
Debug
MIW1
Project - TAL Distributo1
□
El-·
IIQI
Run
Iools
1 ►
11
Add-Ins
Window
Help
@
ln 13, Coll
XI (General)
.,
RepD
Argume nt
(I_REP _NUM)
L-"-r-Op-c_i_on_C_on.p-ar_e_Da_c_ab_a_s_e_ _I------.::....==----,
T AL Distributors (TAL Di
El -~ Modules
:... ~ Modulel
Public Funccion RepDe lece(I_REP_NOM)
Dim scrSQL As Sering
scrSQL = "DELETE FROM REP WHERE REP_NOM = '" . .+--<
scrSQL • scrSQL & I _REP_NOM
scrSQL = scrSQL & " ' "
Commands to
set strSO L
DoCmd . RunSQL scrSQL +-- - - - - - - - -+-- - - ---,
End Funccion
FIGURE 8-28
Runs command
stored in strSOL
Visual Basic code to delete a sales rep
NOTE
If you have concerns about how you constructed the SOL command in strSOL, you can include the
Debug.Print (strSOL) command after the set of commands that construct strSOL. The Debug. Print
command displays the entire command before it is executed so you can review it for accuracy. If you
need to correct an error, rerun the program after making the necessary changes. If you get an error in
your program, check your SOL command carefully to make sure that you concatenated it correctly.
Running the Code
Nor1nally, yo11 r1111 code lilre tl1e f1111ctio11 sl10,v11 i11 Fig11re 8-28 by calling it fro111 a11otl1er
proced11re or associa ti11g it ,,,itl1 some eve11t, s11cl1 as clickit1g a b11tton 011 a fo rm . However ,
yo11 can r11n it directly by 11si11g tl1e I1runedia te ,,,i11do,v ( cliclr Vie v.r 011 tl1e 1ne1111 bar, a11d
tl1e11 click hnmediate \Vi11dow to op en it) . Normally, yo11 ,,,011ld 11se tl1is ,,,i11dow only for
Chapter 8
testing p11rposes, b11t yo11 ca11 11se it to see the resitlt of r11nning the code. To r11n a F11nction proced11re, s11cl1 as the 011e sho\v11 i11 Figure 8-28, in tl1e Immediate \Vindo\v, type a
question n1arli., follo\ved by tl1e name of tl1e proced11re and a set of p arentl1eses, as sl10\vn
in Fig11re 8-29. Place the val11es for any arg11ments in the parentl1eses. Assumit1g that yo11
\Vanted to d ele te a sales rep \Vl1ose n11mber is 60, yo11 \\ro11ld i11clude 11 60 11 i11side tl1e
parentl1eses as sl10\vn in the fig11re.
tJ
4 file ~dit l[iew !nsert Qebug Bun Iools ,Add- Ins ~indow
~ ~ • Q
~
Project • TAL Distributo1
El
II□
I
►
")
Ul
Cit ~
~ ~ •=1
XI [(General)
"]
RepDe
L-=;;;=Op;;:::t:.;;:::i;;:::on=C=om:p=a=re=Da;;:::t:.;;:::ab;;:::a;;::::,;;:::e========;:;!....;==I
=s=~~===,-
e
TAL Distributors (TAL Di
El ~ Modules
;...a Module!
Public Funct:.ion RepDe let:.e(I_REP_NUM)
Dim st:.rSQL As St:.ring
st:.rSQL = "DELETE FROM REP WHERE REP_NOM =
st:.rSQL = st:.rSQL & I_ REP_NOM
:,i;rSQL = st:.rSQL & " ' "
'"
DoCred . RunSQL st:.rSQL
End Funct:.ion
Procedure to delete records
in Immediate window
Immediate
?RepDelet:.e ( " 60 " ) -
FIGURE 8-29
------'
Running the code in the Immediate window
After you type the command and press Ente r , tl1e code will 1un and the appropriate
actio11 will occur . In this case, tl1e co1nn1and dele tes tl1e sales rep with tl1e number 60
(ass111ning there is a sales rep 60).
Updating Data with Visual Basic
A proced11re that 11pdates a table 11sing an UPDA'fE com 1na11d is similar to tl1e one 11sed to
delete a sales rep . In Example 13, t\vo arg11ments are req11ired . One of tl1em, I_LAS'f _NAME ,
contains the ne\v 11ame for the sales re p. Tl1e otl1er, I_REP_NlTh1, contains tl1e n11111ber of
tl1e re p whose name is to b e changed .
SOL Functions and Procedures
EXAMPLE 13
Change the last name of the sales rep whose number is stored in I_REP_NUM to the
value currently stored in I_LAST_NAME.
Tl1is e xa111ple is similar to the previous 011e \<\7ith t"vo in1portant diffe re nces. First, you
need to u se the UPDATE co1n1nand il1stead of tl1e DELETE co11uua11d. Seco11d, the re are
t\<\ro argu111e nts, so the re are t"vo portio11s of tl1e cons t1uc tion of tl1e SQL co1nma11d tha t
involve variables. The comple te procedure is sh o"vn il1 Figure 8 -30 .
Public Function RepUpdate(I_LAST_NAME, I - REP- NUM)
Dim strSQL As String
strSQL = "UPDATE REP SET LAST NAME =
strSQL = strSQL & I - LAST- NAME
WHERE REP NUM strSQL = strSQL &
strSQL = strSQL & I - REP- NUM
strSQL = strSQL & II I
I
I
II
I II
If
DoCmd.RunSQL strSQL
I
End Function
FIGURE 8-30
Code to change a rep's last name
To n1n tl1is procedt1re, yot1 '\,VOt1ld e nte r valt1es fo r botl1 argt11nents as sh o\<\7n in
Figt1re 8-31 .
I ?RepUpdate ( "Webb " , 30 " ) I
11
FIGURE 8-31
Running the code to change the last name of rep 30 to Webb
Inserting Data with Visual Basic
Tl1e process for i11serti11g rows is sitnilar il1 Access wl1e11 co111pare d to PL/SQL or T-SQL.
Yott c reate tl1e appropria te INSERT co1n1nand i11 tl1e strSQL variable. Tl1e re "vill be
1nt1ltiple argt1n1e11ts il1 tl1e procedt1re-011e for e a cl1 value to b e il1serte d .
Finding Multiple Rows with Visual Basic
Jt1s t as wl1en e1nbeddi11g SQL in PUSQL, de le ti11g or ttpdating mt1ltiple r o"vs cat1ses n o
proble m s, because tl1ese procedures still r epresent a sil1gle op eration , "''itl1 all tl1e wo rlr
l1a ppe11ing bellind the scen es. A SELECT command tl1at re turns several rows, however,
poses seriot1s proble m s for r ecord-a t-a-ti1ne langt1ages like PL/SQL and Vist1al Basic. Yott
l1andle SELECT comma11ds differ ently in Access tha11 you do il1 PUSQL o r T-SQL. In partict1lar, tl1ere are no cursors il1 Access. Inste ad, yot1 handle tl1e rest1lts of a que ry just as
yot1 migl1t t1se a loop to process tl1rot1gl1 tl1e r ecords in a table.
Chapter 8
EXAMPLE 14
Retrieve and lis t the name of each customer represented by the sales rep ,vhose number
is stored in the variable I- REP- NUM.
Figure 8 -32 sl1ows a procedure to accomplish the indicated tasl{. The stateme11ts
involving rs and c1111 are a typical "''ay of processil1g through a recordset, that is, tl1rougl1
all the records contai11ed ill a table or in the results of a query. The 011ly difference
between this progra1n a11d one to process all tl1e records in a table is that tl1e Open com1nand refers to an SQL co111mand a11d not a table . (The SQL con1111a11d is stored in the
variable 11amed strSQL a11d is created in the same 1na1111er as show11 i11 tl1e previous
exa111ples.)
Public Function FindCustomers(I- REP- NUM)
Dim rs As New ADODB . Recordset
Di m cnn as ADODB . Connection
Dim strSQL As String
Set cnn = CurrentProject . Connection
Opens a reco rdset fo r
the q uery stored
in strSOL
strSQL = "SELECT CUSTOMER NAME FROM CUSTOMER WHERE REP NUM strSQL = strSQL & I_REP_NUM
strSQL = strSQL &
11 1
;
I
ll
"
rs . Open strSQL, cnn, adOpenStatic, , adCmdText ____ _ ____
!-+-► Do Until rs . EOF
Prints the customer
Debug . Print (rs !CUSTOMER NAME) -+----r
na me fo r the current
rs.MoveNext +---::.,,..--- - - record in recordset
End of loo p \ - + -+ Loop
Moves to the next
Loops until end of
file fo r recordset
End Function
FIGURE 8-32
record in recordset
Code to find customers of a specific rep
Tl1e loop co11ti11ues until reaclling tl1e e11d of file for tl1e recordset, tl1at is, u11til all
records have been processed. " 'ithit1 tl1e loop, you can use tl1e Debug.Print co1ru11and to
pri11t a value. 111 tllis case, tl1e value to be pri11ted is rs! CUSTOMER_NM1E. Tl1is il1dicates tl1e contents of tl1e CUSTOMER_NMffi colu1nn for the record in the recordset (rs)
on wl1icl1 Access is curre11 tly positioned. The 11ext comma11d, rs .MoveNext, 111oves to tl1e
11ext record in tl1e recordset. Tl1e loop continues until all records ill tl1e recordset have
bee11 processed.
Figure 8-33 shov\'S the results of ru1111ing tllis procedure and e11teri11g a value of 11 15 11 as
an argume11t. Access displays the four c11stomers of sales rep 15 .
?FindCustomers ( "15")
Toys Galore
Cards and More
Cress Store
All Season Gifts
FIGURE 8-33
Running the code to find customers of rep 15
SOL Functions and Procedures
NOTE
When you expect an SOL query to return only one record, you would use the same process but would
not need a loop.
USING A TRIGGER
A trigger is a proced1.1re tl1at is exec1.1ted a1.1to1natically i11 resp o11se to a.n associated database oper ation , s1.1ch as an INSERT, UPDATE, or DELETE com1nand. Unlil{e a s tored pro cedure, "''l1icl1 is executed i11 respon se to a 1.1ser r equest, a trigger is exec1.1ted in respon se
to a commru1d that ca1.1ses tl1e associated database operation to occ1.1r.
Tl1e examples in tl1is section ass1.1me tl1ere is a 11ew col1.1mn named ON_ORDER iI1 the
ITEM table. Tl1is colu1nn represents the number of units of a11 item c1.1rrently on orde r. For
example, if tl1ere are two separate order lines for an item and tl1e 111.1mber ordered 011 one order
line is 3 and tl1e n1.11nber ordered 011 tl1e other order line is 2, the ON_ORDER value for that
item vvill be 5 . 1-\ ddillg, ch a11ging, or deleting order lines affects tl1e val1.1e iI1 tl1e ON_ ORDER
column for the item . To enSttre tl1at the val1.1e is updated approp1iately, you can use a trigger .
If you created tl1e ADD_ ORDER_LINE trigger sl1ovvn in Fig1.1re 8 -34, the SQL com1nand in tl1e trigger v\rou ld be executed vvl1en a user adds a11 order li11e. Tl1e trigge r mus t
1.1pdate the ON_ ORDER val1.1e for tl1e corresponding item to r eflect tl1e order line. Fo r
example, if tl1e value in the ON_ ORDER col1.1nn1 for item FDll is 3 and the 1.1ser adds a11
order line on "''l1icl1 tl1e item 111.1mbe r is FD l l a11d the 11umber of units ordered is 2, 5
1.111its of item FDll will be on order . Vl l1en a record is added to the ORDER_LINE table,
tl1e ADD_ORDER_LI~TE trigger ttpdates tl1e ITEM table by addillg tl1e n1.1mbe r of 1.1nits
ordered on the o rder line to tl1e previo1.1s val1.1e i11 tl1e ON_ORDER column .
Home
l
SOL WorllshOp
SQL Scnpts
Scnpt Editor
I
Script Name IADO_OROER_LINE
( Find & Replace )( Undo )( Redo )
-
.
-
CREA.IE OR REPLACE TRIGGER ADD ORDER LINE
AFTER INSERT ON ORDER LINE FOR EACH ROW
BEGIN
UPDATE ITEM
SET ON ORDER • ON ORDER+ :NEW .NUM ORDERED
WHERE ITEM NUM e :NEW. ITEM NUM ;
E.ND;
FIGURE 8-34
-
-
-
ADD_O RDER_LI NE trigger
Tl1e firs t line indicates tl1at the com1nand is c reating a trigger 11a1ned ADD_ ORDER_
LINE. Tl1e second line indicates tha t tllis trigger will be executed after an order line is
inserted a11d tl1at the SQL command is to occur for eac l1 r O\\' tl1at is added . Like s tored
proced1.1res, the SQL c0Inn1and is enclosed be t\\reen tl1e "''ords BEGIN a11d END. 111 tllis
case, tl1e SQL comma11d is a11 UPD1\TE com1nand. Tl1e command 1.1ses tl1e NE\\T qualifier ,
wl1icl1 refers to tl1e r ow that is added to tl1e ORDER LINE table. If an order line is added
on "'' hich tl1e item n1.1mbe r is FD l l a11d the number o rde red is 2, fo r example,
NEVl.ITEM NUM will be FDll and NE\\T.Nl.JNI ORDERED "''ill be 2.
Chapter 8
Tl1e UPDATE_ ORDER_LINE trigge r shown in Figt1re 8 -35 is execttted \Vl1en a
ttser attempts to update a11 order line. There are two differ en ces beh,,een tl1e
UPDATE_ORDER_LINE trigger and tl1e ADD_ ORDER_LINE trigger . First, tl1e seco11d
li11e of tl1e UPDATE_ORDER_LINE trigger indicates tl1at tl1is trigger is execttted after
ru1 UPDATE of an order liI1e ratl1er tl1an an INSERT. Second , the compt1tation to ttpdate
tl1e ON- ORDER column inclttdes botl1 NE\\T.NID.1I - ORDERED and OLD.NUM- ORDERED.
As \Vitl1 tl1e ADD_ ORDER_LINE trigger , NE\1/.Nill/I_ORDERED refer s to the n ew valtte.
In a11 UPDATE command, 110\vever , tl1er e is also a11 old valu e, ,vhicl1 is tl1e valt1e before
tl1e ttpdate talres place. If an ttpdate cl1anges the valtte fo r :t\Tl.JM_ ORDERED from 2 to 3,
OLD.Nill/I_ORDERED is 2 and NE\1/.NU11_0RDERED is 3. Adding NE\1/.NUM_ORDERED
ru1d st1btracti11g OLD.NUM_ORDERED rest1lts in a net change of an increase of 1. (Tl1e net
cl1ange cottld also be negative, in ,vhicl1 case tl1e ON_ ORDER valtte decreases.)
SQL Scnpts
Script Editor
Script Name !UPDATE ORDER LINE
I
Home
SQL Worllshop
( Find & Replace )( Undo )( Redo )
-
<
CREATE OR REl'LACE 'IRIGGER UPDAT E ORDER LINE
AFTER UPDATE ON ORDER- LINE FOR EACH ROW
BEGIN
UPDATE ITEM
SET ON ORDER - ON ORDER+ :NEW . NUM- ORDERED - :OLD. NUM- ORDERED
WHERE -ITEM- NUM - -:NEW. ITEM- NUM;
-
-
E.ND;
UPDATE_ORDER_LI NE trigger
Tl1e DELETE_ORDER_ LThTE trigger shov.r11 i11 Figt1re 8-36 pe rforms a ft111c tion
siI11ilar to tl1e otl1er hvo. \\'11e11 a11 order li11e is deleted , tl1e ON_ORDER valtte for tl1e
correspo11diI1g ite1n is updated by st1btrac tiI1g OLD.Nill/I_ORDERED from tl1e ct1rrent
ON_ORDER valtte. (111 a dele te operatio11, there is 110 NE\\T.NUM_ORDERED.)
FIGURE 8-35
SQL Scnpts
Scnpt Editor
Script Name !DELETE ORDER LINE
I
Home
l
SQL Worxshol)
( Find & Replace )( Undo )( Redo )
_ CREATE OR REPLACE 'IRIGGER DELETE ORDER LINE
AFTER DELETE ON ORDER- LINE FOR L~CH ROW
BEGIN
UPDA'IE ITEM
SE'I ON ORDER - ON ORDER - :OLD . NUM- ORDERED
WHERE -ITEM- NUM e -:OLD. ITEM- NUM ;
END;
-
FIGURE 8-36
-
DELETE_ORDER_LINE trigger
ACCESS
USER
NOTE
Access does not support triggers. When using a form to update table data, you can achieve some of the
same functionality by creating VBA code to be executed after the insertion, update, or deletion of records.
SOL Functions and Procedures
You also can achieve the same functionality as triggers by using data macros with tables in Access.
You can create a data macro using the options on the TABLE TOOLS TABLE tab. Data macros can be
associated with events that occur both before and after inserting, changing, and deleting records.
SQL SERVER
USER
NOTE
In SOL Server, you create triggers using T-SOL. The code to create the ADD_ORDER_LINE trigger is:
CREATE TRIGGER ADD ORDER LINE
ON ORDER LINE
AFTER INSERT
AS
DECLARE @numbord decimal ( 3, O)
SELECT @numbord = (SELECT NUM ORDERED FROM INSERTED)
UPDATE ITEM
SET ON ORDER = ON ORDER + @numbord
This trigger uses one variable, @numbord, and the value placed in that variable is obtained from the
SELECT statement. The INSERTED table is a temporary system table that contains a copy of the
values that the last SOL command inserted. The column names are the same column names as in the
ORDER_LINE table. The INSERTED table holds the most recent value of the NUM_ORDERED column,
which is what you need to update the ITEM table.
The T-SOL trigger that executes after an UPDATE of an order line is:
CREATE TRIGGER UPDATE ORDER LINE
ON ORDER LINE
AFTER UPDATE
AS
DECLARE @newnumbord decimal (3, O)
DECLARE @oldnumbord decimal (3, 0)
SELECT @newnumbord = (SELECT NUM ORDERED FROM INSERTED)
SELE CT @oldnumbord = (SELECT NUM ORDERED FROM DELETED)
UPDATE ITEM
SET ON ORDER = ON ORDER + @newnumbord - @oldnumbord
This trigger uses the INSERTED table and the DELETED table. The DELETED table contains the
previous value of the NUM_ORDERED column while the INSERTED column contains the updated value.
The DELETE_ORDER_LINE trigger uses only the DELETED system table:
CREATE TRIGGER DELETE ORDER LINE
ON ORDER LINE
AFTER DELETE
AS
DECLARE @numbord decimal (3, 0)
SELECT @numbord = (SELECT NUM ORDERED FROM DELETED)
UPDATE ITEM
SET ON ORDER = ON ORDER - @numbord
•
Chapter 8
Chapter Summary
•
The results of some functions are based on the values in single records. UPPER and
LOWER are two examples of functions that act on character data. UPPER displays
each letter in the argument in uppercase. LOWER displays each letter in the argument
in lowercase.
•
ROUND and FLOOR are two examples of functions that act on numeric data. ROUND produces its result by rounding the value to the specified number of decimal places. FLOOR
produces its result by truncating (removing) everything to the right of the decimal point.
•
Use the ADD_MONTHS function in Oracle to add a specific number of months to a
date. In Access and in SQL Server, use the DATEADD function.
•
To add a specific number of days to a date, use normal addition. You can also subtract one date from another to produce the number of days between two dates.
•
To obtain today's date, use the SYSDATE function in Oracle, the GETDATE() function
in SQL Server, and the DATE() function in Access.
•
To concatenate values in character columns in Oracle, separate the column names
with two vertical lines (II). Use the RTRIM function to delete any extra spaces that
follow the values. In SQL Server, use the + symbol to concatenate values. In Access,
use the ampersand (&) symbol to concatenate values.
•
A stored procedure is a query saved in a file that users can execute later.
•
To create a stored procedure in PUSQL or T-SQL, use the CREATE PROCEDURE
command.
•
Variables in PUSQL procedures are declared after the word DECLARE. To assign
variables the same type as a column in the database, use the 0/oTYPE attribute.
•
Use the INTO clause in the SELECT command to place the results of a SELECT
command in variables in Oracle.
•
You can use INSERT, UPDATE, and DELETE commands in PUSQL and T-SQL
procedures, even when they affect more than one row.
•
When a SELECT command is to retrieve more than one row in PL/SOL or T-SQL, it
must be used to define a cursor that will be used to select one row at a time.
•
Use the OPEN command to activate a cursor and execute the query in the cursor definition.
•
Use the FETCH command to select the next row in PL/SQL and T-SQL.
•
Use the CLOSE command to deactivate a cursor. The rows initially retrieved will no
longer be available to PUSQL or T-SQL.
•
To use SQL commands in Access, create the command in a string variable. To run
the command stored in the string variable, use the DoCmd.RunSQL command.
•
To process a collection of rows retrieved by a SELECT command in Access, use a
recordset. Create the SQL command in a string variable and use the string variable in
the command to open the recordset.
SOL Functions and Procedures
•
To move to the next record in a recordset in Access, use the MoveNext command.
•
A trigger is an action that occurs automatically in response to an associated database
operation, such as an INSERT, UPDATE, or DELETE command. Like a stored procedure, a trigger is stored and compiled on the server. Unlike a stored procedure, which
is executed in response to a user request, a trigger is executed in response to a
command that causes the associated database operation to occur.
Key Terms
ADD MONTHS
PL/SOL
argument
procedural code
call
procedural language
client
client/server system
ROUND
CLOSE
server
concatenate
stored procedure
concatenation
SYSDATE
Transact-SOL
cursor
embed
RTRIM
FETCH
trigger
T-SOL
FLOOR
update procedure
LOWER
UPPER
nonprocedural language
OPEN
Review Questions
1. How do you display letters in uppercase in Oracle, Access, and SOL Server? How do you
display letters in lowercase in Oracle, Access, and SOL Server?
2. How do you round a number to a specific number of decimal places in Oracle, Access, and
SOL Server? How do you remove everything to the right of the decimal place in Oracle,
Access, and SOL Server?
3. How do you add months to a date in Oracle, Access, and SOL Server? How do you add
days to a date? How would you find the number of days between two dates?
4. How do you obtain today's date in Oracle, Access, and SOL Server?
5. How do you concatenate values in character columns in Oracle, Access, and SOL Server?
6. Which function deletes extra spaces at the end of a value?
7. What are stored procedures? What purpose do they serve?
8. In which portion of a PUSOL procedure do you embed SOL commands?
Chapter 8
9. Where do you declare variables in PUSOL procedures?
10. In PUSOL, how do you assign variables the same type as a column in the database?
11 . How do you place the results of a SELECT command into variables in PUSOL?
12. Can you use INSERT, UPDATE, or DELETE commands that affect more than one row in
PL/SOL procedures?
13. How do you use a SELECT command that retrieves more than one row in a PUSOL
procedure?
14. Which PUSOL command activates a cursor?
15. Which PUSOL command selects the next row in a cursor?
16. Which PUSOL command deactivates a cursor?
17. How do you use SOL commands in Access?
18. How do you process a collection of rows retrieved by a SELECT command in Access?
19. How do you move to the next record in a recordset in Access?
20. What are triggers? What purpose do they serve?
21 . What is the purpose of the INSERTED and DELETED tables in SOL Server?
CRITICAL
THINKING
22. When you run the following SOL command , the result is "no data found." You know that
one record should be retrieved. Rewrite the SOL command using a function that will
retrieve the record.
SELECT ITEM NUM, DE SCRI PTION, PRICE
FROM ITE M
1
1
WHERE DE SCRI PTION= patien ce ;
Exercises
T AL Distributors
Use the TAL Distributors database (see Figure 1-2 in Chapter 1) to complete the following
exercises. If directed to do so by your instructor, use the information provided with the Chapter
3 Exercises to print your output or save it to a file .
1.
List the item number and description for all items. The descriptions should appear in
uppercase letters.
2.
List the customer number and name for all customers located in the city of Grove.
Your query should ignore case. For example, a customer with the city Grove should be
included as should customers whose city is GROVE, grove, GrOvE, and so on.
3.
List the customer number, name, and balance for all customers. The balance should be
rounded to the nearest dollar.
4.
TAL Distributors is running a promotion that is valid for up to 20 days after an order is
placed. List the order number, customer number, customer name, and the promotion date
for each order. The promotion date is 20 days after the order was placed.
SOL Functions and Procedures
5. Write PUSOL or T-SOL procedures to accomplish the following tasks:
a. Obtain the name and credit limit of the customer whose number currently is stored in
I- CUSTOMER- NUM. Place these values in the variables I- CUSTOMER- NAME and
I_CREDIT_LIMIT, respectively. Output the contents of I_CUSTOMER_NAME and
I- CREDIT- LIMIT.
b. Obtain the order date, customer number, and name for the order whose number
currently is stored in I_ORDER_NUM. Place these values in the variables
I_ORDER_DATE, I_CUSTOMER_NUM and I_CUSTOMER_NAME, respectively.
Output the contents of I_ORDER_DATE, I_CUSTOMER_NUM, and
I- CUSTOMER- NAME.
c. Add a row to the ORDERS table.
d. Change the date of the order whose number is stored in I_ORDER_NUM to the date
currently found in I_ORDER_DATE.
e. Delete the order whose number is stored in I- ORDER- NUM.
6. Write PUSOL or T-SOL procedures to retrieve and output the item number, description,
storehouse number, and unit price of every item in the category stored in !_CATEGORY.
7. Write Access functions to accomplish the following tasks:
a. Delete the order whose number is stored in I- ORDER- NUM.
b. Change the date of the order whose number is stored in I_ORDER_NUM to the date
currently found in I_ORDER_DATE.
c. Retrieve and output the item number, description, storehouse number, and unit price
of every item in the category stored in !_CATEGORY.
8. Write a stored procedure in PUSOL or T-SOL that will change the price of an item with
a given item number. How would you use this stored procedure to change the price of
item AH74 to $26.95?
9. Write the code for the following triggers in PUSOL orT-SOL following the style shown in the text.
a. When adding a customer, add the customer's balance multiplied by the sales rep's
commission rate to the commission for the corresponding sales rep.
b. When updating a customer, add the difference between the new balance and the old
balance multiplied by the sales rep's commission rate to the commission for the corresponding sales rep.
c. When deleting a customer, subtract the balance multiplied by the sales rep's commission rate from the commission for the corresponding sales rep.
C RITICAL
THINKING
10. Oracle SOL includes several date and time functions. Two of these functions are
CURRENT- DATE and MONTHS- BETWEEN. Use the Internet to research these functions. How does the CURRENT DATE function differ from the SYSDATE function? Are
the functions available in Oracle, SOL Server, and Access? Write a paragraph that discusses what the functions do and any differences and/or similarities between the functions
in Oracle, SOL Server, and Access. Then perform the following tasks:
a. TAL Distributors would like to know the number of months between the current date
and the order date of an order. Write an SOL statement in Oracle that displays the
order number and the number of months between the current date and the order
•
Chapter 8
b.
date. The number of months should display as an integer. (Hint: You can nest one
function within another function.)
The NOW() function is another function in Access that will retrieve the current date.
How does it differ from the DATE() function? Be sure to cite your references.
Colonial Adventure Tours
Use the Colonial Adventure Tours database (see Figures 1-4 through 1-8 in Chapter 1) to
complete the following exercises. If directed to do so by your instructor, use the information
provided with the Chapter 3 Exercises to print your output or save it to a file .
1. List the guide number, first name, and last name for all guides. The first name should
appear in lowercase letters and the last name should appear in uppercase letters.
2. List the trip ID and trip name for all trips that start in Bar Harbor. Your query should ignore
case. For example, a trip with the start location of Bar Harbor should be included as
should trips whose start location is BAR HARBOR, Bar harbor, BaR HarBor, and so on.
3. List the reservation ID, trip date, and price for all trips. The price should be rounded to the
nearest dollar.
4. Write PUSQL or T-SQL procedures to accomplish the following tasks:
a. Obtain the first name and last name, separated by a space, of the guide whose
number currently is stored in I_GUIDE_NUM. Place these values in the variables
I_FIRST_NAME and I_LAST_NAME. Output the contents of I_GUIDE_NUM,
I_FIRST_NAME, and I_ LAST_NAME.
b. Obtain the number of persons, customer number, and customer last name for every
reservation whose ID currently is stored in I_RESERVATION_ID. Place these values in the
variables I_NUM_PERSONS, I_CUSTOMER_NUM, and I_LAST_NAME, respectively.
Output the contents of I_NUM_PERSONS, I_CUSTOMER_NUM, and I_LAST_NAME.
c. Add a row to the GUIDE table.
d. Change the last name of the guide whose number is stored in I_GUIDE_NUM to the
value currently found in I_LAST_NAME.
e. Delete the guide whose number is stored in I_GUIDE_NUM.
5. Write PUSQL or T-SQL procedures to retrieve and output the reservation ID, trip ID,
number of persons, and trip price for every reservation whose customer number is stored
in I- CUSTOMER- NUM.
6. Write Access functions to accomplish the following tasks:
a. Delete the guide whose number is stored in I_GUIDE_NUM.
b. Change the last name of the guide whose number is stored in I_GUIDE_NUM to the
value currently found in I_GUIDE_LAST.
c. Retrieve and output the reservation ID, trip ID, trip date, number of persons, and trip
price for every reservation whose customer number is stored in I_CUSTOMER_NUM.
7. Write a stored procedure in PUSQL or T-SQL that will change the maximum group size of
a trip with a given trip ID. How would you use this stored procedure to change the maximum group size of trip 21 to 15?
SOL Functions and Procedures
8. Assume the TRIP table contains a column named TOTAL_PERSONS that represents the
total number of persons for that trip. Following the style shown in the text, write the code
in PUSOL or T-SOL for the following triggers:
a. When inserting a row in the RESERVATION table, add the NUM_PERSONS value to
the TOTAL_PERSONS value for the appropriate trip.
C RITICAL
THINKING
b.
When updating a row in the RESERVATION table , add the difference
between the new NUM- PERSONS value and the old NUM- PERSONS value to the
TOTAL_PERSONS value for the appropriate trip.
c.
When deleting a row in the RESERVATION table , subtract the NUM_PERSONS
value from the TOTAL_PERSONS value for the appropriate trip.
9. Because the TRIP table contains several columns with character data, the staff at Colonial Adventure Tours would like to know more about string or character functions. Use the
Internet to research the following string functions: LENGTH, SUBSTR, and INITCAP. Are
these functions the same in Oracle, SOL Server, and Access? Write a paragraph that
discusses what the functions do and any differences and/or similarities between the functions in Oracle, SOL Server, and Access. Then perform the following tasks using Oracle
SOL:
a. Display the first three characters on the left from the TYPE column.
b. Starting at the fourth character from the left, display the next five characters in the
START LOCATION column.
Solmaris Condominium Group
Use the Solmaris Condominium Group database (see Figures 1-9 through 1-13 in Chapter 1)
to complete the following exercises. If directed to do so by your instructor, use the information
provided with the Chapter 3 Exercises to print your output or save it to a file.
1. List the owner number, first name, and last name for all owners. The first name should
appear in uppercase letters and the last name should appear in lowercase letters.
2. List the owner number and last name for all owners located in the city of Bowton. Your
query should ignore case. For example, a customer with the city Bowton should be
included as should customers whose city is BOWTON, BowTon, BoWtOn, and so on.
3. Solmaris is offering a monthly discount for owners who pay their condo fees on a quarterly basis. The discount is 1.75 percent of the monthly fee . For each condo, list the location number, unit number, owner number, owner's last name, condo fee, and discount.
The discount should be rounded to the nearest dollar.
4. Write PUSOL or T-SOL procedures to accomplish the following tasks:
a. Obtain the first name and last name of the owner whose number currently is stored
in I- OWNER- NUM. Place these values in the variables I- FIRST- NAME and
I_LAST_NAME. Output the contents of I_OWNER_NUM, I_FIRST_NAME, and
I- LAST- NAME.
b. Obtain the location number, unit number, owner number, owner first name, and owner
last name for the condo whose condo ID is currently stored in I_CONDO_ID. Place
these values in the variables I_LOCATION_NUM, I_UNIT_NUM, I_OWNER_NUM,
Chapter 8
c.
d.
e.
I_FIRST_NAME, and I_LAST_NAME, respectively. Output the contents of
I_CONDO_ID, I_LOCATION_NUM, I_UNIT_NUM, I_OWNER_NUM, I_FIRST_NAME,
and I- LAST- NAME.
Add a row to the OWNER table.
Change the last name of the owner whose number is stored in I_OWNER_NUM to
the value currently found in I_LAST_NAME.
Delete the owner whose number is stored in I- OWNER- NUM.
5. Write PUSOL or T-SOL procedures to retrieve and output the location number, unit
number, condo fee, and owner number for every condo whose square footage is equal
to the square footage stored in I_SOR_FT.
6. Write Access functions to accomplish the following tasks:
a. Delete the owner whose number is stored in I- OWNER- NUM.
b. Change the last name of the owner whose number is stored in I_OWNER_NUM to
the value currently found in I_LAST_NAME.
c.
Retrieve and output the location number, unit number, condo fee, and owner number
for every condo whose square footage is equal to the square footage stored in
I_SOR_FT.
7. Write a stored procedure in PUSOL or T-SOL that will change the condo fee of a condo
with a given condo ID and location number. How would you use this stored procedure to
change the condo fee for the condo with the condo ID 3 in location 1 to $525?
8. Assume the OWNER table contains a column named TOT AL_FEES that represents the
total monthly condo fee for all condos owned by that owner. Write the code in PL/SOL or
T-SOL for the following triggers following the style shown in the text.
a. When inserting a row in the CONDO_UNIT table, add the condo fee to the total
condo fees for the appropriate owner.
b. When updating a row in the CONDO_UNIT table, add the difference between the
new condo fee and the old condo fee to the total condo fees for the appropriate
owner.
c. When deleting a row in the CONDO_UNIT table , subtract the condo fee from the total
condo fees for the appropriate owner.
C RITICAL
THINKING
9. SOL includes many numerical functions. Two of these functions are FLOOR and CEIL.
Use the Internet to research these functions. Are the functions available in Oracle, SOL
Server, and Access? Write a paragraph that discusses what the functions do and any
differences and/or similarities between the functions in Oracle, SOL Server, and Access.
Then perform the following tasks:
a. Solmaris Condominium Group would like to know the impact of discounting its condo
fees by 3 percent. Write an SOL statement in Oracle that displays the condo ID, unit
number, discounted condo fee, discounted condo fee with the CEIL function, and
discounted condo fee with the FLOOR function .
b. Based on your research, will the values in the three columns vary? If so, how? Use
the condo with the ID of 1 to explain your answer. Be sure to cite your references.
APPENDIX
L REFERENCE
Yo1.1 can 1.1se this appe ndix to obtain de tails co11cerning important compo11e nts and sy11tax
of tl1e SQL lang1.1age. Ite m s are arranged a lpl1abe tically. Each item co11tains a description ,
a refe re n ce to whe re the item is cover ed in the text, and, \\1h en appropriate, both an
example and a description of the q1.1ery res1.1lts. Som e SQL commands a lso incl1.1de a
description of the clauses associated witl1 tl1e m . For eacl1 cla1.1se, the re is a brief
description and an indication of \.Vl1e the r the cla1.1se is req1.1ired or optional.
ALIASES (PAGES 142-145)
You cat1 specify an alias (alte r11ative 11ame) for eacl1 table iI1 a query. Yo1.1 can use tl1e a lias i11
tl1e rest of the comn1and by follo\.vi11g the n ame of the table \.Vitl1 a space and tl1e alias na1ne.
Tl1e follo'v,1ing com111and cr eates an a lias 11ame d R for tl1e REP table a11d an alias
named C for tl1e CUSTOMER table:
SEL E CT R. REP NUM, R. LAST NAME , R. FIRST NAME ,
C . CUSTOMER NUM, C . CUSTOMER NAME
FROM REP R, CUSTOMER C
WHERE R. REP NUM
= C. REP NUM;
ALTER TABLE (PAGES 179-180)
Use the ALTER TABLE command to change a table's str1.1ctt1re. As shown in Fig1.1re A-1 , you type
tl1e ALTER TABLE command, followed by tl1e table name , and then the alteration to perform.
Clause
Description
Required?
ALTER TABLE table 1ianie
Indicates nan1e of table co be altered.
)'es
alteration
JncUcaces t)rpe of alteration to be perfom1ed.
)'es
FIGURE A-1
ALTER TABLE command
Tl1e followi11g comn1and alters tl1e CUSTOMER table by adding a 11e\.\1 CUSTOMER_TYPE
colu11111:
ALTER TABLE CUSTOMER
ADD CUSTOMER TYPE CHAR ( 1) ;
Append ix A
T l1e following comman d changes the CITY col1.1mn in tl1e CUSTOMER table so tl1at it
cannot accept n1.1lls:
ALTER TABLE CUSTOMER
MODIFY CITY NOT NULL;
Note: In Access, yo1.1 1.1sually mal{e these changes to a table in Design vie\.V ratl1er than
using ALTER TABLE.
Note: In SQL Server , yo1.1 m1.1s t 1.1se tl1e ALTER COLUMN c la1.1se and con1ple tely defiI1e
tl1e col1.11nn as follo\\7S:
ALTER TABLE CUSTOMER
ALTER COLUMN CITY CHAR ( 15) NOT NULL
COLUMN OR EXPRESSION LIST (SELECT
CLAUSE) (PAGES 97-99)
To select col1.1mns, 1.1se the SELECT clause follo,,,ed by the list of col1.11nns, separated by commas.
Tl1e follo,,,i11g SELECT c lat1se selects tl1e CUSTONIER_NUM, CUSTOMER_NANIE, and
BALANCE col1.1mns:
SE LECT CUSTOMER NUM, CUSTOMER NAME, BALANCE
Use an asterisk iI1 a SELECT c lat1se to select all colu1TI11s in a table. The follo\\7ing
SE LECT cla1.1se selects all columns:
SE LECT *
Computed Columns (Pages 106-108)
Yo1.1 can 1.1se a comp1.1tatio11 in place of a colunm by typing tl1e compt1tation. For r eadability,
you can type tl1e comp1.1tation in pare ntl1eses, a lthougl1 it is not n ecessary to do so.
Tl1e following SELECT c lause selects tl1e CUSTOMER_~TTJM and CUSTOMER_NAME
col1.11TI11s as well as tl1e res1.1lts of subtracting the BALANCE col1.1nn1 from the CREDIT_ LINIIT
col1.1nn1:
SE LECT CUSTOMER NUM, CUSTOMER NAME , (CREDIT LIMIT - BALANCE)
The DISTINCT Operator (Pages 115-117)
To avoid selecting d1.1plicate valt1es in a comma nd, 1.1se tl1e DISTINCT operator. ~Then you
omit the DISTINCT operator from the comma11d a11d tl1e sa1n e value appears on mt1ltiple
ro\.vs in the table, tl1at valt1e ,vill appear on m1.1ltiple r o,vs in the quer y rest1lts.
Tl1e follo,,,ing qt1ery selects all c us tomer n1.11nber s from tl1e ORDERS table, but lis ts
eacl1 c us tom er 11t11nber only 011ce iI1 tl1e res1.1lts:
SE LECT DI STINCT (CUSTOMER NUM)
FROM ORDERS;
SOL Reference
Functions (Pages 112-117)
Yott can use fttnctions in a SELECT clattse. Tl1e m ost co1nmonly ttsed fttnc tio11s a re AVG
(to calctilate an aver age), COUNT (to cot1nt the nu1nbe r of ro\.vs), MAX (to de termine tl1e
m aximttm valtte), NIIN (to de termi11e the minimttm valtte), and SU11 (to calcttla te a to tal).
Tl1e follo\.ving SELECT clattse calcttla tes tl1e average balance:
S ELE CT AVG (BALANCE )
COMMIT (PAGE 173)
Use tl1e C011Il\1IT co1nmand to m ake perma11ent any updates made sit1ce the las t command. If no previotts CONIMIT conuna11d has been execttted , tl1e CONTh1.IT comma nd will
malre all tl1e upda tes dttrit1g the cttrrent \.\7ork session permanent itn1nediately. All ttpdates
becom e permanent atttom a tically \.\7l1en you exit SQL. Figttre A-2 describes tl1e CONIMIT
conunand.
Clause
Description
Required?
CO?v!Ml 1'
Indicates that a CO~,ftvflT is to be pe1fon11ed.
Yes
FIGURE A-2
COMMIT command
Tl1e follo,,1i11g command malres all ttpdates s it1ce tl1e 1nost recent COMMIT command
penna nent:
COMMI T;
Note: In SQL Server, the follo,ving co1nma11d m alres all ttpdates since the most rece11t
COMNIIT command:
COMMI T T RANSACT I ON
Note: Access d oes no t sttpport tl1e COM11.IT co1nmand.
CONDITIONS (PAGES 100-105)
A co11ditio11 is an expression tl1at cat1 be evaltta ted as either trtte or false. Vl l1en yott ttse
a condition i11 a \\THERE clause, tl1e results of tl1e que ry contai11 those rov.rs fo r \.Vl1icl1 tl1e
condition is trtie. Yott can create simple conditions a11d compound co11ditions using tl1e
BET\\TEEN, LII(E, IN, EXISTS, ALL, and ANY operators, as described in tl1e followi11g sectio11s.
Simple Conditions (Pages 100-102)
A simple conditio11 has tl1e fo r111 column na1ne, compariso11 operator , a11d tl1en eitl1er
anotl1er colu1n11 na1ne o r a value. The available compariso11 operato rs are = (equal to), <
(less than), > (greater than), <= (less tl1a11 o r eqttal to), >= (greater tl1an or eqttal to),
and < > (not equal to).
Appendix A
Tl1e follo\.ving \\THERE cla11se 11ses a condition to select ro\.vs \.Vher e tl1e balance is
grea te r tl1an the cr edit limit:
WHERE BALANCE > CREDIT LIMIT
Compound Conditions (Pages 102-105)
Compo11nd conditions are formed by connecting t\.\70 or more si111ple conditions 11sing tl1e
AND, OR, and NOT ope rato rs. \i\Tl1en s imple conditions are connected by tl1e AND oper ator, all of tl1e simple conditions m11st be tr11e in order for tl1e compo11nd conditio11 to be
tr11e. \\Tl1en simple conditions are connected by the OR oper ator, the compo11nd condition
will be tr11e \.vl1enever a11y one of tl1e simple conditions is tr11e. Preceding a condition by
tl1e NOT oper ator r everses tl1e tr11tl1 of tl1e o riginal condition.
'fl1e follo\.ving \\THERE cla11se is tr11e if the storel1011se n11mbe r is eq11al to 3 or the
11nits on ha nd is gr eater tl1an 25, or botl1:
WHERE (STOREHOUSE =
1
3 1 ) OR (ON HAND > 25)
Tl1e following WHERE cla11se is tr11e if tl1e stor el1011se n11mber is eq11al to 3 ancl tl1e
11nits on h and is gr eater tl1an 25:
WHERE (STOREHOUSE =
1
3 1 ) AND ( ON HAND > 25)
'f l1e followi11g \\THERE cla11se is tr11e if the storel1011se n11mbe r is not eq11al to 3:
WHERE NOT (STOREHOUSE =
1
31)
BETWEEN Conditions (Pages 105-106)
Y011 can 11se the BETVl EEN operator to de termi11e if a val11e is \.\7itl1in a range of values.
Tl1e following \VHERE cla11se is tr11e if the balance is bet\.veen 2,000 and 5,000:
WHERE BALANCE BETWEEN 2000 AND 5000
LIKE Conditions (Pages 108-109)
LII<E conditio11s use \.\7ildcards to select ro\.vs. Use tl1e per cent (%) \.\7ildcard to represent
any collection of characters. The condition LIKE '%Central%' will be tr11e for data consisti11g of any character or cl1a rac ters, followed by the le tters "Central," follo\.\7ed by any
otl1er cl1arac ter o r ch aracters. Anotl1er \.vildcard symbol is tl1e underscore (_), \.vl1icl1
represents any it1divid11al ch aracter . For example , "T_m" represents tl1e letter "T,"
followed by an y single cl1aracte r, follo\.\7ed by tl1e le tte r "m," and \.\7011ld be tr11e for a
collection of cl1arac ters s11cl1 as Tim, Tom , or T3m .
'f l1e following \\THERE cla11se is tr11e if the val11e in the S'f REET col11mn is Col11mb11s,
Col111nbusia, or any other val11e tl1a t contains "Columb11s":
WHERE STREET L IKE 1 %Columbus% 1
Note: Access uses diffe rent wildca rd syn1bols. The symbol fo r a11y collecti on of cl1ar-
acters is tl1e asterisl{ (*). Tl1e symbol for an individual ch aracter is tl1e q11estio11 1narl{ (?).
SOL Reference
IN Conditions (Pages 110, 138)
You can use IN to de termi11e whe tl1er a valt1e is i11 son1e specific collection of valt1es.
Tl1e follo\.ving vVHERE clat1se is trt1e if tl1e credit lin1it is 5 ,000 , 10,000, or 15,000:
WHERE CREDIT LIMI T I N (5000, 10000, 1 5 000)
Tl1e follo\.vi11g \\THERE clat1se is trt1e if the item nt1mber is in tl1e collection of item
nt1mbers associated with order 11t1mbe r 51623:
WHERE ITEM NUM IN
( SE L E CT ITEM NUM
FROM ORDER LI NE
WHERE ORDER NUM
= 5 1623
1
1
)
EXISTS Conditions (Pages 138-140)
Yot1 can t1se EXIS'f S to de termine \.Vl1e the r the rest1lts of a st1bqt1e ry contain a t least on e
row. The follo\.ving \\THERE clat1se is trt1e if the resttlts of the st1bqt1e ry contain at least
one ro\v, that is, there is at least one orde r line \.Vitl1 tl1e desired order nt1mber and on
which the item number is FDll :
WHERE EX I STS
(SELE CT *
FROM ORDER LI NE
WHERE ORDERS. ORDER NUM
AND ITEM NUM
= ORDER L INE. ORDER NUM
= 1 FD11 1 )
ALL and ANY (Pages 154-156)
Yot1 can t1se ALL or ANY \.Vitl1 st1bqt1eries. If yot1 precede the st1bquery by ALL, tl1e
condition is tn1e only if it is satisfied fo r all valt1es produced by the st1bquery. If yot1
precede the st1bqt1ery by ANY, the conditio11 is true if it is satisfied for any value ( one or
more) produced by the st1bqt1e ry.
Tl1e following vVHERE clat1se is trt1e if tl1e balance is greater than every balance
contained in tl1e rest1lts of tl1e st1bqt1ery:
WHERE BALANCE > ALL
( SE LE CT BALANCE
FROM CUSTOMER
WHERE REP NUM
= 30
1
1
)
Tl1e follo\.ving \\THERE clat1se is trt1e if tl1e bala nce is greater tl1an at le ast one balance
contained in the resttlts of the st1bqt1ery:
WHERE BALANCE > ANY
(SE L E CT BALANCE
FROM CUSTOMER
WHERE REP NUM
= 30
1
1
)
Appendix A
CREATE INDEX (PAGES 210-211)
Use tl1e CREATE 11\TDEX com1nand to create an index for a table. Figure A-3 describes tl1e
CREATE INDEX command.
Clause
Description
Required?
CREA'l'E INDEX index nanie
Inilicates the na111e of the index.
Yes
ON table na,ne
Indicates the table for ,vhich the index is to be created.
Yes
colunin list
Indicates the colu11111 or colun111s on ,vhich the index is to be based.
Yes
FIGURE A-3
CREATE INDEX command
Tl1e follo\.vi11g CREATE INDEX co1n111a11d creates a11 i11dex 11a1ned REP_NAME for tl1e
REP table 011 tl1e combi11ati o11 of tl1e LAST- NA.NIE a11d FIRST- NA.NIE colt11ru1s:
CREATE INDEX REP NAME ON REP (LAST NAME, FIRST NAME) ;
CREATE TABLE (PAGES 65-68)
Use tl1e CREATE TABLE command to define tl1e strt1ctt1re of a ne"'' table. Figtire A-4
describes the CREATE TABLE command.
Clause
Description
Required?
CRE1\TE D\.BLE table na·m e
Indicates the na1ne of the table to be created.
Yes
(colu,,nn and data t_y pe list)
Indicates the columns that comprise the table along ,vith
their correspon ding data ~1Jes (sec Data 1'ypcs section).
Yes
FIGURE A-4
CREATE TABLE command
Tl1e following CREATE TABLE co1nmand creates tl1e REP table and its associated
colt1mns and data types. REP_l\11.JNI is the table's primary Irey.
CREATE TABLE REP
(REP NUM CHAR (2) PRIMARY KEY,
LAST NAME CHAR ( 1 5) ,
FIRST NAME CHAR ( 1 5) ,
STREET CHAR ( 1 5) ,
CITY CHAR ( 1 5) ,
STATE CHAR(2),
POS TAL CODE CHAR ( 5) ,
COMMISSIONDE CIMAL(7,2),
RATE DEC IMAL ( 3 , 2) ) ;
SOL Reference
Note: Access does not sttpport tl1e DECIMAL data type. Use tl1e CURRENCY
da ta type for fie lds tl1at will co11tain ct1rrency val11es; use tl1e NUMBER da ta type
for all other n11me ric fields. In 1\ ccess, use tl1e following command to crea te the
REP table:
CREATE TABL E REP
(REP NUM CHAR (2) PRIMARY KE Y,
LAST NAME CHAR ( 1 5 ) ,
FIR ST NAME CHAR (l5),
STREE T CHAR ( 1 5 ) ,
CITY CHAR ( 1 5 ) ,
STATE CHAR (2),
POSTAL CODE CHAR ( 5 ),
COMMI SS I ON CURRENCY,
RAT E NUMBER ) ;
CREATE VIEW (PAGES 191-193)
Use tl1e CREATE \TIE\V command to create a view. Fig11re A-5 describes tl1e CREATE
\TIE\:\T comn1and.
Clause
Description
Required?
CRE1\TE \ TTE\V vic•w ·n ame ,~S
Indicates the name of the vie\v to be c reated .
Yes
query
[ndicates the defining query for t he vie,v.
Yes
-- "
FIGURE A-5
CREATE VIEW command
Tl1e follo\.ving CREATE \TIE\:\T co1nmand c reates a vie"'' named TOYS, \\'l1ich consists
of tl1e item nt1mber, item description , u11its 011 l1and, a11d u11it price for all rows in tl1e
ITEM table on wl1icl1 tl1e category is TOY:
CREATE V IEW TOYS A S
SEL E CT I TEM NUM, DESCRIPT I ON, ON HAND, PRI CE
FROM I TE M
WHERE CATEGORY
= TOY' ;
1
Append ix A
DATA TYPES (PAGE 70)
Figt.1re A-6 describes tl1e data types that yot1 can t1se in a CREATE TABLE command.
Data Type
Description
CTI1\R(11,)
Stores a characrer string 11 cha.racrcrs long, You use the CTI1\R data type for columns that
contain letters and special characters and for columns containing nurnbers that ,viii not
be used in any calculations. Because neither sales rep nu1nbers nor customer numbers
,vill be used in any calculations, for example, the REP _Nl.Th1 and CUSTOtvIER_NU}.,f
columns are both assigned the CllAll data type,
,
\f1\llC Lli\K(n)
1\u alternative to CI ll\R that stores a character string up to n characters long. Uulli,e
Clli\ll, only the actual character string is stored. If a character string 20 characters long
is stored in a CT-TAR(JO) column, for exa1nple, it ,viii occupy 30 characters (20 characters
plus 10 blank spaces). If it is stored in a VARCI-I.AR(30) column, it ,viii only occupy
20 spaces. In general, tables that use \TARCII.AR instead of Clli\R occupy less space, but the
D81JS does not process then1 as rapidly clurLug queries and updates. llo,vever, both are
legitimate choices. This text uses Clll\1{, but V1\RCII1\R ,vould ,vork equally ,vcll.
'
DATE
Stores date data. The specific format in ,vhich daces ru·e scored vru·ies frorn one SQL
irnplementation to another. In Oracle, dates are enclosed in single quotation marks and
have the forn1at DD-110N-YYYY (for example, '23-0C1'-2015' is October 23, 2015). In
1\ccess, dates are enclosed in number signs and are entered using the forn1at
J\,flvl/DD/YYYY (for cxru.nplc, #10/23/2015# is October 2J, 2015).
DECIJ\IAL(p,q)
Stores a decilnal nu1nber p digits long \\'ith q of these digits being decimal places to the
right of the dccin1al point. For cxan1plc, the data type DECThf1\L(S,2) represents a 11un1bcr
,vith three places to the left and t,vo places to the ri~ht of the decin1al (for exan1ple,
100.00). Yoi.i can use the co11tents of DECIMl\L colum11s in calculations. You also can i.ise
the ~'1BER(p,q) data type in botb Oracle and SQL Server to store a decimal nu1nber.
r\ccess does not support the DECThlAL data type; use the CURRENCY or NU~'113ER data
type instead.
INT
Stores integers, ,vhich are numbers ,vithout a decimal part. The valid range is
- 2147483648 to 2147483647. You can use the contents of fNl' columns in calculations.
lf you follo,v t11c ,vord IN'f \Vith 1\U'fO_JNClIBMENT, you create a colt.unn for ,vhich
SQL ,viii automatically generate a ne,v sequence number each time you add a nc,v
ro,v. 'rhis ,vould be the appropriate choice, for· exa1nple, ,vhen you ,vant the OBf\1S to
generate a value for a primary key.
SJ\,li\LLINT
Stores integers, but uses less space than the INT data type. 'fhe valid range is -32768 to
3276 7. SNlt\LLh\T'l' is a better choice than INT ,vhcn you arc certain that the colu1ru1 ,vill
store numbers ,vi.thin the indicated range, You can use the contents of S1-lALLIJ\TT
colun111s in calcuJations.
FIGURE A-6
Data types
SOL Reference
DELETE ROWS (PAGES 77, 174-176)
Use tl1e DELETE comma nd to dele te one or 1nore rows fro1n a table . Fig11re A-7 describes
tl1e DELETE command .
Clause
Description
Required?
DELETE table na1ne
Indicates the table fro111 ,vhich the ro,v or ro,vs
arc to be deleted.
Yes
\VllERE conditio11
Indicates a condition. Those ro,vs for ,vhich the
condition is true \vill be retrieved and deleted.
No (If you otuit the \VllERE
clause, all ro,vs ,vill be deleted.)
FIGURE A-7
DELETE command
Tl1e follo\.ving DELETE command dele tes any r o\.\' from tl1e LEVELl_CUST OMER
ta ble on wl1icl1 tl1e c11stom e r nu1nbe r is 893:
DEL ET E L EVELl CUSTOMER
WHERE CUSTOMER NUM
= 89 3
1
1
;
DESCRIBE (PAGES 86-87)
111 Or acle, yo11 can 11se the DESCRIBE com1n and to lis t all tl1e colu mns in a table and
tl1eir prop erties. Tl1e following comma nd d escribes the REP ta ble:
DE S CR I BE REP ;
Note: In Access, 11se the Doct1menter to describe the ta bles and otl1er objects i11 a
da ta base .
Note: In SQL Server , execute th e sp_colum11s command to lis t all the colum11s in a
ta ble . The follo\.ving command will list all the columns iI1 the REP ta ble:
Exec s p _ c o l umns REP
DROP INDEX (PAGES 203-204)
Use tl1e DROP INDEX co1runand to dele te a11 index, as sl10\.\7n in Figt1r e A-8.
Clause
Description
Required?
DROP lNl)EX inclex na1ne
lndicates the name of the index to be dropped.
Yes
FIGURE A-8
DROP INDEX command
Tl1e follo\.vi11g DROP INDEX co111ma11d deletes the i11dex 11ai11ed CRED_NA.NIE:
DROP INDEX CRED NAME ;
Append ix A
Note: In SQL Server, yott mt1st q11alify the index name as follows:
DROP INDEX CUSTOMER. CRED NAME
DROP TABLE (PAGES 89, 185-186)
Use tl1e DROP TABLE co111111and to dele te a table, as shown in Figure A-9.
Clause
Description
Required?
DR()P T,\BLE table 1ia1ne
Indicates name of the cable to be dropped.
Yes
FIGURE A-9
DROP TABLE command
Tl1e follo\.ving DROP TABLE con1mand dele tes the table natned LEVELl_CUSTOMER:
DROP TABLE L EVELl CUSTOMER;
DROP VIEW (PAGES 203-204)
Use the DROP VIEW command to dele te a view, as sl1own in Fig11re A-10.
Clause
Description
Required?
DROP VJE\V view nanie
Indicates U1e n~u11e of the vie\v to be dropped.
Yes
FIGURE A-10
DROP VIEW command
Tl1e follo\.\7ing DROP VIE\\T command dele tes tl1e vie\.v named TYS:
DROP VIEW TYS;
GRANT (PAGES 204-207)
Use tl1e GRANT com111and to gra11t privileges to a 11ser. Fig11re A-11 describes the GRANT
command .
Clause
Description
Required?
G R.i.\NT privilege
Indicates the type of privilegc(s) to be granted.
Yes
ON database object
Indicates the database object(s) to ,vhich the privilcge(s) pertain .
Yes
TO user name
Indicates the user(s) to ,vhom the priviJege(s) arc to be granted.
1'o grant the privilege(s) to alJ users, use the TO PUBLIC clause.
Yes
I
FIGURE A-11
GRANT command
SOL Reference
Tl1e follovvi11g GRAN'f command grants tl1e t1ser named Jol1nso11 tl1e privilege of
selecting rovvs from tl1e REP table:
GRANT SE LE CT
ON REP
TO Johnson;
INSERT INTO (QUERY) (PAGES 167-169)
Use tl1e INSERT INTO comma11d vvitl1 a qt1ery to insert the rows re trieved by a query
into a table. As shown it1 Figt1re A-1 2, you must indicate tl1e name of the table into
which tl1e ro\.\7(s) vvill be inserted and the query vvl1ose rest1lts will be inserted into tl1e
11amed table.
Clause
Description
Required?
INSEI~T INTO cable 1wnie
Indicates the name of che table into ,vhich the ro,v(s) ,viii be inserted .
Yes
query
Indicates the query ,vhose results ,viii be inserted into the table.
Yes
FIGURE A-12
I
INSERT INTO (query) command
Tl1e follovvi11g INSERT INTO command inserts rows selected by a qt1ery into tl1e
LE\TELl CUSTOMER table:
INSERT INTO LEVELl CUSTOMER
S ELE CT CUSTOMER NUM, CUSTOMER NAME, BALANCE,
CRE DIT LIMIT, REP NUM
FROM CUSTOMER
WHERE CREDIT LIMIT = 7500;
INSERT INTO (VALUES) (PAGES 72-74)
Use tl1e INSERT INTO command a11d tl1e VALUES clat1se to insert a row into a table by
specifying the valt1es for eacl1 of tl1e colt1mns. As shown in Figure A-13, you mt1st indicate tl1e table into \.\7l1ich to it1sert the valt1es, a11d the11 list the values to i11sert in
parentl1eses.
Clause
Description
Required?
INSERT INTO cable na n1e
Indicates the n arnc of the table into ,vhich the ro,v ,vill be inserted.
Yes
\ '1\LUES ('values list)
Indicates the values for each of the colurnns on the nc,v row.
Yes
FIGURE A-13
INSERT INTO (values) command
I
Appendix A
Tl1e following INSER'f INTO command inserts tl1e valttes shown in parentheses as a
ne\.\1 row i11 tl1e REP table:
INSERT INTO REP
VALUES
(
1
15 1 , 1 Campos 1 , 1Rafael 1 , 1 724 Vin ca Dr. ' , 1 Grove 1 , 1 CA' , '9OO92 1 , 2 34 57 . 5 O, O . O6) ;
INTEGRITY (PAGES 215-218)
You can use the ALTER TABLE command with a11 appropriate ADD CHECI(, ADD
PRIMARY IIBY, or ADD FOREIGN IIBY clattse to specify integrity. Figure A-14 describes
tl1e ALTER TABLE co1nmand for specifying integrity.
Clause
Description
Required?
ALTER TABLE table ·na1rie
Indicates the table for \vhich Integrity is being specined .
Yes
integrity clause
1\DD CIIECI(, 1\DD Plill11\l~Y IIBY, or .ADD FOREIGN KEY
Yes
FIGURE A-14
Integrity options
'fl1e follovving ALTER 'f ABLE command cl1anges tl1e ITEM table so that tl1e only legal
valttes for the CATEGORY colttmn are GME, PZL, and TOY:
ALTER TABLE ITEM
ADD CHECK (CATEGORY IN ( 1GME 1 , 1 PZL 1 , 1TOY 1 )
) ;
'fl1e follovving ALTER 'f ABLE command cl1anges tl1e REP table so that the REP_NUM
colttmn is tl1e table's primary l{ey:
ALTER TABLE REP
ADD PRIMARY KEY (REP NUM) ;
'fl1e follovving ALTER 'f ABLE command cl1anges tl1e CUST OMER table so tl1at the
REP_NUM colttmn in the CUSTOMER table is a for eign l{ey r eferencing the prima ry l{ey of
tl1e REP table:
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (REP NUM) REFERENCE S REP;
SOL Reference
REVOKE (PAGES 204-207)
Use tl1e REVOI(E com1nand to r evolre privileges from a 1.1ser . Figure A-15 describes tl1e
REVO I(E command.
Clause
Description
Required?
RE\TOKE privilege
Indicates the type of privilege(s) to be revoked.
Yes
ON dacabasc obj ect
Indicates the database object(s) to ,vhic h the pri vilege pertains.
Yes
FROM user name
Indicates the user 11an1e(s) fron, ,vhon1 the pri vilege(s) are to be revoked.
Yes
FIGURE A-15
REVOKE command
Tl1e follo\v ing REVO I(E command revolres tl1e SELECT privilege for the REP table
from tl1e 1.1ser named Jol1nso11:
REVOKE S ELE CT
ON REP
FROM J o hnson ;
ROLLBACK (PAGES 173-174)
Use tl1e ROLLBACI( co1111nand to rever se (undo) all updates si11ce tl1e execution of tl1e
previous CONilvllT con1ma11d. If 110 COMNIIT co1nmand l1as bee11 executed , the co1n111and
will undo all c l1anges made durit1g tl1e curre11t vvork. sessio11. Figure A-16 describes tl1e
ROLLBACI( co111ma11d.
Clause
Description
Required?
ROLLB1\CJ{
Indicates that a rolJ back is to be per formed.
Yes
FIGURE A-16
ROLLBACK command
Tl1e following co1runa nd rever ses all 1.1pdates 1nade since tl1e time of tl1e last COMMIT
connnand:
ROLLBACK;
Note: In SQL Server , the follo\.\7i11g co1TI1Tiand r everses all t1pdates made si11ce tl1e time
of tl1e last COMMIT comn1and:
ROLLBACK TRANSA CT I ON
Note: Access does no t s1.1ppo rt tl1e RO LLBACI( command.
Appendix A
SELECT (PAGES 74-76, 97-124)
Use tl1e SELECT con1mand to re trieve data from a table or fron1 multiple tables.
Fig11re A-17 describes tl1e SELECT com1nand.
Clause
Description
Required?
SELECT coliunn or e:cpressio1i list
Indicates the colu1nn(s) and/or expression(s)
to be retrieved.
Yes
FROl\l table list
lndicates the table(s) required for the query.
Yes
\VlTERE conclition
Indicates one or more conditions. Only the
ro,vs for \Vhich the condition(s) are true will
be retrieved.
No (If you omit the
\\TlIERE clause, all
ro\vs will be retrieved.)
GROUP BY column list
Indicates colu1nn(s) on ,vhich ro,vs are to be
grouped.
No (If you om it the
GROUP BY clause, no
grouping ,vill occur.)
£I1\\TJNG conf1ition in;volving grotips
Indicates a condition for groups. Only groups
for ,vhich the condition is true ,viii be
included in query results. Use the IIA\TING
clause only if tbe query output is grouped.
No (If you 0111it the
I
HA\'ING clause, all
groups \vill be included.)
I
I
ORDER B't' column or e.-cpression l-isc
FIGURE A-17
Indicates colun,n(s) on ,vhich the query
output is to be sorted.
No (ff you omit the
ORDER BY clause, no
sorting ,vill occur.)
SELECT command
'f l1e follovvi11g SELECT command joins tl1e ORDERS and ORDER_LINE tables. 'fhe
command selects the c11stomer n11mbe r, order n11mber, order date, and tl1e s11m of tl1e
prod11ct of tl1e n11mbe r ordered and 11nit price, renamed as ORDER_'fO'f AL. Records a re
grouped by order number, c11stomer n11mber , and date. Only grot1ps on which the order
total is greate r tl1an 500 are incl11ded . Gro11ps are ordered by order n11mber .
S ELE CT CUSTOMER NUM, ORDERS . ORDER NUM, ORDER DATE ,
SUM (NUM ORDERED * QUOTED PRI CE ) AS ORDER TOTAL
F ROM ORDERS, ORDER L INE
WHERE ORDERS. ORDER NUM
= ORDER L INE. ORDER NUM
GROUP BY ORDERS . ORDER NUM, CUSTOMER NUM, ORDER DAT E
HAVING SUM(NUM ORDERED * QUOTED PRI CE )
> 5 00
ORDER BY ORDERS . ORDER NUM;
SUBQUERIES (PAGES 117-120, 140-141)
You can use 011e query \.Vitl1in anotl1er . The iru1er query is called a s11bq11ery a11d it is
eval11ated first. Tl1e 011ter query is evaluated next, prod11cing tl1e item description for eacl1
item whose item n11n1ber is in tl1e list.
SOL Reference
Tl1e following command contains a s11bq11ery tl1a t prod11ces a list of item n11mbers
incl11ded i11 order n11mber 51623:
SE LE CT DESCRIPT I ON
FROM I TEM
WHERE ITEM NUM I N
(SE LE CT I T EM NUM
FROM ORDER LI NE
WHERE ORDER NUM
= 5 1623
1
1
);
UNION, INTERSECT, AND MINUS
(PAGES 150-154)
Connecti11g two SELECT co1nmands \Vitl1 tl1e UNION operator prod11ces all the ro\VS tl1at
would be iI1 the results of tl1e first query, tl1e second q11ery, o r botl1 que ries. Co1mecting
t\VO SELECT commands \\7itl1 tl1e INTERSECT operator produces a ll tl1e r o\vs that wo11ld
be in tl1e res11lts of bo th q11e1ies. Connecting two SELECT commands \Vitl1 tl1e MINUS
operato r produces all tl1e rows tha t \\7ould be i11 tl1e results of the first q11e ry, b11t riot in
tl1e results of tl1e second query. Figure A-18 describes tl1e UNION, INTERSECT, a11d
MINUS operators.
Operator
Description
UNION
Produces all the ro,vs that \VouJd be in the results of the fust query, tbe second query,
or both queries.
INTERSEC'f
Produces all the ro,vs that \vould be in the results of both queries.
1'lli\TUS
Produces all the ro,vs that \vould be in the results of the fust query but not in the
results of the second query.
FIGURE A-18
UNION, INTERSECT, and MINUS operators
'
1Vote: Access and SQL Server s11ppo rt the UNION operation . SQL Server s11pports tl1e
INTERSECT com111a11d \\7llile Access does 11ot. Neither SQL Ser ver n or Microsoft Access
s11pport tl1e 11IINUS operator .
Tl1e follovvi11g q11e ry displays the customer ntimber ru1d c11s tom er name of all
customers that are represe11ted by sales rep 15 , or tl1at have orde rs, or bo tl1:
SEL E CT CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER
WHERE REP NUM
= 15
1
1
UNI ON
SEL E CT CUSTOMER. CUSTOMER NUM , CUSTOMER NAME
FROM CUSTOMER , ORDERS
WHERE CUSTOMER. CUSTOMER NUM
= ORDERS . CUSTOMER NUM ;
Append ix A
Tl1e following qt1ery displays the ct1stom e r nt1mber and customer name of all
ct1stomers tl1at are represented by sales re p 15 and tl1at have orders:
SELECT CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER
WHERE REP NUM
= 15
1
1
INTERSECT
SEL E CT CUSTOMER . CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER, ORDERS
WHERE CUSTOMER . CUSTOMER NUM
= ORDERS . CUSTOMER NUM;
Tl1e following qttery displays tl1e ct1stomer nt1n1ber and ct1stomer name of all
ct1stomers tl1at are r epresented by sales re p 15 but tl1at do 11,ot have orders:
SEL E CT CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER
WHERE REP NUM
= 15
1
1
MINUS
SEL E CT CUSTOMER . CUSTOMER NUM, CUSTOMER NAME
FROM CUSTOMER , ORDERS
WHERE CUSTOMER . CUSTOMER NUM
= ORDERS. CUSTOMER NUM;
UPDATE (PAGES 76-78 , 169-171)
Use tl1e UPDATE com111and to cha11ge tl1e contents of 011e or more rows in a table.
Figt1re A-19 describes tl1e UPDATE comma11d.
Clause
Description
Required?
UPDA1'E table 1ia1ne
Indicates the table \Vhose contents ,viii be changed.
Yes
SE1' cohonn = expres1,ion
Indicates the column to be ch anged, along ,vith an
ex7Jressio11 th at provides the n e,v value .
Yes
\VllERE co1iclicion,
Indicates a cond ition. 1' he change ,viii occur only
on those ro,vs for ,vhich th e condi tion is true.
No (Lf you om.it the WlfERE
I
FIGURE A-19
clause, all ro,vs ,viii be updated.)
UPDATE command
Tl1e follo\vi11g UPD;\ TE com1na11d cl1a11ges tl1e custo1ner 11a1ne 011 tl1e ro"'' in
LEVELl_CUSTOMER 011 \vl1icl1 tl1e custon1er nt1111ber is 796 to U11ique Gifts a11d Toys:
UPDATE LEVELl CUSTOMER
SET CUSTOMER_NAME
= Unique Gifts and Toys '
1
WHERE CUSTOMER NUM =
1
796
1
;
APPENDIX
•
•
HOW DO I REFERENCE
Tl1is appendix answers freq11ently aslled q11estions abot1t h ow to accomplish a varie ty of
ta.slls 11sin g SQL. Use tl1e seco11d col11mn to locate the correct section in AppendL~ A tl1at
ans\>vers yo11r q11estion .
Append ix B
How Do I
Review the Named Section(s) in Appendix A
Add colum11s to an existing table?
Al,TER Tl\_BLE
;\dd ro,vs?
INSERT lNTO (\Talues)
Calculate a statistic (stun, average,
maxin1un1, 1ninimun1, or count)?
1. SELECT
2. Colu1nn or ltxpression List (SEJ,ECT Clause)
(Use the approp1;ate function in the query.)
Change ro,vs?
UPD,\TE
Create a data type for a column?
l. Data Types
2. CRE1\TE TABLE
Create a table?
CREATE T1\_BLE
Create a vie,v?
CREATE VJE\,r
Create an index?
CREATE TNDEX
Describe a table's layout?
DESCRIBE
Delete a table?
DROP 'fABLE
Delete a vie\v?
DROPVJE\V
Delete an index?
DROP !Nl)EX
Delete ro,vs?
DELE'l'E Ro,vs
Drop a table?
DROP 'fABLE
Drop a vie,v?
DROPVJE\V
Drop an index?
DROP INDr:x
Grant a privilege?
GR.ANT
Group data in a query?
SELEC'f
(Use a GROlJP BY clause.)
Insert ro,vs?
INSER1' IN'l'O (Values)
Insert ro,vs using a query?
INSER'f INTO (Query)
Join tables?
Conditions
(lnclude a \VliERE clause to relate the tables.)
!\lake updates permanent?
COl\~ITT
Order query results?
SELECT
(Use the ORDER BY clause.)
Prohibit nulls?
1. CR.EA'l'E TABLE
2. 1\LTER T,\BLE
(Include the NOT NULl, clause in a
CRE.1\TE T1\BLE or .1-\LTER T1\BLE comn1aud.)
Ren1ove a priviJege?
REVOJ<E
Ren1ove ro,vs?
DEI,ETE Ro,vs
Retrieve all columns?
l. SEI,EC1'
2. Colunu1 or Expression List (SELEC1' Clause)
(l'ype ''in the SELEC'l' clause.)
FIGURE B-1
How Do I reference
How Do I Reference
How Do I
Review the Named Section(s) in Appendix A
Retrieve all ro\vs?
SELECT
(Omit the \\llJERE clause.)
Retrieve only certain colu11111s?
1. SELEC'l'
2. Column or Expression List (SELECT Clause)
(Type the list of columns in the SELECT clause.)
Revoke a privilege?
REVOT<E
Select all colwnns?
1. SELECT
2. Colu1nn or Expression List (SELECT Clause)
(Type ''in the SELECT clause.)
Select all ro,vs?
SELEC'f
(Omit the \VHERE clause.)
Select only certain columns?
1. SELECT
2. Colu1nn or Expression List (SELECT Clause)
(Type the list of colua1ns in the SELECT clause.)
Select only certain ro,vs?
l. SELEC'l'
2. Conditions
(Use a \VllERE clause.)
Sort query results?
SELEC'f
(lJsc an ORDER BY clause.)
Specify a foreign key?
Integrity
(Use the 1\DD FOREIGN I<EY clause in a11 1\LTER D\BLE command.)
Specify a prin1ary key?
Integrity
(Use the ADD PRJ}.-IARY Jill)' clause in an ALTER TABLE co1nmand.)
I
'
I
Specify a privilege?
GRANT
Specify integrity?
Integrity
(Use an 1\DD CfJE(~l<, ADD PRTh11\RY l<.EY, ancVor t\DD FOREfGN l<EY
clause in an 1\LTER T1\BLE cornrnand.)
Specify legal values?
Integrity
(Use an ADD CJJECJ( clause in an 1\LTER TABIJE con1mand.)
Undo updates?
IlOLLBACI<
Update ro\vs?
UPDA1' E
Use a calculated field?
1. SELEC'l'
2. Column or Expression List (SELECT Clause)
(Enter a calculation in the query.)
Use a compound coudition?
1. SELECT
2. Conditions
(Use sin1ple conditions connected by 1\.i\1D, OR, or NOT in a WIIERE clause.)
Use a con1pound condition
in a query?
Conditions
FIGURE B-1
How Do I reference (continued)
I
Append ix B
How Do I
Review the Named Section(s) in Appendix A
Use a condition in a query?
1. SELECT
2. Conditions
(Use a WIIERE clause.)
Use a subquery?
Subquedes
Use a \vildcard?
1. SELEC'l'
2. Conditions
(Use T_,IT(E and a ~vildcard in a WHERE clause.)
Use an alias?
Aliases
(Enter an alias after the name of each table in the FR011 clause.)
Use set operations (union,
intersection, difference) ?
FIGURE B-1
I
UNION, fN'I'ERSECT, and lvIINUS
(Connect t,vo SELEC1' commands ,vith UNION, IN'l'ERSECT, or 1,IINlJS.)
How Do I reference (continued)
APPENDIX
ANSWERS TO
ODD-NUMBERED
REVIEW UESTIONS
CHAPTER 1-INTRODUCTION TOTAL
DISTRIBUTORS, COLONIAL ADVENTURE
TOURS, AND SOLMARIS CONDOMINIUM
GROUP
Dt1e to the 11att1re of tl1e mate rial in Chapter 1, there are no Review Qi1estio11s.
CHAPTER 2-DATABASE DESIGN
FUNDAMENTALS
1.
An entity is a person , place, thing, or event.
3.
A rela tio11sl1ip is an association be tween tables (entities). A one-to-many
relationsllip be tween two tables is a rela tionsllip in whicl1 each row i11 tl1e
first table can be associated with many rows in the second table, but each
ro\, , in tl1e second table is associated \Vith 011ly one row i11 tl1e first table.
5. A relation is a two-dimension al ta.ble in which the entries in tl1e table are
single-valt1ed (eacl1 location in the table contains a single entry), eacl1 colt1mn has a distinc t name (or attribttte 11ame), all valttes it1 a colt1mn ma tcl1
tl1is name, tl1e orde r of tl1e ro\vs and colt1mns is immate1ial, and eacl1 ro\v
contains t1niqt1e valt1es.
7. For each table, you \Vrite tl1e name of tl1e table a11d the11 withi11 pa rentl1eses
list all of tl1e colu11111s in the table. U11derline tl1e primary keys.
GUI DE (GUIDE NUM, LAST- NAME , FIRST- NAME, ADDRE SS, CI TY, STATE,
POSTAL- CODE, PHONE- NUM, HI RE- DATE)
TRIP (TRI P ID, TRI P- NAME , START- LOCATI ON, STATE , DISTANCE,
MAX- GRP- SI ZE , TYPE , SEASON)
Append ix C
CUSTOMER (CUSTOMER NUM, LAST NAME , FIRST NAME , ADDRESS, CITY,
STATE , POSTAL CODE ,
PHONE)
RES ERVATION (RE SERVATION ID, T RIP ID, TRI P DATE , NUM PERSONS,
TRIP PRICE,
9.
OTHER FEES,
CUSTOMER NUM)
A coliimn (attribute), B, is fiinctionally depende11t 011 anotl1er col11mn (or a
collection of colum11s), A, if at any point in time a valiie for A deter1ni11es
a single value for B.
11 . F11nctional dependencies:
DEPARTMENT NUM ➔ DEPARTMENT NAME
ADVISOR NUM ➔ ADVISOR LAST NAME , ADVISOR FIRST NAME ,
DEPARTMENT NUM
COURSE
COD E ➔ DESCRIPTION
STUDENT NUM ➔ STUDENT LAST NAME , STUDE NT FIRST NAME ,
ADVISOR NUM
STUDENT NUM, COURSE
CODE ➔ GRADE
Relations:
DEPARTMENT (DEPARTMENT NUM, DEPARTMENT NAME)
ADVISOR (ADVISOR NUM, ADVISOR LAST NAME, ADVISOR FIRST NAME ,
DEPARTMENT NUM)
COURSE (COURSE CODE , DE SCRIPTION)
STUDENT (STUDENT NUM, STUDENT LAST NAME, STUDENT FIRST NAME ,
ADVISOR NUM
STUDENT COURSE (STUDENT NUM, COURS E CODE , GRADE)
Entity-relationsl1ip diagram : (Note: Yoiir rectangles can be in diffe re11t
positions as long as they are connected by tl1e san1e arrov.1s.)
DEPARTMENT
ADVISOR
STUDENT
STUDENT_COURSE
COURSE
FIGURE C-1
13.
A table (relation) is i11 seco11d 11ormal form when it is iI1 first nor1nal for1n and
no no11key col11mn is dependent on only a portion of tl1e primary l{.ey. ,\Then
Answers to Odd-Numbered Review Questions
a table is no t in second normal form, tl1e table contains r edl.1ndancy, which
leads to a varie ty of t1pdate ano malies. A change in a value can reqt1ire no t
jt1st 011e change, bt1t several. The re is the possibility of inconsistent data.
Adding additional da ta to the database migl1t no t be possible \,Vithot1t cr eating
artificial valt1es for pa rt of tl1e ltey. Finally, dele tions of certain item s can
result iI1 inadvertently deleting crt1cial information from the d atabase.
15 .
STUDENT (STUDENT NUM, STUDENT LAST NAME , STUDENT F IRST NAME ,
ADVI SOR NUM)
ADVI SOR (ADVISOR NUM, ADVISOR LAST NAME , ADVISOR FI RST NAME )
COURS E (COURS E CODE , DE SCRIPT I ON)
STUDENT COURSE (STUDENT NUM, COURS E CODE , GRADE )
17 . Ans"vers to c ritical tl1iI1king questio11s ar e 11ot provided .
CHAPTER 3-CREATING TABLES
1.
3.
5.
7.
9.
11 .
13.
Use tl1e CREATE TABLE command to cr eate a table by typing the table 11ame
and tl1en listing \,\7ithiI1 a si11gle set of pare11theses the colu111ns i11 tl1e table.
CHAR, \ TARCHAR, DATE, DECIMAL, INT , SMALLINT
a. Valid
b . Valid
c. Invalid
d . Invalid
Use tl1e INSERT conunand.
Use tl1e UPDATE com111ru1d.
Use tl1e DESCRIBE comma11d.
Ans"ve rs to c1itical thinlti11g q1.1estions are no t provided .
CHAPTER 4-SINGLE-TABLE QUERIES
The basic form of tl1e SELECT co111111and is SELECT-FROM-\VHERE. Specify
tl1e colt1n111s to be lis ted after tl1e word SELECT ( or type * to select all columns), and tl1en specify tl1e table 11rune tha t co11tai11s these columns after
tl1e word FROM. Optionally, you can include co11dition (s) after the word
\VHERE.
3. Yott can for1n a co1npot111d co11ditio11 by combiI1i11g si111ple co11ditio11s a11d
t1s iI1g tl1e oper ators AND, OR, or NOT.
S. Use arithme tic operators and write the compt1tation in place of a colt1mn
11am e. Yot1 can assign a nrune to tl1e computation by following tl1e computation \,Vith the \,Vord 1\S a11d the11 tl1e d esired name.
1.
Appendix C
7. lt1 Oracle, the percent (%) wildcard represents any collection of characters.
Tl1e ttnderscore (_) wildcard represents any si11gle cl1aracte r.
9. Use ai1 ORDER BY clause.
11 . To sort data in descending order, follo\V the sort Irey witl1 tl1e DESC
ope ra tor .
13. To avoid dttplicates, precede the colt1nn1 name \.Vitl1 tl1e DISTINCT opera to r.
15 . Use a GROUP BY clat1se.
17 . Use tl1e IS NULL operator in the \\THERE clause.
CHAPTER 5-MULTIPLE-TABLE QUERIES
1 . h1dicate i11 tl1e SELECT clattse all colttmns to display, list i11 tl1e FROM clattse
all tables to joi.11, a11d tl1en inclttde in the \VHERE clause any co11ditio11s
reqttiring valttes in matching colttmns to be equal.
3. IN and EXISTS
5. An alias is an alte1nate name for a table. To specify an alias in SQL, follo\.v
tl1e name of tl1e table \Vitl1 tl1e name of tl1e alias. Yott ttse tl1e alias jttst lilre a
table name throughottt the SQL command.
7. Use tl1e ln\TION, INTERSECT, and 1filTUS operato rs to c reate a unio11, inte rsectio11, and difference of t\vo tables. To perform any of tl1ese operatio11s, the
tables 1nust be union compatible.
9. \\'he11 tl1e ALL ope rator precedes a st1bque ry, the condition is trtte only if it
satisfies all valttes prodttced by tl1e subqtte ry.
11 . In an i11ner join, only n1atclli11g rows from botl1 tables are il1cluded . Yott can
ttse the INNER JOIN clause to perform an illl1er join.
13. lt1 a rigl1t ottter joi11, all rows fron1 tl1e table 011 tl1e rigl1t will be i11cluded
regardless of \.\7he tl1er tl1ey 111atch ro,vs from the table 011 tl1e left. Ro\,,s fro111
the table 011 tl1e left will be i11clttded only if tl1ey 1na tcl1. Yott can ttse tl1e
RIGHT JOIN clattse to perform a rigl1t outer joi11.
15. At1s\\7ers to c1i tical tl1it1king qttestions are no t provided .
CHAPTER 6-UPDATING DATA
1.
3.
5.
7.
CREATE TABLE
Use the INSERT com1nai1d witl1 a SELECT clattse.
DELETE
In Oracle, use tl1e ROLLBACK co1nmand. In SQL Ser ver, use tl1e ROLLBACI(.
TRANSACTION cormnand. 1\11y ttpdates m ade since tl1e most recent
C01vlMIT command (or COMMIT TRANSACTION command i.11 SQL Server)
are reversed .
9. The clause is SET followed by the colttmn nam e, followed by an eqt1als sig11
(= ) and tl1e word ~TULL.
Answers to Odd-Numbered Review Questions
In Oracle, ttse tl1e AL'fER TABLE command witl1 a 110DIFY clattse. In SQL
Server, tise the ALTER TABLE com1na11d witl1 an ALTER COLUMN clattse.
13 . At1s\1,rers to critical tl1il1lting questio11s are 11ot provided.
11.
CHAPTER 7-DATABASE ADMINISTRATION
1. A vie\v contail1s data tl1at is derived from existing base tables vvl1e11 users
attempt to access tl1e viev\'.
3. A defini11g qttery is the portio11 of the CREATE VIEW con1Illat1d tl1at
describes tl1e data to inclttde i11 a \riew.
5. Vievvs provide data independence, allovv database access co11trol, and simplify
tl1e database strt1ctt1re for ttsers.
7. DROP VIEW
9. REVOICE
11 . Use tl1e CREATE INDEX com111and to create an index. Use the CREATE
UNIQUE INDEX co111mand to create a ttnique index. A ttniqtte i11dex allows
only ttniqtte valttes il1 the colunn1 ( or coltlll111S) 011 vvhicl1 tl1e index is created.
13. The DBNIS
15. Tl1e follovvi11g types of updates would violate tl1e foreig11 l{ey constraint:
a. Addil1g a customer for \\7hicl1 tl1e rep number does not match a11y rep il1
the REP table.
b. Cl1angi11g tl1e valtte in REP_l\Tl.JM colttmn i11 tl1e CUSTOMER table to a
valtie that does not matcl1 a11y rep in tl1e REP table.
17 . Tl1e DBNlS tipdates tl1e syste1n catalog at1to111atically vvl1en tisers mal{e cha11ge
to tl1e database, st1cl1 as creati11g, alteril1g, or droppi11g tables or creati11g or
droppi11g i11dexes.
19. Use the Cl-IECI<. clattse of tl1e ALTER TABLE comma11d.
2 1. Use the ADD FOREIGN ICEY clause of the ALTER TABLE command.
23. At1svvers to critical thinlting qttestions are not provided.
CHAPTER 8-SQL FUNCTIONS AND
PROCEDURES
1.
3.
Use the UPPER ft111ction to display letters i11 ttppercase in Oracle and SQL
Server. In Access, use tl1e UCASE() ft1nction. Use the LO\\TER fu11ctio11 to
display letters il1 lowercase in Oracle a11d SQL Server. In Access, tise the
LCASE() fu11ctio11.
To add 111011tl1s to a date, use tl1e 1\DD_NIONTI-IS ft1nctio11 (Oracle), or tl1e
DATEADDO ft1nction (Access and SQL Server). To add days to a date, add
tl1e desired 11t11nber of days to a date . To fi11d tl1e 11t11nber of days between
two dates, sttbtract tl1e earlier date fro1n the later date.
Appendix C
S.
7.
9.
11 .
13.
15 .
17 .
19.
2 1.
lt1 Oracle , separa te tl1e colttmn n ames \.Vith hvo vertical lines (II) in tl1e
SELECT clause. 111 SQL Serve r, separ ate tl1e colt1mn na mes with the +
syn1bol. 111 Access, separa te tl1e column names \.Vitl1 tl1e & symbol.
A stored procedure is a file that is sto red 011 a server and tl1a t conta il1s co1nm a11ds tl1at can be ttsed repeatedly. Stored procedures eliJ11i11ate the need for
tisers to retype a que ry each titne it is needed .
lt1 PUSQL procedtires, yott decla re variables first before a11y procedural code.
Use tl1e INTO clat1se to place the results of a SELECT sta ten1ent in variables.
\\Then re trieving mttltiple ro,vs ,vith a SELECT statem ent, ttse a ct1rsor .
FETCH
To t1se SQL commai1ds in Access, create tl1e cotrunand in a string variable.
To rtin the cormna nd stored il1 tl1e string variable, tise the D0Cmd.Rt111SQL
command.
To move to tl1e ne.A't record in an Access recordset, use tl1e MoveNext
comma11d.
Tl1e INSERTED a11d DELETED tables are temporary syste1n tables created by
SQL Server. Tl1e INSERTED table co11tail1s tl1e most rece11t (t1pdated) valt1es
il1 a record a11d tl1e DELETED table co11tail1s tl1e previous (before t1pdate)
valtte.
@repnum, 250- 251
A
Access (11icrosoft), 183
ALTER TABLE comn1and, 183
changit1g colu1ru1 na1nes in, 195
character functions in, 230
concatenating colu1nns i11, 234
creating indexes in, 210- 211
creating vie'vvs i11, 192
data types in, 168
Docu1nenter tool, 87, 182, 213
parameter q11eries in, 235
and PL/SQL programs, 228
query results display in, 99
rollbacks in, l 7frl77
run11it1g SQL co1nma11ds, 6 7
savmg SQL com1na11ds, 78
SELECT com1nand, 75
specifying foreign keys in, 215-216
specifying pri1nary keys it1, 215
usi11g SQL in, 252- 257
validation n1les in, 218
'vvildcards in, 109
'vVork.iJ1g 'vVith dates in, 231- 233
access control, 204
security and, 204-207
ADD clause, 179
ADD FOREIGN I<EY clause, 216
addmg, 202
rO'vVS, 202- 203
additio11s, 44
to tables, 43-45, 47
ADD_110NTJIS function, 231
ADD PRI11ARY KEY clause, 215
aggregate functions , 112
ALL operator, 154- 156
ALTER COLill1N clause, 183
ALTER TABLE command, 179, 185
ADD PRTh1ARY I<EY clause, 215
CI-IECI< clause, 217
integrity constrai11ts 'vVith, 215- 216
AND condition, 102
AND operator, 102
ANY operator, 154- 156
arguments, 229
aritl1metic operators, 106
AS cla11se, 115
asterisk (*), 99, 109
attributes, 24
database, 24, 26
identifying, 33
Au tocon11nit, 1 73 , 177
AVG fu11ction, 114-115
B
base tables, 191
joins of, updati11g vie'vvs of, 200- 203
BET\.VEEN operator, 105-106
Boyce-Codd normal fonn (BCNF), 48
breadcn1n1bs, 63
C
calli11g, 23 7
stored procedures, 23 7
candidate keys, 32, 48
Cartesia11 products, 159
categories, 2
relationships bet'vveen , 2
changmg, 239
rO'vVS, 239- 240
character functions , 229- 230
CHAR data type, 70
ClIECI< clause, 217
child t able, 217
client, 235
client/server systems, 235
CLOSE con1mand, 242, 245, 250-251
Colonial Adventure Tours database (exa1nple)
exercises, 57, 90- 92, 130- 131, 164- 165, 189,
223- 224, 264- 265
introduction to, 1- 2, 8-14
sample data, 8- 14
column 11ames, 23
conventions for, 23
qualifying, 27, 134- 135
columns, 179
adding, 179
changing values to null, 177- 179
computed, 106, 108
concatenating, 233-234
it.1 databases, 26
decreasing length of, 183
detennmant, 48
listing, 87
11onlley, 44
Index
colum11s (coritini1.ecl)
renan1ing, \Vhen creating vie\.vs, 194- 195
retrieving, 98--100
retrieving single, 235--237, 249
using self-joins on primary key, 145- 14 7
commands, 91- 92
CO:tv111IT co1nmand , 16 7, 173- 174
comparison operators, 101
compound conditions, 102, 105
in updates, 171
computa tio11s, 106, 108
computed columns, 106, 108
concatenation, 29
of columJ1s, 233- 234
conditions
AND, 102
compound , 102, 105
NOT, 104- 105
nulls in, 125
OR, 103
simple, 101- 102, 103
con·elated subqueries, 139
COUNT functio11 , 113, 115
CREAT E INDEX com1nand , 210--211
CREATE PROCEDURE co1runand , 236- 237, 249
CREAT E TABLE con1mai1d , 65, 68, 71, 81- 85,
185
\Vith errors, 67-68
integrity constra il1ts \.Vith, 215
table s truc ture and , 86--87
CREATE VIE\V command, 191- 198
creating, 210
indexes, 210- 211
stored procedures, 235--23 7
credentials, 61
CURRENCY data type, 6 7, 168
cursors, 248
advantages of, 248
closiJ1g, 245
complete procedure using, 245--246
complex, 247- 248, 251- 252
fetching ro\.vs from, 243-245
ope11ing, 250
using, 242- 248, 250- 251
D
da ta, 168
ch anging, it1 table, 168, 171
changing, \Vith stored procedure, 239, 249
c uston1iziJ1g display of, 198
deleting, \.Vith procedure, 239- 240
deleting, \Vith Visual Basic, 252- 253
grouping, 120- 125
inco11sistent, 44, 4 7
inserting, \Vith Visual Basic, 255
sorting, 111- 112
updating, using vie\.VS, 198- 203
updating, \Vith Visual Basic, 254- 255
data base admil1istratio11, 191
c reating a11d usi11g vie\vs, 191- 198
indexes and, 207- 212
integrity constraints and , 215- 218
introduction to, 191
secu rity and, 204- 207
system catalog and, 212- 215
updating da ta using vie\vs, 198- 204
database admiJ1istrator, 191
da tabase design, 51- 53
diagran1s for, 51, 54
introduction to, 21
method for, 32- 33
process example, 3 4 40
rela tions and, 24, 27
requirements, 34
databases, 22
concepts of, 22, 27
defined, 1
for self-joiJ1s, 144
using, 143
da ta dic tionary, 212
Da tasheet vie\.v, 6 7
data types, 65
assigni11g to variables, 237
using, 70
DATEADD() function, 232
DATE da ta type, 70
DATE() function , 233
da tes, 231
\.Vorlting \.Vitl1, 231- 233
DBA_TAB_COLUMNS, 212
DBA_TABLES, 212
DBA_VIE\VS , 212
DBMS_OUTPUT , 23 7
DEALLOCATE con1mand , 250- 251
Debug.Print command, 253
DECTh1AL dat a type, 6 7, 70, 168
DECLARE s ta temen t, 250, 251
defrning q-u ery, 192, 194
DELETE comJna11d , 167, 175, 176, 203, 240- 241,
252- 253
dele ting, 252
da ta, \Vith procedure, 240--241, 250
da ta \.Vith Visual Basic, 252- 253
rO\VS, 174- 177
dele tio11s, 44
fron1 dat abase, 44, 47
DESC opera tor, 112
DESCRIBE com1nand, 86, 184- 185
de te nninai1t, 48
diagran1s, 51
entity-rela tionship (E-R), 51, 54
DISTINCT operator, 115- 117, 199
DoC1nd.Ru11SQL com1nand , 252
Docu1ne11ter tool, 87, 182, 213
DROP INDEX co1TIJnand , 211- 212
dropping, 211
indexes, 211- 212
vie\.vs, 203-204
Index
DROP TABLE comn1and, 69, 185-186
DROP VIE\V con1mand, 203-204
E
entities, 24, 32
entity-relationship (E-R) diagrruns, 51, 54
error handling, 238
\Vith stored procedures, 238- 239
EXCEPTION clause, 238- 239
EXEC command, 249
EXISTS operator
and joi11s, 138- 140
F
FETCHcommand,242,243- 245,247, 250- 251
fields, 26
in databases, 26
first normal for1n (lNF), 40-42
FLOOR fu11ction, 231
foreign keys, 215-216
FROI\1 clause, 97
and joi11s, 148
full outer joins, 158
functional dependence, 27- 30, 33
functio11s
aggregate, 112
AVG function, 114- 115
character, 229- 230
AS clause \Vith, 115
COUNT functio11, 113- 114, 115
introduction to, 227
.tvlfu'{ function, 114-115
I\IIIN functio11, 114-115
n1.11nber, 230- 231
SUI\1function, 113- 114
usit1g, 112, 11 7, 228-234
i11co11sistent data, 44, 47
indexes, 207
creating, 210- 211
described, 201- 210
dropping, 211- 212
unique, 212
inner joins, 157
IN operator, 110
and joins, 137, 138
using, 138
INSERT co1nmand, 71- 74, 81- 85, 168- 169,
171- 172, 185, 199, 202, 255
adding ro\VS using, 171- 172
in CUSTOI\IBR table, 168
inserting, 255
data, \Vith Visual Basic, 255
INT data type, 70
integrity constraints, 215- 218
integrity support, 215
INTERSECT operator, 150, 152- 153
IS NOT NULL operator, 125
IS NULL operator, 125
item, 6
J
joining, 141
mul tiple tables, 140-141, 147- 149
t\vo tables, 134-137, 139
joins, 157
inner, 157
outer, 158- 159
self-joil1s, 145- 147
updating vie\VS involving, 200- 203
K
key, 111- 112
G
GETDATE() function, 233
GRANT con1mand, 204- 207
GROUP BY clat1se, 121- 122, 142
grouping data, 120
it1 databases, 120-125
H
I-IAVINO clause, 122- 125
I
Inu11ediate \Vi11do\v, 253- 254
IN clause, 110
L
LCASE function , 230
left 011ter joms, 158
LIKE operator, 108- 110
LO\VER function, 229
M
111ajor sort l{ey, 112
MAX function, 114- 115
MIN function, 114- 115
111it1or sort key, 112
MINUS operator, 150, 153- 154
MODIFY clatise, 183, 185
111ul tiple-table queries, 133-166
Index
N
na mes, 107
assigning, to computed colu11ms, 107
11a1u ing co11ventions, 23
nested St1bqueries, 140- 141
nestil1g, 117
queries, 117- 120
11onkey colum n , 44
nonprocedural languages, 22 7
11ormal fom1s, 40
nor1n aliza tio n, 40, 50
Boyce-Codd normal form (BCNF), 48
first normal for1n (l NF), 40-42
goal of, 40
second nor1nal fo rm (2NF), 42--46
third normal form (3NF), 46- 51
NOT conditio11, 104- 10 5
NOT NULL clause, 71
NOT opera tor , 102
null da ta value, 71
nulls, 180
ch ru1ging values to, 177- 179, 184- 185
inserting rO\VS \Vith, 74
usil1g, 71
null values, 125
in conditions, 125
in SUM, AVG, 11AX, 111N functio ns,
114- 115
NillvIBER da ta type, 67
numbe r func tio11s, 230-231
num be rs, 10 5
0
one-to-n1an y relatio11ships, 24
OPEN command, 242 , 243, 250-251
opera tions, 163
product, 159- 160
set, 150- 154
special, 157- 160
optin1iza tion, 141
Oracle, 159
oute r joi11s in, 159
systen1 catalog and , 213
Oracle Application Express, 99
query resul ts display il1, 99
Oracle Database llg Express Edition
starting, 60-64
OR co11ditio n, 103
orde r, 6
ORDER BY clat1se, 111, 112, 133, 196
orde r line, 5, 6
ORDERS table, 5-6
OR opera tor, 102
outer joins, 15~ 159
p
pa ran1eter queries, 23 5
pa rent table, 2 17
percent sign (%), 109
PUSQL, 228
crea ting stored procedures, 23 5- 23 7
cursors in, 242 , 248
erro r l1a11dling i11, 238- 239
stored procedures in , 23 5- 23 7, 248
PUSQL comn1ands, 236
primary key colum11s, 145
using self-joi11s 011, 145- 147
prima ry keys, 215
adding, 215
in da tabases, 30, 32
\Vith joi11s, 203
11or1nal forms and , 44, 45
shortl1ru1d representa tio n of, 31
primary sort key, 112
privileges, ·u ser , 204- 207
procedural code, 23 7
procedural languages, 228
procedures, 264
produc ts, 159- 160
Q
que ries, 141
comprel1ensive exaniple, 141- 142
constructing simple, 97 , 111
defin ed , 9 7
defining, 192
multiple-table, 133- 166
nesting, 117- 120
pa raniete r, 235
saving as stored procedures, 23 5- 23 7
subqueries, 118- 120
using aliases in , 142- 143
using SELECT comtnand , 9 7- 110
questio n n1ark (?), 109
R
records, 26
.i n da tabases, 26
red11ndancy, 43
REFERENCES clause, 216
rela tio nal da tabases, 22- 23
co11cepts of, 22, 27
func tional depende11ce in, 27- 30, 33
Index
in troduction to, 22 , 24
11orm aliza tio n of, 40 , 50
sl1ortl1and for, 2 6- 2 7
relations, 25
in databases, 2 5--26
um1or1nalized, 40
relationsl1ips, 24
in da tabases, 24 , 26
011e-to-man y, 24
repeating groups, 25--26
restric tit1g, in join, 135, 13 7
revie"v questions
da tabase adm in istra tion , 220-221
m ultiple-table que ries, 162- 163
single-table queries, 128- 129
SQL, 88-89
upda ting data, 187- 188
REVOI<E commai1d , 206-207
rigl1t o uter joins, 158
ROLLBACI< command, 167, 173- 174,
176- 177
rollbacks, 176
executing, 176-177
ROUND function, 230- 231
ro\,v-and-colutnn subset vie"vs, 200
upda ting, 200 , 202
rO\,VS, 171
adding, 171- 172, 202
ch ru1ging, \>Vith update procedure , 239- 240
counting, 113-114
cursors \,Vitl1, 242- 248
in da tabases, 26
deleting, 174- 177
deleting, \Vith procedure, 240- 241
grouping, 120- 125
inserting, 71, 74
re trieving, 98-100
re trieving si11gle , 23 5--23 7, 249
selecting multiple, 242- 248, 255--2 57
upda ting, 174- 177
RTRIM func tion, 234
s
script files, 23 5- 236
script repository, 78
scripts, 62-63, 78-80
seconda ry sort k.ey, 112
second 11or1n al form (2NF), 42-46
security, 204
access control and, 204- 20 7
provided by vie"vs, 198
SELECT clause, 98
ALL ope ra to r \,Vith, 154-156
ANY operator \,Vith, 154-156
and joins, 142 , 148- 149
SELECT con11nand, 74-77
\,Vith IN clause, 110
fo r colunm and ro"v retrieval, 98- 100
\,Vith co1n pound conditio11s, 102- 105
\,Vith computed colLIOll1S, 106- 108
cou n ting ro,.,vs usit1g, 113
described , 98
\,Vitl1 GROUP BY clause, 121- 122
it1troduc tio n to, 9 7
\,Vith LII<E opera tor , 108-1 10
retrieving mul tiple rO\,VS usi11g, 242, 2 55--256
sorting da ta \,Vith, 111
\VI-IERE clause in, 100-102
self-joins, 145
i11correct, 145
on prin1ary key colum n, 145- 147
using, 143- 145
SEQUEL, 59
server, 23 5
set operatio11s, 150- 154
SET SERVEROUTPUT ON comma11d , 23 7
sim ple conditions, 101- 102, 103
slash (/), 23 7
SMALLlNT da ta type, 70
Social Security numbers, 32
as pritnary key, 32
Solma ris Condomil1iun1 Gro up database (example)
exercises, 58, 93 , 131- 132, 165- 166, 190,
225--226, 265- 266
introduc tion to, 1, 14- 17
sample da ta , 14- 17
sorting, 110-112
sort key, 111- 112
sp_colu1nns stored procedure, 8 7
specific functions, 2 63
sp_tables procedure, 2 13
SQL (Structured Query La11gu age), 215,
227- 228
exte11sions, 228
func tions, 228-234
integrity constraints in, 215- 218
using i11 Access, 2 52- 2 57
using i11 progra1nn1ing enviro nn1ent,
227- 228
SQL comn1a11ds
il1 Access, 67
comparison opera to rs in, 101
correcting e rrors in, 68-69
crea til1g and ruru1ing, 59- 64
embeddit1g, in anotl1er langu age, 228
entering, 63- 64
sto ring in strit1g variable, 2 52- 2 53
triggers \Vith, 257- 2 59
SQL Server , 68, 183
ALTER COLUNIN clause, 183
C0111v1IT ru1d ROLLBACI< commands, 174
co11ca tena ti11g columns it1, 233- 234
Index
SQL Server (conti1it.tecl)
listing colum11s in, 182
nulls in, 1 79
ordering que ry restilts in, 196
query results display it1, 99
stored procedures, 213
triggers it1, 259
usit1g T-SQL in, 248- 252
'.Vork.ing '.Vith dates in, 231- 233
SQL Server Managen1ent Studio , 68
statistics, 203
upda ting vie'.vs involvit1g, 203
stored procedures, 213
calling, 237
described , 235
error handling, 238- 239
illustra tio11 of, 235- 23 7
for selecting n1ultiple ro'.vs, 241- 248
triggers, 257- 259
in T-SQL, 248- 252
upda te procedures, 239- 241, 249
usit1g cursors it1, 242- 248
in Visual Basic, 252- 257
subqueries, 118- 120
ALL ru1d ANY ope ra to rs '.vith, 154-156
correla ted , 139
nested, 140- 141
Sill1 func tio n, 113- 114
Sill1 (BALANCE) func tion , 228
SYSCOLillifNS, 212
SYSDATE func tio n, 232
SYSTABLES, 212
system catalog, 212- 215
SYSVIE\VS, 212
T
Table Design vie'.v, 67
tables, 71
adding ro'.vs, 71
adding ro'.vs to , 171- 172
aliases for , 142- 143
base, 191
ch a11ging da ta i11 existing, 169- 171
ch ru1ging stn1c t11re of, 179- 185
changing values to null i11, 177- 179
creating, 65, 68
creating n e'.v fro1n existing, 167- 169
da ta types, 70
deleting ro'.vs from , 174- 177, 240- 2 41
difference of, 150, 152- 153
dropping, 69, 185-18 7
foreign keys fo r, 215- 216
intersection of, 150, 152- 153
joining 1n ul tiple, 140- 141
joini11g several, 147- 149
joitling n,vo, 134-13 7, 139
n aming con ventio ns, 23
n or1nalization of, 40, SO
primary keys of, 30, 32
produc t of hvo, 159- 160
que rying mul tiple , 133- 166
redundancy in, 43
rela tio ns in, 24, 28
repeating groups in, 25- 26
self-joins, 145- 147
system catalog and, 212- 215
union compa tible , 1551
union of, 150- 151, 152
upda ting ro\VS in, 174-177
TAL Distributors da tabase (exa n1ple), 34
design process for, 3 4 40
E-R diagram of, 51, 54
exercises, 56-57, 90, 129- 130, 163-164,
188-189, 22 1- 223, 262- 264
integrity constraints in, 215- 218
introduc tion to, 1, 8
sample da ta, 4, 6, 22- 23
sample order , 2-8
table str11cture, 4-5
tlurd no rmal form (3NF), 46-51
transactions, 173
Tran sact-SQL (T-SQL) , 228
cursors in, 242- 248
retrieving single ro'.v and colunn1, 249
sto red procedures it1, 248- 252
using i11 SQL Server , 248- 252
triggers, 257- 259
tuples, 26
u
UCASE function , 230
underscore (_), 109
union-compa tible tables, 151
UNIO N opera tor, 150- 151, 152
unique i11dexes, 212
uru1onnalized rela tions, 40
upda te a non1alies, 43, 47
UPDATE command , 169- 170, 171, 175, 180- 181,
185, 203, 239- 241, 254- 255
upda te procedures, 239- 241 , 249
upda tes, 173
COIDlnitting, 173
roll backs, 1 73
to tables, 43, 4 7
upda ting, 198
da ta, using vie'.vs, 198- 204
da ta, \Vith Visual Basic, 254- 255
rO'.VS, 174- 177
table data, 169- 171
table structure, 179- 185
Index
UPPER function, 229- 230
user access, 204- 207
V
VARCHAR data type, 70
variable na1nes, 236
in PUSQL, 23Cr23 7
variables, 236
assigning data type to, 236
vie"vs, 197
benefits of, 197- 198
creating and usi11g, 191- 198
dropping, 203- 204
involving joins, 200- 203
involving statistics, 203
ro\,v-and-colu1nn subset vie"vs, 200, 202
updating data using, 198- 204
Visual Basic, 259
deleting data \,Vitl1, 252- 253
finding 111ultiple r O\,VS \,Vith, 255- 257
i11serting data \,Vitl1, 255
running code in, 253- 254
updating data \,Vith, 254-255
w
\\THERE clause, 134
described, 98
vs. HAVINO clause, 123-125
and joins, 134, 135--136, 148- 149
using, 100- 102
\,Vilclcards, 108--109
vVITH GRANT OPTION cla1.1se, 206- 207
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )