The Companion Web SiteThe companion Web site for this book is a Google group called “sqlfun.”The group Web address is: http://groups.google.com/group/sqlfun You can also send e-mail to m
Trang 2F U N D A M E N T A L S
Third Edition
Trang 5warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental
or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact:
U.S Corporate and Government Sales
Visit us on the Web: informit.com/ph
Library of Congress Cataloging-in-Publication Data
Patrick, John J.
SQL fundamentals / John J Patrick — 3rd ed.
p cm.
Includes indexes.
ISBN 978-0-13-712602-6 (pbk : alk paper) 1 SQL (Computer program
language) 2 Oracle 3 Microsoft Access.
I Title
QA76.73.S67P38 2008
005.75'65—dc22
2008024745 Copyright © 2009 Pearson Education, Inc.
All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information regarding permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax: (617) 671-3447
ISBN-13: 978-0-13-712602-6
ISBN-10: 0-13-712602-6
Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts.
First printing, August 2008
Trang 6Seymour Hayden, who taught me mathematicsStanley Sultan, who taught me Irish literatureJim Seibolt, who taught me computers
Scot Stoney, who taught me databases
and to all my students
Trang 8Preface xxv
1 Storing Information in Tables 1
2 Getting Information from a Table 31
3 Compound Conditions in the Where Clause 83
4 Saving Your Results 133
5 The Data Dictionary and Other Oracle Topics 171
6 Creating Your Own Tables 209
7 Formats, Sequences, and Indexes 245
8 Data Integrity 281
9 Row Functions 321
10 Using Row Functions 361
11 Summarizing Data 399
12 Controlling the Level of Summarization 435
13 Inner Joins 473
14 Outer Joins 517
15 Union and Union All 555
16 Cross Joins, Self Joins, and CrossTab Queries 597
17 Combining Tables in a Production Database 653
18 If-Then-Else, Parameter Queries, and Subqueries 673
19 The Multiuser Environment 721
20 The Design of SQL 739
A Oracle Is Free: How to Get Your Copy 751
B Quick Start with Oracle 765
C Quick Start with Access 771
D Diagram of the Lunches Database 783
Index 787
Trang 10P r e f a c e x x v
1-4 What is in this book? 8
1-5 Data is stored in tables 101-6 A row represents an object and the information about it 111-7 A column represents one type of information 12
1-8 A cell is the smallest part of a table 141-9 Each cell should express just one thing 151-10 Primary key columns identify each row 161-11 Most tables are tall and thin 18
Trang 11Examples of Tables 19
1-12 An example of a table in Oracle and Access 191-13 Some design decisions in the l_employees table 221-14 The Lunches database 23
Chapter 2
G e t t i n g I n f o r m a t i o n f r o m a T a b l e 31
2-1 The goal: Get a few columns and rows from a table 332-2 Overview of the select statement 34
2-3 Overview of the select clause 372-4 Use a select clause to get a list of some of the columns 382-5 Use a select clause to get a list of all of the columns 412-6 Use a select clause to get the distinct values in one column 442-7 Use a select clause to get the distinct values in two columns 48
2-8 Overview of the where clause 502-9 Using an Equal condition in the where clause 522-10 Using a Less Than condition in the where clause 562-11 Using a Not Equal condition in the where clause 582-12 Using the in condition in the where clause 612-13 Using the between condition in the where clause 632-14 Using the like condition in the where clause 662-15 Using the is null condition in the where clause 69
2-16 Overview of the order by clause 712-17 Sorting the rows by one column in ascending order 732-18 Sorting the rows by several columns in ascending order 752-19 Sorting the rows by several columns in various orders 772-20 The whole process so far 79
Trang 12Chapter 3
C o m p o u n d C o n d i t i o n s i n t h e W h e r e C l a u s e 83
3-1 Using a compound condition in the where clause 853-2 Using not with in,between, like, and is null 883-3 The standard form of a complex condition in the where clause 903-4 A common mistake 92
3-12 You can turn off case sensitivity in the Oracle SQL Command Line environment 117
3-13 Case sensitivity in Access 118
3-14 SQL uses three-valued logic 120
3-15 Error messages are often wrong 122
3-16 Exercise 1 1243-17 Exercise 2 1273-18 Exercise 3 129
Chapter 4
S a v i n g Y o u r R e s u l t s 133
4-1 Create a new table from the result of a select statement 1354-2 Creating a new view from the results of a select statement 139
Trang 134-3 Similarities between tables and views 1424-4 Differences between tables and views 1424-5 Deleting a table 143
4-6 Deleting a view 1454-7 One view can be built on top of another view 1464-8 Preventative delete 149
4-9 Adding one new row to a table 1514-10 Adding many new rows to a table 1544-11 Changing data in the rows already in a table 1574-12 Deleting rows from a table 159
4-13 Using the Oracle GUI to change data in a table 1614-14 Using the Access GUI to change the data in a table 164
4-15 Constraints with insert,update, and delete 1674-16 Security restrictions 169
Chapter 5
T h e D a t a D i c t i o n a r y a n d O t h e r O r a c l e T o p i c s 171
5-2 The Autocommit option 1745-3 Transactions 175
5-4 Changing data through a view 1805-5 Example of changing data through a view 1815-6 Views using With Check Option 189
5-7 Overview of the SQL Commands page 1925-8 The Autocommit option 194
5-9 The Explain option 194
5-10 Overview of the Data Dictionary 195
Trang 145-11 How to find the names of all the tables 1975-12 How to find the names of all the views 1995-13 How to find the select statement that defines a view 2005-14 How to find the names of the columns in a table or view 2015-15 How to find the primary key of a table 203
6-4 Numeric datatypes 2226-5 Date/time datatypes 2226-6 Other datatypes 2226-7 Putting data into a new table 2236-8 Creating the l_employees table in Oracle 224
6-9 Adding a primary key to a table 2266-10 Changing the primary key of a table 2286-11 Adding a new column to a table 2296-12 Expanding the length of a column 2316-13 Deleting a column from a table 2326-14 Making other changes to tables 234
6-15 The problem with duplicate rows 2376-16 How to eliminate duplicate rows 2396-17 How to distinguish between duplicate rows 240
Trang 157-2 Displaying formatted dates 2497-3 Entering formatted dates 2527-4 Other formats in Oracle 2547-5 Formats in Access 254
7-6 Creating a sequence in Oracle 2577-7 Using sequences in Oracle 2587-8 Sequences in Access 260
7-9 Creating an index 2637-10 The Optimizer 2647-11 An example of how an index works 264
7-12 How to find information about the datatype of a column 2667-13 How to find information about sequences 269
7-14 How to find information about indexes 2717-15 How to find information about all your database objects 2747-16 How to use the index of Data Dictionary tables 276
7-17 How to use the index of Data Dictionary columns 277
7-18 Create a table of the days you want to celebrate 278
Chapter 8
D a t a I n t e g r i t y 281
8-1 A constraint keeps the data consistent 2838-2 check constraints 283
8-3 unique constraints 2858-4 not null constraints 2878-5 primary key constraints 2888-6 Restrictions on the datatype and length of fields 289
8-7 The concept of RI 2908-8 An example of RI 291
Trang 168-9 Inserts and updates to the data table prevented by RI 2938-10 Inserts and updates to the data table allowed by RI 2948-11 Updates and deletes to the lookup table prevented by RI 2958-12 How to delete a code from the lookup table 296
8-13 How to change a code in the lookup table 2988-14 RI as a relationship between the tables 2998-15 Setting up RI in the Access GUI 300
8-16 The three options for deletes and updates to the lookup table 3038-17 The delete rule: set null 304
8-18 The delete rule: cascade 3068-19 The update rule: cascade 308
Variations of Referential Integrity 311
8-20 The two meanings of primary key 3118-21 Using two or more columns for the primary key 3138-22 The lookup and data tables can be the same table 315
8-23 Constraints are often coded in the create table statement 316
Chapter 9
R o w F u n c t i o n s 321
9-1 Getting data directly from the beginning table 3239-2 What is a row function? 324
9-3 An example of a row function in the select clause 3279-4 An example of a row function used in
all the clauses of a select statement 3299-5 Defining a row function as the first step 331
9-6 Functions on numbers 3349-7 How to test a row function 3369-8 Another way to test a numeric row function 337
9-9 Functions on text 340
Trang 179-10 Combining the first and last names 3449-11 Separating the first and last names 3469-12 Formatting phone numbers 348
9-13 Functions on dates 3509-14 An example of a date function 3549-15 Removing the time from a date 356
Chapter 10
U s i n g R o w F u n c t i o n s 361
10-1 Other row functions 36310-2 Using a function to identify the user and the date 36510-3 Using a function to change nulls to other values 36610-4 Using a function to change the datatype 369
10-5 Using Oracle documentation 37310-6 Using Access documentation 37410-7 Using the Access Expression Builder to find row functions 375
10-8 Create a simple pattern of numbers 37710-9 Create a complex pattern of numbers 37910-10 List all the days of one week 38110-11 Create a calendar of workdays 38310-12 How to find out how many days old you are 38810-13 How to find the date when you will be 10,000 days old 38910-14 Numbering the lines of a report in Oracle and Access 39010-15 Optional: An easy way to solve an algebraic equation 393
Chapter 11
S u m m a r i z i n g D a t a 399
11-1 Summarizing all the data in a column 401
Trang 1811-2 A list of the column functions 402
11-3 Finding the maximum and minimum values 40411-4 Using a where clause with a column function 40711-5 Finding the rows that have the maximum or minimum value 409
11-10 The sum and average functions 42011-11 The problem with nulls in addition and how to solve it 422
11-12 Nulls are not always changed to zero 42811-13 Counting the number of nulls in a column 43011-14 Counting distinct dates 431
Chapter 12
C o n t r o l l i n g t h e L e v e l o f S u m m a r i z a t i o n 435
12-1 Summary of groups of data within a column 43712-2 The group by clause 438
12-3 Groups formed on two or more columns 44112-4 Null groups when there are two or more grouping columns 44412-5 Summarized data cannot be mixed with
nonsummarized data in the same select statement 44712-6 Solution 1: Add more columns to the group by clause 45112-7 Solution 2: Divide the query into two separate select statements 45212-8 How to create a report with subtotals and a grand total 455
12-9 Counting to zero, part 2 45512-10 Counting to zero, part 3 457
12-11 The having clause 460
Trang 1912-12 The having clause contrasted with the where clause 46212-13 The whole process of the select statement on a single table 46312-14 The having clause does not add any
more power to the select statement 46312-15 Use a where clause to eliminate raw data 46612-16 How to apply one column function to another column function and get around other restrictions 467
13-10 A join using two or more matching columns 49513-11 A join using between to match on a range of values 49713-12 A join using the Greater Than condition 499
13-13 A join using a row function 50113-14 Writing the join condition in the from clause 502
13-15 Lookup tables 50413-16 Combining a join and selection of data 50713-17 Using a join with summarization 51013-18 How to find the primary key in the Oracle Data Dictionary 51213-19 Combining three or more tables with inner joins 513
Trang 20Chapter 14
O u t e r J o i n s 517
14-1 Outer joins are derived from inner joins 51914-2 The three types of outer joins 520
14-3 The left outer join 52214-4 The right outer join 52414-5 The full outer join 52614-6 An introduction to the union 52914-7 An example of a union of two tables with matching columns 531
14-8 Counting to zero, part 4 53414-9 Combining an outer join with a selection of the data 53614-10 A full outer join in sorted order 539
14-11 Finding the defects in a pattern 54214-12 Comparing tables using two or more columns 54414-13 Comparing two different full outer joins 54614-14 Problem: Left and right outer joins can be difficult to handle 549
15-4 The order by clause in a union 56315-5 Creating a table or view that includes a union 56715-6 Automatic datatype conversion in a union 570
Trang 2115-11 Attaching messages to flag exceptions, warnings, and errors 58315-12 Dividing data from one column into two different columns 58515-13 Applying two functions to different parts of the data 58715-14 A union of three or more tables 588
Set Intersection and Set Difference in Oracle 590
15-15 Set intersection 59015-16 Set difference 592
16-5 An error in the join condition can appear to be a cross join 60516-6 Using a cross join to list all the possible combinations 60816-7 Other layouts when there are three or more dimensions 61116-8 Avoid a cross join of large tables 612
16-13 CrossTab queries when there are two dimensions 62416-14 CrossTab queries with up to four dimensions 63116-15 CrossTab queries with more dimensions 63316-16 CrossTab to show who is attending each lunch 63816-17 CrossTab to show the foods for each lunch 641
16-18 CrossTab queries in Oracle — Part 1 64516-19 CrossTab queries in Oracle — Part 2 647
Trang 22Chapter 17
C o m b i n i n g T a b l e s i n a P r o d u c t i o n D a t a b a s e 653
17-1 Joining several tables in a series of steps 65517-2 Joining several tables at once in the where clause 65817-3 Joining several tables at once in the from clause 658
17-4 Be careful with an inner join 66017-5 Be careful with a left and right outer join 66017-6 A full outer join preserves all the information 66117-7 A full outer join of several tables 661
17-8 Monitor your queries 66317-9 Use the indexes 66417-10 Select the data you want early in the process 66417-11 Use a table to save summarized data 66517-12 Try several ways of writing the SQL 665
17-13 The joins are part of the database design 66617-14 A view can standardize the way tables are joined 66617-15 Ad hoc reporting 670
18-4 Dividing data from one column into two different columns 68518-5 Applying two functions to different parts of the data 687
18-6 A parameter query in Oracle 69018-7 Using a parameter more than once in Oracle 69318-8 More ways to define parameters in Oracle 695
Trang 2318-9 A parameter query in Access 69818-10 A query in Access with two parameters 69918-11 Limitations on parameters in Access 700
18-12 Introduction to subqueries 70118-13 Subqueries that result in a list of values 70318-14 Subqueries that result in a single value 70618-15 Avoid using not in with nulls 708
18-16 Subqueries used in an update command 71018-17 Finding the difference between two tables 71218-18 Using the most current data 714
18-19 Correlated subqueries 71418-20 Subqueries using exists 71618-21 Using a subquery to write an outer join 71718-22 Nested subqueries 718
18-23 Subqueries can be used in limited locations 71918-24 Many subqueries can also be written as a join 719
19-5 How to use a table you do not own 727
19-8 Identifying the user 73219-9 Privileges 732
Trang 2419-10 Roles 73419-11 Several people can use the same table at the same time 736
19-12 ALL versus USER 73619-13 How to find the tables youwant in the Data Dictionary 73719-14 How to find the meaning of the columns 737
Chapter 20
T h e D e s i g n o f S Q L 739
20-1 Do one thing and do it well 74120-2 Focus on information 74120-3 Keep it simple 74220-4 Coordinate people to work together 743
A-1 Create a new database user 755A-2 Download the files to build the Oracle tables 758
Trang 25A-3 Build the Oracle tables by running an SQL script 758A-4 Disaster recovery if you need it 763
A-5 The official Oracle solution 763A-6 My own solution 764
Appendix B
Q u i c k S t a r t w i t h O r a c l e 765
Appendix C
Q u i c k S t a r t w i t h A c c e s s 771
Trang 26SQL is one of the most important computer languages It is the language
of databases Whenever you search for the information you need in alarge library of information, the code that performs the search is likely to
be using SQL Many applications in which you share information tocoordinate with other people also use SQL
It is used in more than 100 software products, and new ones are beingadded all the time This book shows you how to get the most out of thedatabases you use It explains how to use SQL to solve practical prob-lems, using the most widely used SQL products, Oracle and MicrosoftAccess Oracle and Access are both widely used, easily available, and run
on personal computers By learning these two products in detail, youwill have all the basic skills to use any of the many products based onSQL
Trang 27How the Topics Are Presented
This book uses an informal conversational style to take you on a tour ofSQL topics Oracle and Access are placed side by side doing the sametasks, so you can see their similarities and differences Most topics areillustrated with an example of SQL code I have intentionally kept thetables small in these examples, which makes them easy to check andunderstand
Each example of SQL code begins by setting a task Then the SQL code
is given that performs that task Whenever possible, I wrote the SQLcode so that it works in both Oracle and Access However, sometimes Icould not do that, so I wrote one version of SQL code for Oracle and adifferent version for Access
To make this book easier to read, each example of SQL shows the ning and ending data table(s) This allows you to check that you under-stand what the SQL is doing I have tried to make these examples small
begin-so they are easy to check
Each example is often followed by notes to explain any subtle pointsabout the SQL code or the data tables
Finally, I give you a problem to solve to check your understanding of thetopic You can decide if you want to do these problems or not Usuallythey are fairly easy and require only a small modification of the SQLcode in the example If you decide to do a problem, the Web site willallow you to determine if your solution is correct
Each example of SQL code in this book is designed to be independentand stand on its own, without needing any changes performed in previ-ous sections This allows you to skip around in the book and read thesections in any order you want Some people may want to read the bookfrom beginning to end, but it is not necessary to do this
Be sure to look at the appendices for practical tips on how to run Oracleand Access The database files and the code for all the examples areavailable from the Web site In several places throughout this book, Ihave expressed opinions about computer technology, something thatmany other technical books avoid doing These opinions are my own and
I take full responsibility for them I also reserve the right to change mymind If I do so, I will put my revised opinion, and the reasons that havecaused me to change my thinking, on the Web site for this book
Trang 28The Companion Web Site
The companion Web site for this book is a Google group called “sqlfun.”The group Web address is:
http://groups.google.com/group/sqlfun
You can also send e-mail to me at:
sqlfun@gmail.com
This Web site contains:
■ Oracle SQL code to build all the data tables used in this book
■ Access databases with all the data tables used in this book bases are available for several versions of Access
Data-■ Ways to check your answers to problems in the book
■ A list of corrections, if there are any
■ An open area for discussions, your comments, and questions youwant me to answer
I invite you to come visit the Web site!
Acknowledgments
Many people contributed greatly to this book I would like to thank themfor all the support they have given me during the time I was writing it.Their ideas and feedback have improved the quality of the material andthe way I present it In particular, I want to thank the following people fortheir suggestions and help with this third edition:
■ Dejang Liu
■ Alma Lynn Bane
People who helped with the previous editions include:
■ Anila Manning, for much help in writing the second edition
■ Paul Reavis, who taught this course with me at UC Berkeley Extension
Trang 29■ Todd Matson, who reviewed the Access material.
■ Faysal Shaarani and Bill Allaway, who reviewed the Oracle material
■ Spencer Brucker and the UC Berkeley Extension, who have supported
me in teaching the SQL Fundamentals course and developing thematerial in this book
■ All the folks at Prentice Hall, especially Bernard Goodwin, editor;Vanessa Moore, Moore Media, Inc., production editor; MichaelMeehan and Jeffery Pepper, the original editors for this book; and themany other people with whom I never worked directly
■ Thanks especially to my mom, Jean Praninskas, and to my son, ard Watts, who also reviewed this book
Rich-Thanks also to Brian Akitoye, Mehran Ansari, Asa Ashraf, Anne Bester,Sandra Bush, Connie Chong, Patricia Cleveland, Robert D’Antony, GanDavnarrain, Bruce Douglass, James Drummond, Ron Duckworth, DeanEvans, Steve Fajardo, Earl Gardner, Wolday Gebremichael, NeelamHasni, Reda Ismail, Marques Junior, John Karsnak, Allyson Kinney, Gla-dys Lattier, Brian Lester, Mahen Luximan, Alex McDougall, E Muljadi,Satyendra Narayan, Bade Oyebamiji, Stefan Pantazi, Todd Perchert,Oxana Rakova, Jacob Relles, Ricardo Ribeiro, Cindy Roberts, JohnRusk, Ty Seward, Gary Shapiro, David Smith, Kenneth Smith, JoanSpasyk, Patricia Warfel, and William White
Trang 30In relational databases, all the data is stored in tables and all
the results are expressed in tables In this chapter, we examine
tables in detail
Trang 311-2 What is a relational database and why would you use one? 4 1-3 Why learn SQL? 6 1-4 What is in this book? 8
The Parts of a Table 9
1-5 Data is stored in tables 10 1-6 A row represents an object and the information about it 11 1-7 A column represents one type of information .12 1-8 A cell is the smallest part of a table 14 1-9 Each cell should express just one thing 15 1-10 Primary key columns identify each row 16 1-11 Most tables are tall and thin .18
Examples of Tables 19
1-12 An example of a table in Oracle and Access 19 1-13 Some design decisions in the l_employees table 22 1-14 The Lunches database 23
Key Points 30
Trang 321-1 What is SQL?
The name SQL stands for Structured Query Language It is pronounced
“S-Q-L” and can also be pronounced “sequel.”
SQL is a computer language designed to get information from data that isstored in a relational database In a moment, I discuss what a relationaldatabase is For now, you can think of it as one method of organizing alarge amount of data on a computer SQL allows you to find the informa-tion you want from a vast collection of data The purpose of this book is toshow you how to get the information you want from a database
SQL is different from most other computer languages With SQL, youdescribe the type of information you want The computer then determinesthe best procedure to use to obtain it and runs that procedure This is
called a declarative computer language because the focus is on the result:
You specify what the result should look like The computer is allowed touse any method of processing as long as it obtains the correct result
Most other computer languages are procedural These are languages like C,
Cobol, Java, Assembler, Fortran, Visual Basic, and others In these guages, you describe the procedure that will be applied to the data; you donot describe the result The result is whatever emerges from applying theprocedure to the data
lan-Let me use an analogy to compare these two approaches Suppose I go to acoffee shop in the morning With the declarative approach, used by SQL, I
can say what I want: “I would like a cup of coffee and a donut.” With the cedural approach, I cannot say that I have to say how the result can be
pro-obtained and give a specific procedure for it That is, I have to say how tomake a cup of coffee and how to make a donut So, for the coffee, I have tosay, “Grind up some roasted coffee beans, add boiling water to them, allowthe coffee to brew, pour it into a cup, and give it to me.” For the donut, I willhave to read from a cookbook Clearly, the declarative approach is muchcloser to the way we usually speak and it is much easier for most people touse
The fact that SQL is easy to use, relative to most other computer guages, is the main reason it is so popular and important The claim isoften made that anyone can learn SQL in a day or two I think that claim ismore a wish than a reality After all, SQL is a computer language, and com-puters are not as easy to use as telephones — at least not yet
Trang 33lan-Nonetheless, SQL is easy to use With one day of training, most people canlearn to obtain much useful information That includes people who are notprogrammers People throughout an organization, from secretaries to vicepresidents, can use SQL to obtain the information they need to make busi-ness decisions That is the hope and, to a large extent, it has been proventrue.
Information is not powerful by itself It only becomes powerful when it isavailable to people throughout an organization when they need to use it.SQL is a tool for delivering that information
Notes about SQL
■ SQL is the designated language for getting information from a relational database
■ SQL says what information to get, rather than how to get it.
■ Basic SQL is easy to learn
■ SQL empowers people by giving them control over information
■ SQL allows people to handle information in new ways
■ SQL makes information powerful by bringing it to people when theyneed it
1-2 What is a relational database
and why would you use one?
A relational database is one way to organize data in a computer There are
other ways to organize it, but in this book, we do not discuss these otherways, except to say that each method has some strengths and some draw-backs For now, we look only at the advantages a relational database has tooffer
SQL is one of the main reasons to organize data into a relational database.Using SQL, information can be obtained from the data fairly easily by peo-ple throughout the organization That is very important
Another reason is that data in a relational database can be used by manypeople at the same time Sometimes hundreds or thousands of people canall share the data in a database All the people can see the data and changethe data (if they have the authority to do so) From a business perspective,this provides a way to coordinate all the employees and have everybodyworking from the same body of information
Trang 34A third reason is that a relational database is designed with the tion that your information requirements may change over time You mightneed to reorganize the information you have or add new pieces of informa-tion to it Relational databases are designed to make this type of changeeasy Most other computer systems are difficult to change They assumethat you know what all the requirements will be before you start to con-struct them My experience is that people are not very good at predictingthe future, even when they say they can, but here I am showing my own biastoward relational databases.
expecta-From the perspective of a computer programmer, the flexibility of a tional database and the availability of SQL make it possible to develop newcomputer applications much more rapidly than with traditional tech-niques Some organizations take advantage of this; others do not
rela-The idea of a relational database was first developed in the early 1970s tohandle very large amounts of data — millions of records At first, the rela-tional database was thought of as a back-end processor that would provideinformation to a computer application written in a procedural languagesuch as C or Cobol Even now, relational databases bear some of the traits
of that heritage
Today, however, the ideas have been so successful that entire informationsystems are often constructed as relational databases, without much needfor procedural code (except to support input forms) That is, the ideas thatwere originally developed to play a supporting role for procedural codehave now taken center stage Much of the procedural code is no longerneeded
In relational databases, all the data is kept in tables, which aretwo-dimensional structures with columns and rows I describe tables indetail later in this chapter After you work with them for a while, you willfind that tables provide a very useful structure for handling data Theyadapt easily to changes, they share data with all users at the same time,and SQL can be run on the data in a table Many people start thinking oftheir data in terms of tables Tables have become the metaphor of choicewhen working with data
Today, people use small personal databases to keep their address books,catalog their music, organize their libraries, or track their finances Busi-ness applications are also built as relational databases Many people pre-fer to have their data in a database, even if it has only a few records in it
Trang 35The beginning of relational databases
■ Relational databases were originally developed in the 1970s to organizelarge amounts of information in a consistent and coherent manner
■ They allowed thousands of people to work with the same information
at the same time
■ They kept the information current and consistent at all times
■ They made information easily available to people at all levels of anorganization, from secretaries to vice presidents They used SQL,forms, standardized reports, and ad-hoc reports to deliver informa-tion to people in a timely manner
■ They were designed to work as an information server back end Thismeans that most people would not work directly with the database;instead, they would work with another layer of software This othersoftware would get the information from the database and then adapt
it to the needs of each person
■ They empowered people by making current information available tothem when they needed to use it
Today — How relational databases have changed
■ In addition to the large databases described already, now there arealso many smaller databases that handle much smaller amounts ofinformation These databases can be used by a single person orshared by a few people
■ Databases have been so successful and are so easy to use that theyare now employed for a wider range of applications than they wereoriginally designed for
■ Many people now work directly with a database instead of throughanother layer of software
■ Many people prefer to keep their data in databases They feel thatrelational databases provide a useful and efficient framework for han-dling all types of data
1-3 Why learn SQL?
SQL is used in more than 100 software products Once you learn SQL, youwill be able to use all of these products Of course, each one will require alittle study of its special features, but you will soon feel at home with it andknow how to use it You can use this one set of skills over and over again
Trang 36Adabas DGreenplum DatabaseHSQLDB
Alpha_FiveOne$DBScimoreDBPervasive PSQLGladius DBDaffodil databasesolidDB
(and many more)
Trang 37There are reasons SQL is used so much One reason is that it is easy tolearn, relative to many other computer languages Another reason is that itopens the door to relational databases and the many advantages they offer.Some people say that SQL is the best feature of relational databases and it
is what makes them successful Other people say that relational databasesmake SQL successful Most people agree that together they are a winningteam
SQL is the most successful declarative computer language — a languagewith which you say what you want rather than how to get it There are someother declarative languages and report-generation tools, but most of themare much more limited in what they can do SQL is more powerful and can
be applied in more situations
SQL can help you get information from a database that may not be able to people who do not know SQL It can help you learn and understandthe many products that are based on it
avail-Finally (don’t tell your boss), learning SQL can be enjoyable and fun It canstretch your mind and give you new tools with which to think You mightstart to view some things from a new perspective
1-4 What is in this book?
The subject of this book
This book shows you how to use SQL to get information from a relationaldatabase It begins with simple queries that retrieve selected data from asingle table It progresses step by step to advanced queries that summarizethe data, combine it with data from other tables, or display the data in spe-cialized ways It goes beyond the basics and shows you how to get theinformation you need from the databases you have
Who should read this book?
Anyone with an interest in getting information from a database can readthis book It can be a first book about databases for people who are new tothe subject You do not need to be a computer programmer The discussionbegins at the beginning and it does not assume any prior knowledge aboutdatabases The only thing you need is the persistence to work through theexamples and a little prior experience working with your own computer
Trang 38Professional programmers can also use this book The techniques shownhere can help them find solutions to many problems Whether you are anovice or a professional, an end user or a manager, the SQL skills you learnwill be useful to you over and over again.
Organization of this book
This book discusses the practical realities of getting information from adatabase A series of specific tasks are accomplished and discussed Eachconcept is presented with an example
The tasks are designed and arranged to show the most important aspects ofthe subject Each topic is discussed thoroughly and in an organized manner.All the major features and surprising aspects of each topic are shown
Why compare two different implementations
of SQL — Oracle and Access?
If a book discusses only the theory of SQL, and no particular product thatimplements it, the reader will be left with no practical skills He or she will
be able to think about the concepts, but might have difficulty writing codethat works
If a book discusses only one implementation of SQL, it is easy to get tracted by the quirks and special features it has You also lose sight of thefact that SQL is used in many products, although in slightly different ways.This book compares Oracle and Access because they are two of the mostwidely used SQL products and because they both run on a PC They aresomewhat different You will see them side by side Oracle is used mostlyfor larger business applications Access is used mostly for personal data-base applications and smaller business applications
dis-The Parts of a Table
SQL always deals with data that is in tables You probably understandtables already on an informal level The tables used in a relational data-base have a few unusual features Because computers need precise defini-tions, the description of a table must be formalized In this section, I definewhat a table is and what its parts are
Trang 391-5 Data is stored in tables
In a relational database, all the data is stored in tables A table is a
two-dimensional structure that has columns and rows Using more tional computer terminology, the columns are called fields and the rows are called records You can use either terminology.
tradi-Most people are familiar with seeing information in tables Bus schedulesare usually presented in tables Newspapers use tables to list stock values
We all know how to use these tables They are a good way to present a lot ofinformation in a very condensed format The tables in a relational databaseare very similar to these tables, which we all understand and use every day.All the information in a relational database is kept in tables There is noother type of container to keep it in — there are no other data structures.Even the most complex information is stored in tables Someone once saidthat there are three types of data structures in a relational database: tables,tables, and tables In a relational database, we have nothing but tables;there are no numbers, no words, no letters, and no dates unless they arestored in a table
You might think that this restricts what a relational database can do andthe data it can represent Is it a limitation? The answer is no All data iscapable of being represented in this format Sometimes you have to dosome work to put it in this format It doesn’t always just fall into this format
by itself But you can always succeed at putting data into tables, no matterhow complex the data is This has been proven in mathematics The proof
is long and complex and I do not show it to you here, but you can have fidence that tables are versatile enough to handle all types of data
con-The following two depictions show a basic table structure and how a tablemight store information
A conceptual diagram of a table
Trang 40An example of a table that stores information about children.
Each row contains information about one child Each column contains onetype of information for all the children As always, this table contains only alimited amount of information about each child It does not say, forinstance, how much each child weighs
■ In a relational database, all the data is stored in tables
■ A table has two dimensions called columns and rows
■ Tables can hold even the most complex information
■ All operations begin with tables and end with tables All the data isrepresented in tables
1-6 A row represents an object
and the information about it
Each row of a table represents one object, event, or relationship I callthem all objects for now, so I do not have to keep repeating the phrase
“object, event, or relationship.”
All the rows within a table represent the same type of object If you have 100doctors in a hospital, you might keep all the information about them in asingle table If you also want to keep information about 1,000 patients whoare in the hospital, you would use a separate table for that information
Notes