Tài liệu SQL A Beginner’s Guide Third Edition - Pdf 10

www.it-ebooks.info
SQL
A Beginner’s Guide
Third Edition
Andy Oppel
Robert Sheldon
New York Chicago San Francisco
Lisbon London Madrid Mexico City
Milan New Delhi San Juan
Seoul Singapore Sydney Toronto
www.it-ebooks.info
Copyright © 2009 by The McGraw-Hill Companies. All rights reserved. Manufactured in the United States of America. Except as
permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by
any means, or stored in a database or retrieval system, without the prior written permission of the publisher.
0-07-154865-3
The material in this eBook also appears in the print version of this title: 0-07-154864-5.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked
name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the
trademark. Where such designations appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training
programs. For more information, please contact George Hoare, Special Sales, at or (212) 904-4069.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work.
Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy
of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit,
distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work
for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be
terminated if you fail to comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO
THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUD-
ING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND

product experience includes IMS, DB2, Sybase, Microsoft SQL Server, Microsoft Access,
MySQL, and Oracle (versions 7, 8, 8i, 9i, and 10g).
Robert Sheldon has worked as a consultant and technical writer for a number of years.
As a consultant, he has managed the development and maintenance of web-based and client-
server applications and the databases that supported those applications. He has designed and
implemented various Access and SQL Server databases and has used SQL to build databases,
create and modify database objects, query and modify data, and troubleshoot system- and
data-related problems. Robert has also written or cowritten eight books on various network
and server technologies, one of which received a Certificate of Merit from the Puget Sound
Chapter of the Society for Technical Communication. In addition, two of the books that
Robert has written focus exclusively on SQL Server design and implementation. Robert
has also written and edited a variety of other documentation related to SQL databases and
other computer technologies. His writing includes material outside the computer industry—
everything from news articles to ad copy to legal documentation—and he has received two
awards from the Colorado Press Association.
About the Technical Editor
James Seymour is a graduate of the University of North Carolina at Chapel Hill with a BA in
history and political science and the University of Kentucky with a MA in history. He became
first involved with computer technology in 1965 with the mainframe environment at North
Carolina. While in the United States Army during the Vietnam War, he was on the small team
that worked with the mainframe setup at the Pentagon for various military strategic scenarios.
Since 1972, he has been involved in varied computer environments with the second point-of-sale
Copyright © 2009 by The McGraw-Hill Companies. Click here for terms of use.
www.it-ebooks.info
and inventory control project in the retail industry, analytical programs and database initiatives in
the insurance and benefits industries, loss control startups, and other inventory control and sales
tracking projects throughout many different industries.
From 1987 through 1995, James was an instructor of database management in the community
college system of the state of Kentucky. In this capacity, he created the first database management
and C programming courses in the state of Kentucky and helped both public and private entities

Qualified Names 41
For more information about this title, click here
www.it-ebooks.info
vi SQL: A Beginner’s Guide
Create a Schema 42
Create a Database 44
3 Creating and Altering Tables 49
Create SQL Tables 50
Specify Column Data Types 54
String Data Types 55
Numeric Data Types 57
Datetime Data Types 58
Interval Data Type 60
Boolean Data Type 61
Using SQL Data Types 62
Create User-Defined Types 63
Specify Column Default Values 64
Delete SQL Tables 69
4 Enforcing Data Integrity 73
Understand Integrity Constraints 74
Use NOT NULL Constraints 76
Add UNIQUE Constraints 77
Add PRIMARY KEY Constraints 79
Add FOREIGN KEY Constraints 83
The MATCH Clause 88
The <referential triggered action> Clause 89
Define CHECK Constraints 95
Defining Assertions 97
Creating Domains and Domain Constraints 98
5 Creating SQL Views 103

Delete SQL Data 186
9 Using Predicates 193
Compare SQL Data 194
Using the BETWEEN Predicate 199
Return Null Values 200
Return Similar Values 203
Reference Additional Sources of Data 209
Using the IN Predicate 209
Using the EXISTS Predicate 213
Quantify Comparison Predicates 216
Using the SOME and ANY Predicates 216
Using the ALL Predicate 218
10 Working with Functions and Value Expressions 225
Use Set Functions 226
Using the COUNT Function 227
Using the MAX and MIN Functions 229
Using the SUM Function 231
Using the AVG Function 232
Use Value Functions 232
Working with String Value Functions 233
Working with Datetime Value Functions 236
Use Value Expressions 238
Working with Numeric Value Expressions 238
Using the CASE Value Expression 241
Using the CAST Value Expression 244
Use Special Values 245
www.it-ebooks.info
viii SQL: A Beginner’s Guide
11 Accessing Multiple Tables 253
Perform Basic Join Operations 254

