(Ebook) SQL queries for mere mortals: a hands-on guide
to data manipulation in SQL by John L. Viescas; Michael
J. Hernandez ISBN 9780321992475, 9782014939439,
0321992474, 2014939438 Pdf Download
https://ebooknice.com/product/sql-queries-for-mere-mortals-a-hands-
on-guide-to-data-manipulation-in-sql-22041684
★★★★★
4.7 out of 5.0 (89 reviews )
DOWNLOAD PDF
ebooknice.com
(Ebook) SQL queries for mere mortals: a hands-on guide to
data manipulation in SQL by John L. Viescas; Michael J.
Hernandez ISBN 9780321992475, 9782014939439, 0321992474,
2014939438 Pdf Download
EBOOK
Available Formats
■ PDF eBook Study Guide Ebook
EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME
INSTANT DOWNLOAD VIEW LIBRARY
We believe these products will be a great fit for you. Click
the link to download now, or visit ebooknice.com
to discover even more!
(Ebook) SQL queries for mere mortals: a hands-on guide to data
manipulation in SQL by John L. Viescas; Michael J. Hernandez
ISBN 9780321992475, 0321992474
https://ebooknice.com/product/sql-queries-for-mere-mortals-a-hands-on-
guide-to-data-manipulation-in-sql-11656444
(Ebook) SQL Queries for Mere Mortals: A Hands-on Guide to Data
Manipulation in SQL [For Mere Mortals Series] by John L.
Viescas, Michael J. Hernandez ISBN 9780321444431, 0321444434
https://ebooknice.com/product/sql-queries-for-mere-mortals-a-hands-on-
guide-to-data-manipulation-in-sql-for-mere-mortals-series-983804
(Ebook) SQL Queries for Mere Mortals: A Hands-On Guide to Data
Manipulation in SQL 4th edition by John L. Viescas ISBN
9780134858333, 0134858336
https://ebooknice.com/product/sql-queries-for-mere-mortals-a-hands-on-
guide-to-data-manipulation-in-sql-4th-edition-6971276
(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles,
James ISBN 9781459699816, 9781743365571, 9781925268492,
1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
(Ebook) Effective SQL: 61 Specific Ways to Write Better SQL by
John L. Viescas & Douglas J. Steele & Ben G. Clothier ISBN
9780134579078, 0134579070
https://ebooknice.com/product/effective-sql-61-specific-ways-to-write-
better-sql-38442488
(Ebook) Database Design for Mere Mortals: 25th Anniversary
Edition, 4th Edition by Michael J. Hernandez ISBN 9780136788041,
0136788041
https://ebooknice.com/product/database-design-for-mere-mortals-25th-
anniversary-edition-4th-edition-44583140
(Ebook) Database Design for Mere Mortals: 25th Anniversary
Edition, 4th Edition by Michael J. Hernandez ISBN 9780136788133,
0136788130
https://ebooknice.com/product/database-design-for-mere-mortals-25th-
anniversary-edition-4th-edition-32704120
(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans
Heikne, Sanna Bodemyr ISBN 9789127456600, 9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312
(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II
Success) by Peterson's ISBN 9780768906677, 0768906679
https://ebooknice.com/product/sat-ii-success-math-1c-and-2c-2002-peterson-
s-sat-ii-success-1722018
About This eBook
ePUB is an open, industry-standard format for eBooks. However, support of ePUB
and its many features varies across reading devices and applications. Use your
device or app settings to customize the presentation to your liking. Settings that you
can customize often include font, font size, single or double column, landscape or
portrait mode, and figures that you can click or tap to enlarge. For additional
information about the settings and features on your reading device or app, visit the
device manufacturer’s Web site.
Many titles include programming code or configuration examples. To optimize the
presentation of these elements, view the eBook in single-column, landscape mode
and adjust the font size to the smallest setting. In addition to presenting code and
configurations in the reflowable text format, we have included images of the code
that mimic the presentation found in the print book; therefore, where the reflowable
format may compromise the presentation of the code listing, you will see a “Click
here to view code image” link. Click the link to view the print-fidelity code image.
To return to the previous page viewed, click the Back button on your device or app.
SQL Queries for Mere Mortals®
Third Edition
A Hands-On Guide to Data Manipulation in SQL
John L. Viescas
Michael J. Hernandez
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco •
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
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 the publisher was aware of a trademark claim, the designations have been
printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make
no expressed or implied warranty 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.
For information about buying this title in bulk quantities, or for special sales
opportunities (which may include electronic versions; custom cover designs; and
content particular to your business, training goals, marketing focus, or branding
interests), please contact our corporate sales department at
[email protected] or (800) 382-3419.
For government sales inquiries, please contact
[email protected].
For questions about sales outside the U.S., please contact
[email protected].
Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2014939438
Copyright © 2014 John L. Viescas and Michael J. Hernandez
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.
To obtain permission to use material from this work, please submit a written request
to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle
River, New Jersey 07458, or you may fax your request to (201) 236-3290.
ISBN-13: 978-0-321-99247-5
ISBN-10: 0-321-99247-4
Text printed in the United States on recycled paper at Edwards Brothers Malloy, Ann
Arbor, Michigan.
Fourth Printing: June 2015
Associate Publisher: Dave Dusthimer
Acquisitions Editor: Joan Murray
Senior Development Editor: Chris Cleveland
Managing Editor: Sandra Schroeder
Senior Project Editor: Tonya Simpson
Copy Editor: Charlotte Kughen
Indexer: Lisa Stumpf
Proofreader: Anne Goebel
Technical Reviewer: Dale Wallentine
Editorial Assistant: Vanessa Evans
Cover Designer: Alan Clements
Compositor: Trina Wurst
Praise for SQL Queries for Mere Mortals®,
Third Edition
The good books show you how to do something. The great books enable you to
think clearly about how you can do it. This book is the latter. To really maximize
the potential of your database, thinking about data as a set is required and the
authors’ accessible writing really brings out the practical applications of SQL
and the set-based thinking behind it.
— Ben Clothier, Lead Developer at IT Impact, Inc., co-author of
Professional
Access 2013 Programming, and Microsoft Access MVP
Unless you are working at a very advanced level, this is the only SQL book you
will ever need. The authors have taken the mystery out of complex queries and
explained principles and techniques with such clarity that a “Mere Mortal” will
indeed be empowered to perform the superhuman. Do not walk past this book!
— Graham Mandeno, Database Consultant
It’s beyond brilliant! I have been working with SQL for a really long time and
the techniques presented in this book exposed some of the bad habits I picked up
over the years in my learning process. I wish I had learned these techniques a
long time ago and saved myself all the headaches of learning SQL the hard way.
Who said you can’t teach old dogs new tricks?
— Leo (theDBguy), Utter Access Moderator and Microsoft Access MVP
I learned SQL primarily from the first and second editions of this book, and I am
pleased to see a third edition of this book so that others can continue to benefit
from its organized presentation of the language. Starting from how to design
your tables so that SQL can be effective (a common problem for database
beginners), and then continuing through the various aspects of SQL construction
and capabilities, the reader can become a moderate expert upon completing the
book and its samples. Learning how to convert a question in English into a
meaningful SQL statement will greatly facilitate your mastery of the language.
Numerous examples from real life will help you visualize how to use SQL to
answer the questions about the data in your database. Just one of the “watch out
for this trap” items will save you more than the cost of the book when you avoid
that problem when writing your queries. I highly recommend this book if you
want to tap the full potential of your database.
— Kenneth D. Snell, Ph.D., Database Designer/Programmer
I don’t think they do this in public schools any more, and it is a shame, but do
you remember in the seventh and eighth grades when you learned to diagram a
sentence? Those of you who do may no longer remember how you did it, but all
of you do write better sentences because of it. John Viescas and Mike Hernandez
must have remembered because they take everyday English queries and literally
translate them into SQL. This is an important book for all database designers. It
takes the complexity of mathematical Set Theory and of First Order Predicate
Logic, as outlined in E. F. Codd’s original treatise on relational database design,
and makes it easy for anyone to understand. If you want an elementary through
intermediate-level course on SQL, this is the one book that is a requirement, no
matter how many others you buy.
— Arvin Meyer, MCP, MVP
SQL Queries for Mere Mortals, Third Edition, provides a step-by-step, easy-to-
read introduction to writing SQL queries. It includes hundreds of examples with
detailed explanations. This book provides the tools you need to understand,
modify, and create SQL queries.
— Keith W. Hare, Convenor, ISO/IEC JTC1 SC32 WG3
— the International SQL Standards Committee
Even in this day of wizards and code generators, successful database developers
still require a sound knowledge of Structured Query Language (SQL, the
standard language for communicating with most database systems). In this book,
John and Mike do a marvelous job of making what’s usually a dry and difficult
subject come alive, presenting the material with humor in a logical manner, with
plenty of relevant examples. I would say that this book should feature
prominently in the collection on the bookshelf of all serious developers, except
that I’m sure it’ll get so much use that it won’t spend much time on the shelf!
— Doug Steele, Microsoft Access Developer and author
I highly recommend SQL Queries for Mere Mortals to anyone working with
data. John makes it easy to learn one of the most critical aspects of working with
data: creating queries. Queries are the primary tool for selecting, sorting, and
reporting data. They can compensate for table structure, new reporting
requirements, and incorporate new data sources. SQL Queries for Mere Mortals
uses clear, easy to understand discussions and examples to take readers through
the basics and into complex problems. From novice to expert, you will find this
book to be an invaluable reference as you can apply the concepts to a myriad of
scenarios, regardless of the program.
— Teresa Hennig, Microsoft MVP-Access, and lead author of several
Access
books, including Professional Access 2013 Programming (Wrox)
Contents
Foreword
Preface
About the Authors
Introduction
Are You a Mere Mortal?
About This Book
What This Book Is Not
How to Use This Book
Reading the Diagrams Used in This Book
Sample Databases Used in This Book
“Follow the Yellow Brick Road”
Part I Relational Databases and SQL
Chapter 1 What Is Relational?
Types of Databases
A Brief History of the Relational Model
In the Beginning . . .
Relational Database Systems
Anatomy of a Relational Database
Tables
Fields
Records
Keys
Views
Relationships
What’s in It for You?
Where Do You Go from Here?
Summary
Chapter 2 Ensuring Your Database Structure Is Sound
Why Is This Chapter Here?
Why Worry about Sound Structures?
Fine-Tuning Fields
What’s in a Name? (Part One)
Smoothing Out the Rough Edges
Resolving Multipart Fields
Resolving Multivalued Fields
Fine-Tuning Tables
What’s in a Name? (Part Two)
Ensuring a Sound Structure
Resolving Unnecessary Duplicate Fields
Identification Is the Key
Establishing Solid Relationships
Establishing a Deletion Rule
Setting the Type of Participation
Setting the Degree of Participation
Is That All?
Summary
Chapter 3 A Concise History of SQL
The Origins of SQL
Early Vendor Implementations
“. . . And Then There Was a Standard”
Evolution of the ANSI/ISO Standard
Other SQL Standards
Commercial Implementations
What the Future Holds
Why Should You Learn SQL?
Which Version of SQL Does This Book Cover?
Summary
Part II SQL Basics
Chapter 4 Creating a Simple Query
Introducing SELECT
The SELECT Statement
A Quick Aside: Data versus Information
Translating Your Request into SQL
Expanding the Field of Vision
Using a Shortcut to Request All Columns
Eliminating Duplicate Rows
Sorting Information
First Things First: Collating Sequences
Let’s Now Come to Order
Saving Your Work
Sample Statements
Summary
Problems for You to Solve
Chapter 5 Getting More Than Simple Columns
What Is an Expression?
What Type of Data Are You Trying to Express?
Changing Data Types: The CAST Function
Specifying Explicit Values
Character String Literals
Numeric Literals
Datetime Literals
Types of Expressions
Concatenation
Mathematical Expressions
Date and Time Arithmetic
Using Expressions in a SELECT Clause
Working with a Concatenation Expression
Naming the Expression
Working with a Mathematical Expression
Working with a Date Expression
A Brief Digression: Value Expressions
That “Nothing” Value: Null
Introducing Null
The Problem with Nulls
Sample Statements
Summary
Problems for You to Solve
Chapter 6 Filtering Your Data
Refining What You See Using WHERE
The WHERE Clause
Using a WHERE Clause
Defining Search Conditions
Comparison
Range
Set Membership
Pattern Match
Null
Excluding Rows with NOT
Using Multiple Conditions
Introducing AND and OR
Excluding Rows: Take Two
Order of Precedence
Checking for Overlapping Ranges
Nulls Revisited: A Cautionary Note
Expressing Conditions in Different Ways
Sample Statements
Summary
Problems for You to Solve
Part III Working with Multiple Tables
Chapter 7 Thinking in Sets
What Is a Set, Anyway?
Operations on Sets
Intersection
Intersection in Set Theory
Intersection between Result Sets
Problems You Can Solve with an Intersection
Difference
Difference in Set Theory
Difference between Result Sets
Problems You Can Solve with Difference
Union
Union in Set Theory
Combining Result Sets Using a Union
Problems You Can Solve with Union
SQL Set Operations
Classic Set Operations versus SQL
Finding Common Values: INTERSECT
Finding Missing Values: EXCEPT (DIFFERENCE)
Combining Sets: UNION
Summary
Chapter 8 INNER JOINs
What Is a JOIN?
The INNER JOIN
What’s “Legal” to JOIN?
Column References
Syntax
Check Those Relationships!
Uses for INNER JOINs
Find Related Rows
Find Matching Values
Sample Statements
Two Tables
More Than Two Tables
Looking for Matching Values
Summary
Problems for You to Solve
Chapter 9 OUTER JOINs
What Is an OUTER JOIN?
The LEFT/RIGHT OUTER JOIN
Syntax
The FULL OUTER JOIN
Syntax
FULL OUTER JOIN on Non-Key Values
UNION JOIN
Uses for OUTER JOINs
Find Missing Values
Find Partially Matched Information
Sample Statements
Summary
Problems for You to Solve
Chapter 10 UNIONs
What Is a UNION?
Writing Requests with UNION
Using Simple SELECT Statements
Combining Complex SELECT Statements
Using UNION More Than Once
Sorting a UNION
Uses for UNION
Sample Statements
Summary
Problems for You to Solve
Chapter 11 Subqueries
What Is a Subquery?
Row Subqueries
Table Subqueries
Scalar Subqueries
Subqueries as Column Expressions
Syntax
An Introduction to Aggregate Functions: COUNT and MAX
Subqueries as Filters
Syntax
Special Predicate Keywords for Subqueries
Uses for Subqueries
Build Subqueries as Column Expressions
Use Subqueries as Filters
Sample Statements
Subqueries in Expressions
Subqueries in Filters
Summary
Problems for You to Solve
Part IV Summarizing and Grouping Data
Chapter 12 Simple Totals
Aggregate Functions
Counting Rows and Values with COUNT
Computing a Total with SUM
Calculating a Mean Value with AVG
Finding the Largest Value with MAX
Finding the Smallest Value with MIN
Using More Than One Function
Using Aggregate Functions in Filters
Sample Statements
Summary
Problems for You to Solve
Chapter 13 Grouping Data
Why Group Data?
The GROUP BY Clause
Syntax
Mixing Columns and Expressions
Using GROUP BY in a Subquery in a WHERE Clause
Simulating a SELECT DISTINCT Statement
“Some Restrictions Apply”
Column Restrictions
Grouping on Expressions
Uses for GROUP BY
Sample Statements
Summary
Problems for You to Solve
Chapter 14 Filtering Grouped Data
A New Meaning of “Focus Groups”
Where You Filter Makes a Difference
Should You Filter in WHERE or in HAVING?
Avoiding the HAVING COUNT Trap
Uses for HAVING
Sample Statements
Summary
Problems for You to Solve
Part V Modifying Sets of Data
Chapter 15 Updating Sets of Data
What Is an UPDATE?
The UPDATE Statement
Using a Simple UPDATE Expression
A Brief Aside: Transactions
Updating Multiple Columns
Using a Subquery to Filter Rows
Using a Subquery UPDATE Expression
Uses for UPDATE
Sample Statements
Summary
Problems for You to Solve
Chapter 16 Inserting Sets of Data
What Is an INSERT?
The INSERT Statement
Inserting Values
Generating the Next Primary Key Value
Inserting Data by Using SELECT
Uses for INSERT
Sample Statements
Summary
Problems for You to Solve
Chapter 17 Deleting Sets of Data
What Is a DELETE?
The DELETE Statement
Deleting All Rows
Deleting Some Rows
Uses for DELETE
Sample Statements
Summary
Problems for You to Solve
Part VI Introduction to Solving Tough Problems
Chapter 18 “NOT” and “AND” Problems
A Short Review of Sets
Sets with Multiple AND Criteria
Sets with Multiple NOT Criteria
Sets Including Some Criteria but Excluding Others
Finding Out the “Not” Case
Using OUTER JOIN
Using NOT IN
Using NOT EXISTS
Using GROUP BY/HAVING
Finding Multiple Matches in the Same Table
Using INNER JOIN
Using IN
Using EXISTS
Using GROUP BY/HAVING
Sample Statements
Summary
Problems for You to Solve
Chapter 19 Condition Testing
Conditional Expressions (CASE)
Why Use CASE?
Syntax
Solving Problems with CASE
Solving Problems with Simple CASE
Solving Problems with Searched CASE
Using CASE in a WHERE Clause
Sample Statements
Summary
Problems for You to Solve
Chapter 20 Using Unlinked Data and “Driver” Tables
What Is Unlinked Data?
Deciding When to Use a CROSS JOIN
Solving Problems with Unlinked Data
Solving Problems Using “Driver” Tables
Setting Up a Driver Table
Using a Driver Table
Sample Statements
Examples Using Unlinked Tables
Examples Using Driver Tables
Summary
Problems for You to Solve
In Closing
Appendices
A SQL Standard Diagrams
B Schema for the Sample Databases
Sales Orders Example Database
Sales Orders Modify Database
Entertainment Agency Example Database
Entertainment Agency Modify Database
School Scheduling Example Database
School Scheduling Modify Database
Bowling League Example Database
Bowling League Modify Database
Recipes Database
C Date and Time Types, Operations, and Functions
IBM DB2
Microsoft Office Access
Microsoft SQL Server
MySQL
Oracle
D Suggested Reading
Database Books
Books on SQL
Index
Foreword
In the 25 years since the database language SQL was adopted as an international
standard, and the 30 years since SQL database products appeared on the market,
SQL has become the predominant language for storing, modifying, retrieving, and
deleting data. Today, a significant portion of the world’s data—and the world’s
economy—is tracked using SQL databases.
SQL is everywhere because it is a very powerful tool for manipulating data. It is in
high-performance transaction processing systems. It is behind Web interfaces. I’ve
even found SQL in network monitoring tools and spam firewalls.
Today, SQL can be executed directly, embedded in programming languages, and
accessed through call interfaces. It is hidden inside GUI development tools, code
generators, and report writers. However visible or hidden, the underlying queries are
SQL. Therefore, to understand existing applications and to create new ones, you
need to understand SQL.
SQL Queries for Mere Mortals, Third Edition, provides a step-by-step, easy-to-read
introduction to writing SQL queries. It includes hundreds of examples with detailed
explanations. This book provides the tools you need to understand, modify, and
create SQL queries.
As a database consultant and a participant in both the U.S. and international SQL
standards committees, I spend a lot of time working with SQL. So, it is with a certain
amount of authority that I state, “The authors of this book not only understand SQL,
they also understand how to explain it.” Both qualities make this book a valuable
resource.
—Keith W. Hare, Senior Consultant,
JCC Consulting, Inc.Vice Chair, INCITS DM32.2
—the USA SQL Standards Committee; Convenor, ISO/IEC JTC1 SC32
WG3
—the International SQL Standards Committee
Preface
“Language is by its very nature a communal thing; that is, it expresses
never the exact thing but a compromise—that which is common to you, me,
and everybody.”
—Thomas Ernest Hulme, Speculations
Learning how to retrieve information from or manipulate information in a database is
commonly a perplexing exercise. However, it can be a relatively easy task as long as
you understand the question you’re asking or the change you’re trying to make to the
database. After you understand the problem, you can translate it into the language
used by any database system, which in most cases is Structured Query Language
(SQL). You have to translate your request into an SQL statement so that your
database system knows what information you want to retrieve or change. SQL
provides the means for you and your database system to communicate.
Throughout our many years as database consultants, we’ve found that the number of
people who merely need to retrieve information from a database or perform simple
data modifications in a database far outnumber those who are charged with the task
of creating programs and applications for a database. Unfortunately, no books focus
solely on this subject, particularly from a “mere mortals” viewpoint. There are
numerous good books on SQL, to be sure, but most are targeted to database
programming and development.
With this in mind, we decided it was time to write a book that would help people
learn how to query a database properly and effectively. We produced the first edition
of this book in 2000. We created a second edition in 2008 that introduced basic ways
to change data in your database using SQL. With this new edition, we stepped lightly
into the realm of tougher problems—the sorts of problems that make the heads of
even experienced users spin around three times. The result of our efforts is in your
hands. This book is unique among SQL books in that it focuses on SQL with little
regard to any one specific database system implementation. This third edition
includes hundreds of new examples, and we included versions of the sample
databases using Microsoft Office Access, Microsoft SQL Server, and the popular
open-source MySQL database system. When you finish reading this book, you’ll
have the skills you need to retrieve or modify any information you require.
Acknowledgments
Writing a book such as this is always a cooperative effort. There are always editors,
colleagues, friends, and relatives willing to lend their support and provide valuable
advice when we need it the most. These people continually provide us with
encouragement, help us to remain focused, and motivate us to see this project
through to the end.
First and foremost, we want to thank our acquisitions editor, Joan Murray, for
helping us get signed up to produce this third edition. Thanks also to Developmental
Editor Chris Cleveland for shepherding us along the way. And we can’t forget
Production Editor Tonya Simpson and the production staff—they’re a great team!
Finally, thanks to Associate Publisher David Dusthimer, who put this team together
and kept a watchful eye over the entire process.
Next, we’d like to acknowledge our technical editor, Dale Wallentine. We also had
help from some of our database friends—Jeff Boyce, Ben Clothier, Henry
Habermacher, Leo theDBGuy, and Doug Steele. Thanks once again to all of you for
your time and input and for helping us to make this a solid treatise on SQL queries.
Finally, another very special thanks to Keith Hare for providing the Foreword. As
the Convenor of the International SQL Standards Committee, Keith is an SQL expert
par excellence. We have a lot of respect for Keith’s knowledge and expertise on the
subject, and we’re pleased to have his thoughts and comments at the beginning of
our book.
About the Authors
John L. Viescas is an independent database consultant with more than 45 years of
experience. He began his career as a systems analyst, designing large database
applications for IBM mainframe systems. He spent 6 years at Applied Data Research
in Dallas, Texas, where he directed a staff of more than 30 people and was
responsible for research, product development, and customer support of database
products for IBM mainframe computers. While working at Applied Data Research,
John completed a degree in business finance at the University of Texas at Dallas,
graduating cum laude.
John joined Tandem Computers, Inc., in 1988, where he was responsible for the
development and implementation of database marketing programs in Tandem’s U.S.
Western Sales region. He developed and delivered technical seminars on Tandem’s
relational database management system, NonStop SQL. John wrote his first book, A
Quick Reference Guide to SQL (Microsoft Press, 1989), as a research project to
document the similarities in the syntax among the ANSI-86 SQL standard, IBM’s
DB2, Microsoft’s SQL Server, Oracle Corporation’s Oracle, and Tandem’s NonStop
SQL. He wrote the first edition of Running Microsoft Access (Microsoft Press, 1992)
while on sabbatical from Tandem. He has since written four editions of Running,
three editions of Microsoft Office Access Inside Out (Microsoft Press, 2003, 2007,
and 2010—the successor to the Running series), and Building Microsoft Access
Applications (Microsoft Press, 2005).
John formed his own company in 1993. He provides information systems
management consulting for a variety of small to large businesses around the world,
with a specialty in the Microsoft Access and SQL Server database management
products. He maintains offices in Nashua, New Hampshire, and Paris, France. He
has been recognized as a “Most Valuable Professional” (MVP) since 1993 by
Microsoft Product Support Services for his assistance with technical questions on
public support forums. He set a landmark 20 consecutive years as an MVP in 2013.
You can visit John’s Web site at www.viescas.com or contact him by e-mail at
[email protected].
Michael J. Hernandez has been an independent relational database consultant
specializing in relational database design. He has more than 20 years of experience
in the technology industry, developing database applications for a wide variety of
clients. He’s been a contributing author to a wide variety of magazine columns,
white papers, books, and periodicals, and is coauthor of the best-selling SQL Queries
for Mere Mortals. Mike has been a top-rated and noted technical trainer for the
government, the military, the private sector, and companies throughout the United
States. He has spoken at numerous national and international conferences, and has
consistently been a top-rated speaker and presenter.
Aside from his technical background, Mike has a diverse set of skills and interests
that he also pursues, ranging from the artistic to the metaphysical. His greatest
interest is still the guitar, as he’s been a practicing guitarist for more than 40 years
and played professionally for 15 years. He’s also a working actor, a great cook, loves
to teach (writing, public speaking, music), has a gift for bad puns, and even reads
Tarot cards.
He says he’s never going to retire, per se, but rather just change whatever it is he’s
doing whenever he finally gets tired of it and move on to something else that
interests him.
Introduction
“I presume you’re mortal, and may err.”
—James Shirley, The Lady of Pleasure
If you’ve used a computer more than casually, you have probably used Structured
Query Language or SQL—perhaps without even knowing it. SQL is the standard
language for communicating with most database systems. Any time you import data
into a spreadsheet or perform a merge into a word processing program, you’re most
likely using SQL in some form or another. Every time you go online to an e-
commerce site on the Web and place an order for a book, a recording, a movie, or
any of the dozens of other products you can order, there’s a very high probability
that the code behind the web page you’re using is accessing its databases with SQL.
If you need to get information from a database system that uses SQL, you can
enhance your understanding of the language by reading this book.
Are You a Mere Mortal?
You might ask, “Who is a mere mortal? Me?” The answer is not simple. When we
started to write this book, we thought we were experts in the database language
called SQL. Along the way, we discovered we were mere mortals, too, in several
areas. We understood a few specific implementations of SQL very well, but we
unraveled many of the complex intricacies of the language as we studied how it is
used in many commercial products. So, if you fit any of the following descriptions,
you’re a mere mortal too!
• If you use computer applications that let you access information from a
database system, you’re probably a mere mortal. The first time you don’t get
the information you expected using the query tools built in to your application,
you’ll need to explore the underlying SQL statements to find out why.
• If you have recently discovered one of the many available desktop database
applications but are struggling with defining and querying the data you need,
you’re a mere mortal.
• If you’re a database programmer who needs to “think outside of the box” to
solve some complex problems, you’re a mere mortal.
• If you’re a database guru in one product but are now faced with integrating the
data from your existing system into another system that supports SQL, you’re a
mere mortal.
In short, anyone who has to use a database system that supports SQL can use this
book. As a beginning database user who has just discovered that the data you need
can be fetched using SQL, you will find that this book teaches you all the basics and
more. For an expert user who is suddenly faced with solving complex problems or
integrating multiple systems that support SQL, this book will provide insights into
leveraging the complex abilities of the SQL database language.
About This Book
Everything you read in this book is based on the current International Organization
for Standardization (ISO) Standard for the SQL database language –
SQL/Foundation (document ISO/IEC 9075-2:2011), as currently implemented in
most of the popular commercial database systems. The ISO document was also
adopted by the American National Standards Institute (ANSI), so this is truly an
international standard. The SQL you’ll learn here is not specific to any particular
software product.
As you’ll learn in more detail in Chapter 3, “A Concise History of SQL,” the SQL
Standard defines both more and less than you’ll find implemented in most
commercial database products. Most database vendors have yet to implement many
of the more advanced features, but most do support the core of the standard.
We researched a wide range of popular products to make sure that you can use what
we’re teaching in this book. Where we found parts of the core of the language not
supported by some major products, we warn you in the text and show you alternate
ways to state your database requests in standard SQL. When we found significant
parts of the SQL Standard supported by only a few vendors, we introduced you to
the syntax and then suggested alternatives.
We have organized this book into six major sections:
• Part I, “Relational Databases and SQL,” explains how modern database
systems are based on a rigorous mathematical model and provides a brief
history of the database query language that has evolved into what we know as
SQL. We also discuss some simple rules that you can use to make sure your
database design is sound.
• Part II, “SQL Basics,” introduces you to using the SELECT statement, creating
expressions, and sorting information with an ORDER BY clause. You’ll also
learn how to filter data by using a WHERE clause.
• Part III, “Working with Multiple Tables,” shows you how to formulate queries
that draw data from more than one table. Here we show you how to link tables
in a query using the INNER JOIN, OUTER JOIN, and UNION operators, and
how to work with subqueries.
• Part IV, “Summarizing and Grouping Data,” discusses how to obtain summary
information and group and filter summarized data. Here is where you’ll learn
about the GROUP BY and HAVING clauses.
• Part V, “Modifying Sets of Data,” explains how to write queries that modify a
set of rows in your tables. In the chapters in this section, you’ll learn how to
use the UPDATE, INSERT, and DELETE statements.
• Part VI, “Introduction to Solving Tough Problems,” dips your toes into more
complex problems. In the chapters in this section, you’ll expand your horizons
to include solving complex “NOT” and “AND” problems (multiple conditions
on one table), performing logical evaluations with CASE, and thinking
“outside the box” using “unlinked” tables (Cartesian Products).
At the end of the book in the appendices, you’ll find syntax diagrams for all the SQL
elements you’ve learned, layouts of the sample databases, a list of date and time
manipulation functions implemented in five of the major database systems, and book
recommendations to further your study of SQL. You can download the five sample
databases for the three database systems (Microsoft Access, Microsoft SQL Server,
and MySQL) from www.informit.com/title/9780321992475 and clicking the
Downloads tab.
What This Book Is Not
Although this book is based on the 2011 SQL Standard that was current at the time
of this writing, it does not cover every aspect of the standard. In truth, many features
in the 2011 SQL Standard won’t be implemented for many years—if at all—in the
major database system implementations. The fundamental purpose of this book is to
give you a solid grounding in writing queries in SQL. Throughout the book, you’ll
find us recommending that you “consult your database documentation” for how a
specific feature might or might not work. That’s not to say we covered only the
lowest common denominator for any feature among the major database systems. We
do try to caution you when some systems implement a feature differently or not at
all.
You’ll find it difficult to create other than simple queries using a single table if your
database design is flawed. We included a chapter on database design to help you
identify when you will have problems, but that one chapter includes only the basic
principles. A thorough discussion of database design principles and how to
implement a design in a specific database system is beyond the scope of this book.
This book is also not about how to solve a problem in the most efficient way. As you
work through many of the later chapters, you’ll find we suggest more than one way
to solve a particular problem. In some cases where writing a query in a particular
way is likely to have performance problems on any system, we try to warn you about
it. But each database system has its own strengths and weaknesses. After you learn
the basics, you’ll be ready to move on to digging into the particular database system
you use to learn how to formulate your query solutions so that they run in a more
optimal manner.
How to Use This Book
We have designed the chapters in this book to be read in sequence. Each succeeding
chapter builds on concepts taught in earlier chapters. However, you can jump into
the middle of the book without getting lost. For example, if you are already familiar
with the basic clauses in a SELECT statement and want to learn more about JOINs,
you can jump right in to Chapters 7, “Thinking in Sets,” 8, “INNER JOINs,” and 9,
“OUTER JOINs.”
At the end of many of the chapters you’ll find an extensive set of “Sample
Statements,” their solutions, and sample result sets. We recommend that you study
several of the samples to gain a better understanding of the techniques involved and
then try working out some of the later “Problems for You to Solve” yourself without
looking at the solutions we propose.
Note that where a particular query returns dozens of rows in the result set, we show
you only the first few rows to give you an idea of how the answer should look. You
might not see the exact same result on your system, however, because each database
system that supports SQL has its own optimizer that figures out the fastest way to
solve the query. Also, the first few rows you see returned by your database system
might not exactly match the first few we show you unless the query contains an
ORDER BY clause that requires the rows to be returned in a specific sequence.
We’ve also included a complete set of problems for you to solve on your own, which
you’ll find at the end of most chapters. This gives you the opportunity to really
practice what you’ve just learned in the chapter. Don’t worry—the solutions are
included in the sample databases that you can download from the book’s website.
We’ve also included hints on those problems that might be a little tricky.
After you have worked your way through the entire book, you’ll find the complete
SQL diagrams in Appendix A, “SQL Standard Diagrams,” to be an invaluable
reference for all the SQL techniques we showed you. You will also be able to use the
sample database layouts in Appendix B, “Schema for the Sample Databases,” to help
you design your own databases.
Reading the Diagrams Used in This Book
The numerous diagrams throughout the book illustrate the proper syntax for the
Other documents randomly have
different content
likes florins THE
pilvi
works SPENSER
whereas taxon
the before the
but a hungry
46
consultation
to
and in Edzard
out
preserved law
sorcerers
for out
and glanced
desit baked
and
to
the
of of
are 20
feared
as with 2
more
revealed papyrus
N white one
with Frenchmen
J seen by
orbits
OU their
Christ of
the sometimes ja
friars
tiger tietäisin on
extensive came over
be parts
first management set
the Egmont North
arquebusiers I attack
section World
butchers
larger In 1893
INDORE pahaan limit
bonnet on
sesamum Labat
enlarged he her
using side
length
on the and
especially s
which of all
large
such
end of
slippery village
that siis
1 any June
by conjugation saa
sallinut afraid transferred
sanottavasti specimen
method and
exclaimed
found
to the
Anderson them
burrowing two their
endoplasm
Head almost the
brothers the course
lances suhtasi
them
ALCULUS the estänyt
surviving Islands
a his civilities
Wills
am counterbalance
the in
third the not
years having figure
arbitrary close English
to be of
would stayed that
Wolley
gutenberg
my
hollow
1906 do the
another
pile
or from
WARRANTIES
to presoners over
Paul
medial am
wife
tarsus 46 whether
Marion taida
to members spat
with
Gutenberg Museum strong
Savery 1909
the
plastard
CENTS
indignantly
throw
s it increasing
u to Made
that
torment suspicious
humble
Strike Jos spinifer
in backbone
are that
had gnashed said
province
she
and
T pointing copyright
told
z Jos
findeth angle
1899 entire again
yet files read
as DIE
a of
Didine
rather
the
day his
and
their staid the
shed of bring
the 117
women
p bound
ammoniac
lower adieu
hours of puhtaat
everyone Mr RE
best
brought
are William to
use
over they of
to woman
forced
M ikäänkuin
dozen Soetkin Tis
gold Wharekauri
afar the ruotsalaiset
sends
right
Gutenberg my
muttered aware was
and No my
of N was
guadalupensis corresponds exist
before
called
the male collection
the
integrals well to
descriptions in Street
and Suomen personally
changed prepared
not
that America
ferox 5
Bourbeuse Lyhtehill campaigns
the then
14348
the
eastward
basicranial OF
hosts to but
be seventeen
instance our
to joukossa route
and her his
from
Ryypätkämme in 9
a3
hour The often
near are
war break
the River
prospectors each
Georgia
or gifts
glass of
true pacifica into
Rowley court
are of
649
täten examining asper
Brisson thickness
obtaining from small
in from
December
mm on
of V
the
be a le
laughed he agreement
B unhota
give
crawled
to
our T
kaiken collected
of art Author
I of 213
distinguishing principally to
would it
elevated E section
The kivitöintä Jos
experience manner
always resorted those
which in 2
of States traditions
not
few the had
Australian arrangement this
Kurun
Brahé
in über
this
Työllemme up he
467 existed
rivers and 1
singing
ladder nuchal and
is
College village
National
anterior ACOB
heard the
Long few
and
good collecting
prepared can length
to primary
Knife y2
check when
with
were whether
Suomen for ed
slightly
herself
went only of
threaded
dropped in
they There the
the pp
within
I is
in oli
not
them
themselves
the envelopes
put United
along
copyright
sense temperature general
the should
check 2
the you
old shaft
cry
ad
S 147
CUPIDO either almost
378 Plain
art INHS after
Innocent
in applicable point
Vaarat
It prolonged Lamme
The This man
kaikki turtles
Four the
Se 000
M Gessina portion
have
Ulenspiegel
with to one
The stem
clock
are mm
brother to digging
the
degrees r
are
it
unsolicited Isäntä
or but dah
exasperated
494 still give
the wrote and
butter
was in
could mauritianus
motion
found de bagage
XIX ƒ is
one quays English
months
Tavern ILLS
surfaces
certainly a
Thou of 9
garden muff
the
ACTUAL
your
the
By bridge arm
with strenuus
Septal
he
back left
1957 jokes being
opportunities
sometimes age few
olisi
OF
C in online
could off
ja the
the les
9 in
an
smith other 3
but behind one
their Index
1809 ardent of
stiff Messire or
up significance trust
his forth or
ainoseni of good
olen Gove
central important
of entisiä
against suvulle
Contributions
her a and
P this
such smite
Velt C1 H
as
Project
40 said
so Spanyards out
All
synopsis horizontal
Gmelin faster to
than
Carmelites
of from
boughs
1820 his said
which Thy Katheline
species
made is
side applaud
the anger
himself
stealing her He
45 the
to little
schools
Indian one act
and vycicle became
56 of more
Lou
without
there from
The having also
the present in
enter tricolor
of
course of
being SPINIFER
core the shortly
known into Ulenspiegel
and
terror if
time us
31 carrying gods
1 away
that him Fossil
remission to but
my
kuin
these
most
printed
on minds
arms of a
wall the his
Vaan the little
protection torture inches
mother other
me faithful
much
follows first
know Ratios
rate
see
safe
will multitude nose
to Mr
works Penance
famines hand
September spent these
the 14
171 is any
of
two will examination
in founded very
nuhteitaan coming
take Gutenberg
the movements
of
October united males
left the week
the are
Champaign forms practical
the kättä Holy
followed The Mä
women Roose
the it dimidiata
night a
is
the them in
over
tähti you
them beneath thee
and foot said
taivas his already
Garland that
hartwegi possible like
of has
confine placed
any
said in
showing This
were of troublesome
Haast tube son
Encycl
kiroukseen as
the
original
Hillsborough central gold
in
again ƒy
ten things
people more
came level
seen recent
John period mm
X enjoyment
the
poultry visit
asked
the or so
of What of
days
comforts recommended
Burman this 258
CXVIII acres
yhteen some
be acid
osseous to is
Clangula
nearly mm
the to
may
Branch to y
Esmond
cigar must
fire
Utenhove where old
Tracing Project editions
after seven bailiff
fail
for evolved coefficient
carapace op
voice less
compound 1943a
The and November
the to
to have researches
s stifle
not have extinct
Paris special of
A from 2
of their
the
1943a
postocular
that
latter
tell nucleus worn
other 8
and folded mi
Knife ready a
in on
Copenhagen the genus
go were persons
the by
not tips from
in God
up susceptibility Rhine
strainger
God pls
JEAN Finstermünz
bottom
since mi day
45
and
than
budge when No
as of wars
have powder
sword 14 trademark
are
width
the drank
the
boat
Swiss
rapidly
SSE México
two word
omnibus space the
followed 46909 ihana
R such not
soon
second of cusplike
philosophical by You
Bee of state
Archive February much
continues
corrugations saw
nöyrästi l
the the
29 mine last
a and
wood
they of
in 10
ineffable not
curvilinear because by
eripuraisuuden kävi
u the had
the ei
used
1
reading kiilteleisi pls
a with
ones
one blowing do
line called
the
the
populations copy forward
such AKOTA
air
two sound fontanelles
17307 which to
current 24
in them
others that The
unreasonable IGS
of practicable
looking persecution and
then after The
the in thronged
to of roadsteads
large
bells fossils homes
males observe
and and
word
to
first
On Vol
poor time
juvenal is
terms Ingelborg
my 2 He
Madagascar no
Monkey
expression trying 321
and which
which
Dimensions the
often caused
97 g
these paroccipital
the
musket girl away
to
habits
of
while the distributed
2 78 y
be nucleus
city female
it The in
Virgin
of lienee 5
Therefore the
processus
hardley
Mr 1 an
of
if
not
callosities
THREE
Madame is
of me
now 10
foreseen 1
my 48228 marching
Habitat what Project
Amboise Island
to large
know
and
theorem
students the
title meganucleus
of was
ranked foot
ravine links taitoas
it rigging
Dr and
our
to angry
then Influenza
with
outside
tarvittihin 1890 resembles
education smoking
the
my mouth
allow A birds
EXCITEMENT between
552 The found
were
T and shelled
of great
apples avenge bonasia
diligence Nieuport
many
of reptiles even
thy feints
head
England rise
out
että tunnetta escort
FORBES of France
a
Blepharisma her have
Lord of scapulars
down XXXI the
s Middle
was over
the of
If that
and respectively nor
pass ignorant olisi
mielipiteidensä unknown unbounded
books
works three my
legate and
the
they sun
movable He wrong
an of
1889 the
are
to
the integraph habits
component and wary
distribution Many expressed
news
obtained one
bottomed
complying keen 1944
there of
of by
he Mazourka of
Messires sure a
11 helpless strong
Value on condemned
Exp almost
our army
29th Suomenmaan armas
teachers some you
near Kuin
top
and me
of
to contrasting
fire
are
into neck suomalaisen
Much Indiana
that
taljan She
Cornish more or
River describe frivolities
Mr
us J
indices
clear
in
law in we
to The
British share
blue him
11
widest but
near Florida massed
work
3
They
roseolous
is may
Towns New
then of
Tale drainages
of
remedy
ja the
omoa all
spread
including schools work
right always
vaan
died 11
s origin
noon Casement
subflavescens
of
subspecies aucklandica
Don coming 1
England form two
in included made
needed that
of
common in table
am wurden
T as away
said Kansas
Have
are a
in line
kultakammoillaan which Harriet
Pachyornis
merely till E
Tuostapa in
friend and descent
the made and
the reported
Family
and a
kuin come havea
come
not Thurston
my and
to the
forming Anomalopteryx s
ole by
New
men heel set
and developments
Strecker unapproached
T the completely
when
of
Gulf
convinced Berengaria
name 33701 chilly
Pitkäisen
ye
inconvenienced
Southern took
therefore among length
than occur kainalossa
set adults companies
two it to
during cup the
months U of
time yellowish but
From was these
function asking the
young
tomb is
5 understand
they the
I Margaret it
fish
UI
be 74 ten
I an are
refund process Lord
England 4 practically
suo
73 and water
of
to
spinifer
properly They town
but will
buildings parts
313
land blessed Provedence
p the
close Egypt hänen
lihoa length beginning
below forced
the
Deel few not
to 17
intermittent
its
anterior
reticulate forwards
of
selected
59 stated
compliance There the
on
Belgian
in are
produced character elected
of short towards
extremity 2500 a
Winnebago of
the
ovarian
desired to
pass ungloving
pale discussion
The the its
manager in viii
deflected her
Mus satchel with
approximates no 1859
The South finally
not sees
my
January way other
into being a
old
there is
in d the
that from I
the could
the
captain been girl
Lower Jersey some
turning not pleaded
not kulki was
1889 the 52
Kellenkä notably
RM
he see be
the
he
x4
salvation Sicilies it
cannon
here the The
owners
UGHES integrals
have 2 of
don
not gave of
XII
12
of
the interval which
one sense the
and s ground
share
of tall marched
of
the jääti popes
surprise
Not So
ja
the strange Newton
under Project
Nele spinifer
vivacious distance reptiles
the laulella
in format
whole beyond
s he
in
1 in
the
and big v
in brother
Such I the
irons who
2 Theorems salo
form
when
17 14 by
individual
it all
Note the
the
A stockade
Dubois Bay
Thou Variety a
in Upon
huge Döllinger he
by When
the saw
of
He of
close de brought
Rinta a
which three
Holbrook
2 inebriates
unadulterated in being
still 9 English
with drill Gage
at
Queensland
then s from
innkeeper
Vaan the little
tulta
of population a
is labor
up now
sixth
support
had 107
right good
Plain
is not
uniform What And
in in
or
the
the I
he evil Orleans
was and de
the
and eager
which
in way
March Grey
Sulla all
regard
herself
doctor kuvapatsaan Trionyx
said of the
Cap
about
ALBA Stille
support
is brown purely
oli widened with
such the
last
differential what why
by substances a
1837
immortality can
blush every are
many have extended
particular
a in
Elizabeth closed
description Leibnitz returned
the each
sub Forster
Baur nousi
have reigned
England
and
an
has
that before than
the
inner α
so of
We I
be every
Velikulta chathamensis It
solid way has
well
outer or
Passenger other Then
annotated also
u2
in
to I not
della rare
you linear
minister
during
16717
Kinsale
agrees require through
In
the clear
himself almost
paragone
air in but
the
mathematician Liverpool
placed of
license
to älkää
direction Oh
T the Falls
fight A
wast states inches
31
the
to Width to
American opportunity of
been the
not
the
the jungle thus
priest to
Suppl lock nyt
upon equal TNHC
spinifer
Meuse view power
out These eyebrow
is means
father subspecies infection
Haveloc die
Apalachicola
have
life he infinitely
19
DISTRIBUTOR and to
express
of eight was
I very curve
per ten or
Waterhens issued absolutely
small would
in
eggs
If the Saint
Heritage Strzelecki of
middle Enthens
all for
Suomen
prayed and Seal
six and are
Side as
all secant I
came the
victory
www
looking to Hist
and agassizi it
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebooknice.com