Sams Teach Yourself SQL in 10 Minutes
Sams Teach Yourself SQL in 10 Minutes
Sams Teach Yourself SQL in 10 Minutes
SQL
Ben Forta
in 10
Minutes
THIRD EDITION
Bulk Sales
Sams Publishing offers excellent discounts on this book when
ordered in quantity for bulk purchases or special sales. For more
information, please contact
U.S. Corporate and Government Sales
1-800-382-3419
[email protected]
For sales outside of the U.S., please contact
International Sales
[email protected]
Contents
Introduction..........................................................................................1
1 Understanding SQL 5
Database Basics ..................................................................................5
What Is SQL? ....................................................................................11
Try It Yourself ....................................................................................12
Summary ............................................................................................12
2 Retrieving Data 13
The SELECT Statement........................................................................13
Retrieving Individual Columns..........................................................14
Retrieving Multiple Columns ............................................................16
Retrieving All Columns ....................................................................17
Summary ............................................................................................18
4 Filtering Data 26
Using the WHERE Clause......................................................................26
The WHERE Clause Operators ..............................................................28
Summary ............................................................................................32
9 Summarizing Data 66
Using Aggregate Functions................................................................66
Aggregates on Distinct Values ..........................................................72
Combining Aggregate Functions ......................................................73
Summary ............................................................................................74
10 Grouping Data 75
Understanding Data Grouping ..........................................................75
Creating Groups ................................................................................76
Filtering Groups ................................................................................78
Grouping and Sorting ........................................................................80
SELECT Clause Ordering ....................................................................83
Summary ............................................................................................83
12 Joining Tables 91
Understanding Joins ..........................................................................91
Creating a Join ..................................................................................94
Summary ..........................................................................................100
Index 225
Introduction
SQL is the most widely used database language. Whether you are an
application developer, database administrator, Web application designer,
or Microsoft Office user, a good working knowledge of SQL is an impor-
tant part of interacting with databases.
This book was born out of necessity. I had been teaching Web application
development for several years, and students were constantly asking for
SQL book recommendations. There are lots of SQL books out there.
Some are actually very good. But they all have one thing in common: for
most users they teach just too much information. Instead of teaching SQL
itself most books teach everything from database design and normaliza-
tion to relational database theory and administrative concerns. And while
those are all important topics, they are not of interest to most of us who
just need to learn SQL.
And so, not finding a single book that I felt comfortable recommending, I
turned that classroom experience into the book you are holding. Sams
Teach Yourself SQL in 10 Minutes will teach you SQL you need to know,
starting with simple data retrieval and working on to more complex topics
including the use of joins, subqueries, stored procedures, cursors, triggers,
and table constraints. You’ll learn methodically, systematically, and sim-
ply—in lessons that will each take 10 minutes or less to complete.
Now in its third edition, this book has taught SQL to hundreds of thou-
sands of users, and now it is your turn. So turn to Lesson 1, and get to
work. You’ll be writing world class SQL in no time at all.
Example databases and SQL scripts are also available for all of these
DBMSs.
INPUT The Input icon identifies code that you can type in yourself.
Sorting Data
As you learned in the last lesson, the following SQL statement returns a
single column from a database table. But look at the output. The data
appears to be displayed in no particular order at all.
SELECT prod_name
INPUT FROM Products;
prod_name
OUTPUT --------------------
Fish bean bag toy
Bird bean bag toy
Rabbit bean bag toy
8 inch teddy bear
12 inch teddy bear
18 inch teddy bear
Raggedy Ann
King doll
Queen doll
storage space. The end result is that you cannot (and should not) rely on
the sort order if you do not explicitly control it. Relational database
design theory states that the sequence of retrieved data cannot be assumed
to have significance if ordering was not explicitly specified.
Clause SQL statements are made up of clauses, some required
and some optional. A clause usually consists of a keyword and
supplied data. An example of this is the SELECT statement’s FROM clause,
which you saw in the last lesson.
To explicitly sort data retrieved using a SELECT statement, the ORDER BY
clause is used. ORDER BY takes the name of one or more columns by
which to sort the output. Look at the following example:
SELECT prod_name
INPUT FROM Products
ORDER BY prod_name;
prod_name
OUTPUT --------------------
12 inch teddy bear
18 inch teddy bear
8 inch teddy bear
Bird bean bag toy
Fish bean bag toy
King doll
Queen doll
Rabbit bean bag toy
Raggedy Ann
the values in the prod_price column had been unique, no data would
have been sorted by prod_name.
But what if you were to sort by multiple columns? The following example
sorts the products in descending order (most expensive first), plus product
name:
SELECT prod_id, prod_price, prod_name
INPUT FROM Products
ORDER BY prod_price DESC, prod_name;
24 Lesson 3
It is worth noting that DESC is short for DESCENDING, and both keywords
may be used. The opposite of DESC is ASC (or ASCENDING), which may be
specified to sort in ascending order. In practice, however, ASC is not usu-
ally used because ascending order is the default sequence (and is assumed
if neither ASC nor DESC are specified).
Sorting Retrieved Data 25
Summary
In this lesson, you learned how to sort retrieved data using the SELECT
statement’s ORDER BY clause. This clause, which must be the last in the
SELECT statement, can be used to sort data on one or more columns as
needed.
INDEX
IS NULL, 31 derived, 54
SELECT statements, order of, fully qualified names, 95
83 GROUP BY clause, 77
WHERE, 26 grouping data, specifying by
AND operator, 33-34 relative position, 77
checking against single Identity fields, 160
value, 29 INSERT SELECT statements,
checking for nonmatches, 124
29-30 INSERT statement, omitting
checking for NULL value, columns, 122
31 insert STATEMENT AND, 120
checking for range of val- multiple, sorting query results
ues, 30-31 by, 21-22
IN operator, 36-38 nonselected, sorting query
joins and, 95-97 results by, 23
multiple query criteria, 33 NULL value, checking for, 31
NOT operator, 38-39 NULL value columns, 136-137
operator support by OrderItems example table, 191
DBMS, 30 Orders example table, 190
operators, 28 padded spaces, RTRIM( ) func-
OR operator, 34-35 tion, 51-52
order of evaluation, 35-36 position, sorting query results
positioning, 27 by, 22
SOUNDEX function, 61 primary keys, 10
client-based results formatting, com- Products example table, 189
pared to server-based, 49 retrieving
CLOSE statements, closing cursors, all, 17-18
173 individual, 14-15
code (programming) multiple, 16-17
commenting, 59 unknown, 18
stored procedures, 159 separating names in queries, 16
portability, 58 sorting data, descending on
ColdFusion (Macromedia), running, multiple columns, 24
196 subquery result restrictions, 88
columns. See also fields updating multiple, 128
aliases values, deleting, 129
alternative uses, 54 Vendors example table, 188
concatenating fields, 53-54 combined queries
creating, 101 creating, 112-113
names, 54 duplicate rows and, 114-115
AVG( ) function, individual overview, 111
columns, 68 performance, 114
breaking data correctly, 8 rules, 114
concepts, 8 sorting results, 116
Customers example table, 189
formatting LEN( ), 60
query data, 17 LENGTH( ), 60
retrieved data with views, LOWER( ), 60
148-149 LTRIM( ), 60
server-based compared to MAX( ), 67-69
client-based, 49 DISTINCT argument, 73
statements, 135 non-numeric data, 70
subqueries, 87 NULL values, 70
FROM clause, creating joins, 94 MIN( ), 67, 70
FROM keyword, 14 DISTINCT argument, 73
DELETE statement, 130 non-numeric data, 70
UPDATE statement, 129 NULL values, 71
full outer joins, 108 numeric, 59, 64-65
fully qualified column names, 95 PI( ), 65
functions RIGHT( ), 60
ABS( ), 64 RTRIM( ), 51-52, 60
advisability of using, 59 SIN( ), 65
aggregate SOUNDEX( ), 60-61
ALL argument, 72 support for, 61
AVG( ), 67-68 SQRT( ), 65
combining, 73-74 SUM( ), 67, 71
COUNT( ), 68-69 multiple columns and, 72
defined, 67 NULL values, 72
DISTINCT argument, support considerations, 57-58
72-73 system, 59
joins and, 108-110 TAN( ), 65
MAX( ), 69 text, 59-60
MIN( ), 70 list of common, 60
naming aliases, 74 to_char, 63
overview, 66 to_number, 63
SUM( ), 71 TRIM, 52
AVG( ), 67-68 types of, 59
DISTINCT argument, 72 UCASE( ), 60
NULL values, 68 UPPER( ), 59-60
COS( ), 64 YEAR( ), 63
COUNT( ), 67-69
DISTINCT argument, 73
NULL values, 69 G
DATALENGTH( ), 60
date and time, 59, 62-64 global variables, @@IDENTITY,
DATEPART( ), 62 160
defined, 57 GRANT statement, 185
EXP( ), 64 greater than operator (WHERE
LCASE( ), 60 clause), 28
LEFT( ), 60
J-K
H-I
joins
HAVING clause, grouping data, 78 aggregate functions and,
108-110
IBM DB2, running, 195-196 Cartesian Product, 95-97
Identity fields, 160 creating, 94
IN operator, 36-38 cross joins, 97
indexes inner joins, 97-98
cautions, 182 multiple tables, 98-100
creating, 182, 208 natural joins, 104-105
overview, 180-182 outer, 105-108
revisiting, 182 full, 108
inner joins, 97-98 left, 107
INSERT SELECT statement, right, 107
122-124 syntax, 107
SELECT INTO statement com- types, 108
parison, 125 overview, 91
syntax, 210 performance considerations, 99
INSERT statement self joins, 102-104
columns lists, 121 usefulness of, 93
completing rows, 118-120 views, 147-148
INTO keyword, 119 WHERE clause, 95-97
omitting columns, 122
overview, 118 keys, primary, 9-11
partial rows, 121-122 keywords, 13
query data, 122-124 AND, 31, 34
rollbacks, 167 AS, 53-54
security privileges, 118 Oracle support, 102
syntax, 209 ASC, query results sort order,
24
INDEX 233