Invoking SQL-Invoked Procedures 305
Add Input Parameters to Your Procedures 306
Using Procedures to Modify Data 309
Add Local Variables to Your Procedures 311
Work with Control Statements 313
Create Compound Statements 313
Create Conditional Statements 314
Create Looping Statements 316
Add Output Parameters to Your Procedures 320
Create SQL-Invoked Functions 321
www.it-ebooks.info
Contents ix
14 Creating SQL Triggers 329
Understand SQL Triggers 330
Trigger Execution Context 331
Create SQL Triggers 333
Referencing Old and New Values 334
Dropping SQL Triggers 335
Create Insert Triggers 336
Create Update Triggers 338
Create Delete Triggers 343
15
Using SQL Cursors 351
Understand SQL Cursors 352
Declaring and Opening SQL Cursors 353
Declare a Cursor 355
Working with Optional Syntax Elements 356
Creating a Cursor Declaration 360
Open and Close a Cursor 363
Retrieve Data from a Cursor 363

Working with Host Variables 424
Retrieving SQL Data 426
18 Working with XML Data 433
Learn the Basics of XML 434
Learn About SQL/XML 437
The XML Data Type 437
SQL/XML Functions 439
SQL/XML Mapping Rule 441
PART IV Appendices
A Answers to Self Test 449
B SQL:2006 Keywords 491
SQL Reserved Keywords 492
SQL Nonreserved Keywords 494
C SQL Code Used in Try This Exercises 497
SQL Code by Try This Exercise 498
The INVENTORY Database 514
Index 519
www.it-ebooks.info
xi
Introduction
R
elational databases have become the most common data storage mechanism for modern
computer applications. Programming languages such as Java, C, and COBOL, and
scripting languages such as Perl, VBScript, and JavaScript must often access a data source
in order to retrieve or modify data. Many of these data sources are managed by a relational
database management system (RDBMS), such as Oracle, Microsoft SQL Server, MySQL, and
DB2, that relies on the Structured Query Language (SQL) to create and alter database objects,
add data to and delete data from the database, modify data that has been added to that database,
and of course, retrieve data stored in the database for display and processing.
SQL is the most widely implemented language for relational databases. Much as

understanding of how to use SQL to access data in your relational database.
This third edition has been updated to include the provisions of the ISO SQL:2006
standard, along with technical corrigenda published in 2007. Chapter 18 has been added
to cover SQL/XML, which was added to the SQL standard in 2006. In addition, the SQL
statements have been reformatted and all database object names folded to uppercase to
improve readability and transportability across the wide variety of commercially available
RDBMS products.
Who Should Read This Book
SQL: A Beginner’s Guide is recommended for anyone trying to build a foundation in SQL
programming based on the ISO SQL:2006 standard. The book is designed specifically for
those who are new or relatively new to SQL; however, those of you who need a refresher in
SQL will also find this book beneficial. Whether you’re an experienced programmer, have had
some web development experience, are a database administrator, or are new to programming
and databases, SQL: A Beginner’s Guide provides a strong foundation that will be useful to
anyone wishing to learn more about SQL. In fact, any of the following individuals will find
this book helpful when trying to understand and use SQL:
● The novice new to database design and SQL programming
● The analyst or manager who wants to better understand how to implement and access SQL
databases
● The database administrator who wants to learn more about programming
● The technical support professional or testing/QA engineer who must perform ad hoc
queries against an SQL data source
● The web developer writing applications that must access SQL databases
● The third-generation language (3GL) programmer embedding SQL within an application’s
source code
● Any other individual who wants to learn how to write SQL code that can be used to create
and access databases within an RDBMS
Whichever category you might fit into, an important point to remember is that the book
is geared toward anyone wanting to learn standard SQL, not a product-specific version of
the language. The advantage of this is that you can take the skills learned in this book and

user-defined types, and specify column default values. You’ll also learn how to alter a table
definition and delete that definition from your database.
Chapter 4: Enforcing Data Integrity
This chapter explains how integrity constraints are used to enforce data integrity in your
SQL tables. The chapter includes information on table-related constraints, assertions, and
domain constraints. You will learn how to create NOT NULL, UNIQUE, PRIMARY KEY,
FOREIGN KEY, and CHECK constraints.
Introduction xiii
www.it-ebooks.info
xiv SQL: A Beginner’s Guide
Chapter 5: Creating SQL Views
In this chapter, you’ll learn how to add views to your SQL database. You’ll also learn how to
create updateable views and how to drop views from the database.
Chapter 6: Managing Database Security
In this chapter, you’ll be introduced to the SQL security model and learn how authorization
identifiers are defined within the context of a session. You’ll then learn how to create and
delete roles, grant and revoke privileges, and grant and revoke roles.
Part II: Data Access and Modification
Part II explains how to access and modify data in an SQL database. You’ll also learn how
to use predicates, functions, and value expressions to manage that data. In addition, Part II
describes how to join tables and use subqueries to access data in multiple tables.
Chapter 7: Querying SQL Data
This chapter describes the basic components of the SELECT statement and how the statement
is used to retrieve data from an SQL database. You’ll learn how to define each clause that can
be included in the SELECT statement and how those clauses are processed when querying a
database.
Chapter 8: Modifying SQL Data
In this chapter, you’ll learn how to modify data in an SQL database. Specifically, you’ll learn
how to insert data, update data, and delete data. The chapter reviews each component of the
SQL statements that allow you to perform these data modifications.

