Learning SQL 2nd Edition Alan Beaulieu download
Learning SQL 2nd Edition Alan Beaulieu download
download
https://ebookfinal.com/download/learning-sql-2nd-edition-alan-
beaulieu/
https://ebookfinal.com/download/learning-sql-1st-edition-alan-
beaulieu/
https://ebookfinal.com/download/murach-s-oracle-sql-and-pl-sql-for-
developers-2nd-edition-joel-murach/
https://ebookfinal.com/download/beginning-t-sql-2012-2nd-edition-
scott-shaw/
Database Systems Using Oracle A Simplified Guide to SQL
and PL SQL 2nd Edition Nilesh Shah
https://ebookfinal.com/download/database-systems-using-oracle-a-
simplified-guide-to-sql-and-pl-sql-2nd-edition-nilesh-shah/
https://ebookfinal.com/download/sql-a-beginner-s-guide-2nd-edition-
robert-sheldon/
https://ebookfinal.com/download/sql-injection-attacks-and-defense-2nd-
ed-edition-clarke/
https://ebookfinal.com/download/impact-techniques-for-therapists-1st-
edition-danie-beaulieu/
PROC SQL Beyond the Basics Using SAS 2nd edition Edition
Lafler
https://ebookfinal.com/download/proc-sql-beyond-the-basics-using-
sas-2nd-edition-edition-lafler/
Learning SQL 2nd Edition Alan Beaulieu Digital Instant
Download
Author(s): Alan Beaulieu
ISBN(s): 9780596555580, 059655558X
Edition: 2
File Details: PDF, 2.10 MB
Year: 2009
Language: english
SECOND EDITION
Learning SQL
Alan Beaulieu
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://safari.oreilly.com). For more information, contact our corporate/
institutional sales department: (800) 998-9938 or [email protected].
Printing History:
August 2005: First Edition.
April 2009: Second Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Learning SQL, the image of an Andean marsupial tree frog, and related trade dress
are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
TM
ISBN: 978-0-596-52083-0
[M]
1239115419
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. A Little Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Introduction to Databases 1
Nonrelational Database Systems 2
The Relational Model 4
Some Terminology 6
What Is SQL? 7
SQL Statement Classes 7
SQL: A Nonprocedural Language 9
SQL Examples 10
What Is MySQL? 12
What’s in Store 13
iii
Column Value Violations 37
Invalid Date Conversions 37
The Bank Schema 38
3. Query Primer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Query Mechanics 41
Query Clauses 43
The select Clause 43
Column Aliases 46
Removing Duplicates 47
The from Clause 48
Tables 49
Table Links 51
Defining Table Aliases 52
The where Clause 52
The group by and having Clauses 54
The order by Clause 55
Ascending Versus Descending Sort Order 57
Sorting via Expressions 58
Sorting via Numeric Placeholders 59
Test Your Knowledge 60
4. Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Condition Evaluation 63
Using Parentheses 64
Using the not Operator 65
Building a Condition 66
Condition Types 66
Equality Conditions 66
Range Conditions 68
Membership Conditions 71
Matching Conditions 73
Null: That Four-Letter Word 76
Test Your Knowledge 79
iv | Table of Contents
Self-Joins 93
Equi-Joins Versus Non-Equi-Joins 94
Join Conditions Versus Filter Conditions 96
Test Your Knowledge 97
Table of Contents | v
Generating Rollups 152
Group Filter Conditions 155
Test Your Knowledge 156
9. Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
What Is a Subquery? 157
Subquery Types 158
Noncorrelated Subqueries 159
Multiple-Row, Single-Column Subqueries 160
Multicolumn Subqueries 165
Correlated Subqueries 167
The exists Operator 169
Data Manipulation Using Correlated Subqueries 170
When to Use Subqueries 171
Subqueries As Data Sources 172
Subqueries in Filter Conditions 177
Subqueries As Expression Generators 177
Subquery Wrap-up 181
Test Your Knowledge 181
vi | Table of Contents
12. Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Multiuser Databases 217
Locking 217
Lock Granularities 218
What Is a Transaction? 219
Starting a Transaction 220
Ending a Transaction 221
Transaction Savepoints 223
Test Your Knowledge 225
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Programming languages come and go constantly, and very few languages in use today
have roots going back more than a decade or so. Some examples are Cobol, which is
still used quite heavily in mainframe environments, and C, which is still quite popular
for operating system and server development and for embedded systems. In the data-
base arena, we have SQL, whose roots go all the way back to the 1970s.
SQL is the language for generating, manipulating, and retrieving data from a relational
database. One of the reasons for the popularity of relational databases is that properly
designed relational databases can handle huge amounts of data. When working with
large data sets, SQL is akin to one of those snazzy digital cameras with the high-power
zoom lens in that you can use SQL to look at large sets of data, or you can zoom in on
individual rows (or anywhere in between). Other database management systems tend
to break down under heavy loads because their focus is too narrow (the zoom lens is
stuck on maximum), which is why attempts to dethrone relational databases and SQL
have largely failed. Therefore, even though SQL is an old language, it is going to be
around for a lot longer and has a bright future in store.
ix
Why Use This Book to Do It?
The SQL language is broken into several categories. Statements used to create database
objects (tables, indexes, constraints, etc.) are collectively known as SQL schema state-
ments. The statements used to create, manipulate, and retrieve the data stored in a
database are known as the SQL data statements. If you are an administrator, you will
be using both SQL schema and SQL data statements. If you are a programmer or report
writer, you may only need to use (or be allowed to use) SQL data statements. While
this book demonstrates many of the SQL schema statements, the main focus of this
book is on programming features.
With only a handful of commands, the SQL data statements look deceptively simple.
In my opinion, many of the available SQL books help to foster this notion by only
skimming the surface of what is possible with the language. However, if you are going
to work with SQL, it behooves you to understand fully the capabilities of the language
and how different features can be combined to produce powerful results. I feel that this
is the only book that provides detailed coverage of the SQL language without the added
benefit of doubling as a “door stop” (you know, those 1,250-page “complete referen-
ces” that tend to gather dust on people’s cubicle shelves).
While the examples in this book run on MySQL, Oracle Database, and SQL Server, I
had to pick one of those products to host my sample database and to format the result
sets returned by the example queries. Of the three, I chose MySQL because it is freely
obtainable, easy to install, and simple to administer. For those readers using a different
server, I ask that you download and install MySQL and load the sample database so
that you can run the examples and experiment with the data.
x | Preface
Chapter 6, Working with Sets, is all about data sets and how they can interact within
queries.
Chapter 7, Data Generation, Conversion, and Manipulation, demonstrates several
built-in functions used for manipulating or converting data.
Chapter 8, Grouping and Aggregates, shows how data can be aggregated.
Chapter 9, Subqueries, introduces the subquery (a personal favorite) and shows
how and where they can be utilized.
Chapter 10, Joins Revisited, further explores the various types of table joins.
Chapter 11, Conditional Logic, explores how conditional logic (i.e., if-then-else)
can be utilized in select, insert, update, and delete statements.
Chapter 12, Transactions, introduces transactions and shows how to use them.
Chapter 13, Indexes and Constraints, explores indexes and constraints.
Chapter 14, Views, shows how to build an interface to shield users from data
complexities.
Chapter 15, Metadata, demonstrates the utility of the data dictionary.
Appendix A, ER Diagram for Example Database, shows the database schema used
for all examples in the book.
Appendix B, MySQL Extensions to the SQL Language, demonstrates some of the
interesting non-ANSI features of MySQL’s SQL implementation.
Appendix C, Solutions to Exercises, shows solutions to the chapter exercises.
Preface | xi
Indicates a tip, suggestion, or general note. For example, I use notes to
point you to useful new features in Oracle9i.
Indicates a warning or caution. For example, I’ll tell you if a certain SQL
clause might have unintended consequences if not used carefully.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
O’Reilly maintains a web page for this book, which lists errata, examples, and any
additional information. You can access this page at:
http://www.oreilly.com/catalog/9780596520830
To comment or ask technical questions about this book, send email to:
[email protected]
For more information about O’Reilly books, conferences, Resource Centers, and the
O’Reilly Network, see the website at:
http://www.oreilly.com
xii | Preface
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at [email protected].
Acknowledgments
I would like to thank my editor, Mary Treseler, for helping to make this second edition
a reality, and many thanks to Kevin Kline, Roy Owens, Richard Sonen, and Matthew
Russell, who were kind enough to review the book for me over the Christmas/New
Year holidays. I would also like to thank the many readers of my first edition who were
kind enough to send questions, comments, and corrections. Lastly, I thank my wife,
Nancy, and my daughters, Michelle and Nicole, for their encouragement and
inspiration.
Preface | xiii
CHAPTER 1
A Little Background
Before we roll up our sleeves and get to work, it might be beneficial to introduce some
basic database concepts and look at the history of computerized data storage and
retrieval.
Introduction to Databases
A database is nothing more than a set of related information. A telephone book, for
example, is a database of the names, phone numbers, and addresses of all people living
in a particular region. While a telephone book is certainly a ubiquitous and frequently
used database, it suffers from the following:
• Finding a person’s telephone number can be time-consuming, especially if the
telephone book contains a large number of entries.
• A telephone book is indexed only by last/first names, so finding the names of the
people living at a particular address, while possible in theory, is not a practical use
for this database.
• From the moment the telephone book is printed, the information becomes less and
less accurate as people move into or out of a region, change their telephone num-
bers, or move to another location within the same region.
The same drawbacks attributed to telephone books can also apply to any manual data
storage system, such as patient records stored in a filing cabinet. Because of the cum-
bersome nature of paper databases, some of the first computer applications developed
were database systems, which are computerized data storage and retrieval mechanisms.
Because a database system stores data electronically rather than on paper, a database
system is able to retrieve data more quickly, index data in multiple ways, and deliver
up-to-the-minute information to its user community.
Early database systems managed data stored on magnetic tapes. Because there were
generally far more tapes than tape readers, technicians were tasked with loading and
unloading tapes as specific data was requested. Because the computers of that era had
very little memory, multiple requests for the same data generally required the data to
1
be read from the tape multiple times. While these database systems were a significant
improvement over paper databases, they are a far cry from what is possible with today’s
technology. (Modern database systems can manage terabytes of data spread across
many fast-access disk drives, holding tens of gigabytes of that data in high-speed mem-
ory, but I’m getting a bit ahead of myself.)
Over the first several decades of computerized database systems, data was stored and
represented to users in various ways. In a hierarchical database system, for example,
data is represented as one or more tree structures. Figure 1-1 shows how data relating
to George Blake’s and Sue Smith’s bank accounts might be represented via tree
structures.
Credit of $77.86
on 2004-04-04
Transactions
George and Sue each have their own tree containing their accounts and the transactions
on those accounts. The hierarchical database system provides tools for locating a par-
ticular customer’s tree and then traversing the tree to find the desired accounts and/or
Debit of $100.00
Checking on 2004-01-22
Checking
George Blake Credit of $25.00
on 2004-02-05
Savings
Debit of $250.00
on 2004-03-09 Savings
Debit of $1000.00
on 2004-03-25
Checking MoneyMkt
Credit of $138.50
on 2004-04-02
Sue Smith MoneyMkt
Credit of $77.86
on 2004-04-04
Line of credit Line of credit
Debit of $500.00
on 2004-03-27
In order to find the transactions posted to Sue’s money market account, you would
need to perform the following steps:
1. Find the customer record for Sue Smith.
2. Follow the link from Sue Smith’s customer record to her list of accounts.
3. Traverse the chain of accounts until you find the money market account.
4. Follow the link from the money market record to its list of transactions.
One interesting feature of network database systems is demonstrated by the set of
product records on the far right of Figure 1-2. Notice that each product record (Check-
ing, Savings, etc.) points to a list of account records that are of that product type.
Account records, therefore, can be accessed from multiple places (both customer records
and product records), allowing a network database to act as a multiparent hierarchy.
Introduction to Databases | 3
Both hierarchical and network database systems are alive and well today, although
generally in the mainframe world. Additionally, hierarchical database systems have
enjoyed a rebirth in the directory services realm, such as Microsoft’s Active Directory
and the Red Hat Directory Server, as well as with Extensible Markup Language (XML).
Beginning in the 1970s, however, a new way of representing data began to take root,
one that was more rigorous yet easy to understand and implement.
Customer Account
cust_id fname lname account_id product_cd cust_id balance
1 George Blake 103 CHK 1 $75.00
106 MM 2 $500.00
107 LOC 2 0
Product Transaction
product_cd name txn_id txn_type_cd account_id amount date
CHK Checking 978 DBT 103 $100.00 2004-01-22
There are four tables in Figure 1-3 representing the four entities discussed so far:
customer, product, account, and transaction. Looking across the top of the customer
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com