Chapter 15: Using SQL Cursors
In this chapter, you’ll learn how SQL cursors are used to retrieve one row of data at a time
from a result set. The chapter explains how to declare a cursor, open and close a cursor, and
retrieve data from a cursor. You’ll also learn how to use positioned UPDATE and DELETE
statements after you fetch a row through a cursor.
Chapter 16: Managing SQL Transactions
In this chapter, you’ll learn how transactions are used to ensure the integrity of your SQL
data. The chapter describes how to set transaction properties, start a transaction, set constraint
deferability, create savepoints in a transaction, and terminate a transaction.
Chapter 17: Accessing SQL Data from Your Host Program
This chapter describes the four methods supported by the SQL standard for accessing an SQL
database. You’ll learn how to invoke SQL directly from a client application, embed SQL
statements in a program, create SQL client modules, and use an SQL call-level interface to
access data.
Chapter 18: Working with XML Data
This chapter describes how XML data can be incorporated into an SQL database. You’ll learn
the basics of XML, how to use the XML data type to store XML in table column values, how
to write SQL/XML functions that can be used to return data from the database formatted as
XML, and the SQL/XML mapping rules that describe how SQL values are translated to XML
values and vice versa.
Part IV: Appendices
The appendices include reference material for the information presented in the first three parts.
Appendix A: Answers to Self Test
This appendix provides the answers to the Self Test questions listed at the end of each chapter.
Appendix B: SQL: 2006 Keywords
This appendix lists the reserved and nonreserved keywords as they are used in SQL statements
as defined in the SQL:2006 standard.
Introduction xv
www.it-ebooks.info
xvi SQL: A Beginner’s Guide

keywords that are used to formulate the SQL statement. (For a complete list of SQL:2006
keywords, see Appendix B.) Although SQL does not require that keywords be written in
uppercase, I use that convention in this book so that you can easily identify the keywords
within a statement. In addition to the keywords, the syntax for an SQL statement includes a
number of other elements that help define how a particular statement should be created:
● Square brackets The square brackets indicate that the syntax enclosed in those brackets is
optional. For example, the ON COMMIT clause in the CREATE TABLE statement is optional.
www.it-ebooks.info
● Angle brackets The angle brackets enclose information that represents a placeholder.
When a statement is actually created, the placeholder is replaced by the appropriate SQL
elements or identifiers. For example, you should replace the <table name> placeholder
with a name for the table when you define a CREATE TABLE statement.
● Curly brackets The curly brackets are used to group elements together. The brackets tell
you that you should first decide how to handle the contents within the brackets and then
determine how they fit into the statement. For example, the PRESERVE | DELETE set of
keywords is enclosed by curly brackets. You must first choose PRESERVE or DELETE
and then deal with the entire line of code. As a result, your clause can read ON COMMIT
PRESERVE ROWS, or it can read ON COMMIT DELETE ROWS.
● Vertical bars The vertical bar can be read as “or,” which means that you should use
either the PRESERVE option or the DELETE option.
● Three periods The three periods indicate that you can repeat the clause as often as
necessary. For example, you can include as many table elements (represented by <table
element>) as necessary.
● Colons/equals sign The ::= symbol (two consecutive colons plus an equals sign)
indicates that the placeholder to the left of the symbol is defined by the syntax following
the symbol. In the syntax example, the <table definition> placeholder equals the syntax
that makes up a CREATE TABLE statement.
By referring to the syntax, you should be able to construct an SQL statement that creates
database objects or modifies SQL data as necessary. However, in order to better demonstrate
how the syntax is applied, each chapter also contains examples of actual SQL statements.

Try This Exercises
Each chapter contains one or two Try This exercises that allow you to apply the information
that you learned in the chapter. Each exercise is broken down into steps that walk you through
the process of completing a particular task. Many of the projects include related files that you
can download from our web site at . The files usually include the
SQL statements used within the Try This exercise. In addition, a consolidation of the SQL
statements is included in Appendix C.
The Try This exercises are based on the INVENTORY database. You’ll create the
database, create the tables and other objects in the database, add data to those tables, and then
manipulate that data. Because the projects build on one another, it is best that you complete
them in the order that they’re presented in the book. This is especially true for the chapters
in Part I, in which you create the database objects, and Chapter 7, in which you insert data
into the tables. However, if you do plan to skip around, you can refer to Appendix C, which
provides all the code necessary to create the database objects and populate the tables with data.
To complete most of the Try This exercises in this book, you’ll need to have access to an
RDBMS that allows you to enter and execute SQL statements interactively. If you’re accessing
an RDBMS over a network, check with the database administrator to make sure that you’re
logging in with the credentials necessary to create a database and schema. You might need
special permissions to create these objects. Also verify whether there are any parameters
you should include when creating the database (for example, log file size), restrictions on
the names you can use, or restrictions of any other kind. Be sure to check the product’s
documentation before working with any database product.
www.it-ebooks.info
Part I
Relational Databases
and SQL
Copyright © 2009 by The McGraw-Hill Companies. Click here for terms of use.
www.it-ebooks.info
This page intentionally left blank
www.it-ebooks.info

a complex system of data retrieval and storage that relies on user interfaces and a network of
client computers and servers. There are as many definitions for the word database as there are
books about them. Moreover, different DBMS vendors have developed different architectures,
so not all databases are designed in the same way. Despite the lack of an absolute definition,
most sources agree that a database, at the very least, is a collection of data organized in a
structured format that is defined by metadata that describes that structure. You can think
of metadata as data about the data being stored; it defines how the data is stored within the
database.
Over the years, a number of database models have been implemented to store and manage
data. Several of the more common models include the following:
● Hierarchical This model has a parent–child structure that is similar to an inverted tree,
which is what forms the hierarchy. Data is organized in nodes, the logical equivalent of
tables in a relational database. A parent node can have many child nodes, but a child node
www.it-ebooks.info
Chapter 1: Introduction to Relational Databases and SQL 5
can have only one parent node. Although the model has been highly implemented, it is
often considered unsuitable for many applications because of its inflexible structure and
lack of support for complex relationships. Still, some implementations such as IMS from
IBM have introduced features that work around these limitations.
● Network This model addresses some of the limitations of the hierarchical model. Data
is organized in record types, the logical equivalent of tables in a relational database. Like
the hierarchical model, the network model uses an inverted tree structure, but record
types are organized into a set structure that relates pairs of record types into owners and
members. Any one record type can participate in any set with other record types in the
database, which supports more complex queries and relationships than are possible in the
hierarchical model. Still, the network model has its limitations, the most serious of which
is complexity. In accessing the database, users must be very familiar with the structure and
keep careful track of where they are and how they got there. It’s also difficult to change the
structure without affecting applications that interact with the database.
● Relational This model addresses many of the limitations of both the hierarchical and

example, in Figure 1-1, the entity is a compact disc (CD) with attributes of CD_NAME (the
title of the CD), ARTIST_NAME (the name of the recording artist), and COPYRIGHT_YEAR
(the year the recording was copyrighted).
As you can see in Figure 1-1, each attribute has an associated domain. A domain defines
the type of data that can be stored in a particular attribute; however, a domain is not the same
thing as a data type. A data type, which is discussed in more detail in Chapter 3, is a specific
kind of constraint (a control used to enforce data integrity) associated with a column, whereas
a domain, as it is used in the relational model, has a much broader meaning and describes
exactly what data can be included in an attribute associated with that domain. For example, the
COPYRIGHT_YEAR attribute is associated with the Year domain. As you see in this example,
it is common practice to include a class word that describes the domain in attribute names, but
this is not at all mandatory. The domain can be defined so that the attribute includes only data
whose values and format are limited to years, as opposed to days or months. The domain might
also limit the data to a specific range of years. A data type, on the other hand, restricts the
format of the data, such as allowing only numeric digits, but not the values, unless those values
somehow violate the format.
Data is stored in a relation in tuples (rows). A tuple is a set of data whose values make
up an instance of each attribute defined for that relation. Each tuple represents a record of
related data. (In fact, the set of data is sometimes referred to as a record.) For example, in
Figure 1-1, the second tuple from the top contains the value “Joni Mitchell” for the ARTIST_
NAME attribute, the value “Blue” for the CD_NAME attribute, and the value “1971” for the
COPYRIGHT_YEAR attribute. Together these three values form a tuple.
ARTIST_NAME:FullName
Jennifer Warnes
Joni Mitchell
William Ackerman
Kitaro
Bing Crosby
Patsy Cline Patsy Cline: 12 Greatest Hits
CD_NAME:Title


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status