Tải bản đầy đủ

SQL for dummies, 6th ed 2006

www.dbebooks.com - Free Books & magazines


SQL
FOR

DUMmIES
6TH



EDITION

by Allen G. Taylor
Author of Database Development For Dummies®
and Crystal Reports® 10 For Dummies®


SQL
FOR


DUMmIES
6TH



EDITION

by Allen G. Taylor
Author of Database Development For Dummies®
and Crystal Reports® 10 For Dummies®


SQL For Dummies®, 6th Edition
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing,
Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at
http://www.wiley.com/go/permissions.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE
CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE
UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE
AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE
INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY
MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK
MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT
IS READ.


Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United
States and other countries, and may not be used without written permission. All other trademarks are the
property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
For general information on our other products and services, please contact our Customer Care
Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Library of Congress Control Number: 2006926171
ISBN-13: 978-0-470-04652-4
ISBN-10: 0-470-04652-X
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
6B/SX/QX/QW/IN


About the Author
Allen G. Taylor is a 30-year veteran of the computer industry and the author
of 24 books, including Crystal Reports 10 For Dummies, Database Development
For Dummies, Access Power Programming with VBA, and SQL Weekend Crash
Course. He lectures internationally on databases, networks, innovation, and
entrepreneurship. He also teaches database development through a leading
online education provider and teaches digital electronics and computer architecture at Portland State University. He teaches computer hardware via
distance learning at the International Institute for Information Science &
Technology in Shanghai, China. For the latest news on Allen’s activities,
check out www.DatabaseCentral.Info. You can contact Allen at allen.
taylor@ieee.org.



Dedication
This book is dedicated to Georgina Taylor, my mom.

Author’s Acknowledgments
First and foremost, I would like to acknowledge the help of Jim Melton, editor
of the ISO/ANSI specification for SQL. Without his untiring efforts, this book,
and indeed SQL itself as an international standard, would be of much less
value. Andrew Eisenberg has also contributed to my knowledge of SQL
through his writing. I would also like to thank my project editor, Nicole
Haims, and my acquisitions editor, Tiffany Ma, for their key contributions to
the production of this book. Thanks also to my agent, Carole McClendon of
Waterside Productions, for her support of my career.


Publisher’s Acknowledgments
We’re proud of this book; please send us your comments through our online registration form
located at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and
Media Development

Composition Services

Project Editor: Nicole Haims
(Previous Edition: Kala Schrager)
Acquisitions Editor: Tiffany Ma

Project Coordinator: Tera Knapp
Layout and Graphics: Carl Byers, Andrea Dahl,
Barbara Moore, Heather Ryan

Technical Editor: Greg Guntle

Proofreaders: Leeann Harney,
Christy Pingleton, Techbooks

Editorial Manager: Jodi Jensen

Indexer: Techbooks

Media Development Manager:
Laura VanWinkle
Editorial Assistant: Amanda Foxworth
Sr. Editorial Assistant: Cherie Case
Cartoons: Rich Tennant
(www.the5thwave.com)

Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Joyce Pepple, Acquisitions Director
Composition Services
Gerry Fahey, Vice President of Production Services
Debbie Stailey, Director of Composition Services


Contents at a Glance
Introduction .................................................................1
Part I: Basic Concepts...................................................5
Chapter 1: Relational Database Fundamentals...............................................................7
Chapter 2: SQL Fundamentals ........................................................................................21
Chapter 3: The Components of SQL...............................................................................47

Part II: Using SQL to Build Databases..........................73
Chapter 4: Building and Maintaining a Simple Database Structure ...........................75
Chapter 5: Building a Multitable Relational Database .................................................91

Part III: Storing and Retrieving Data .........................121
Chapter 6: Manipulating Database Data ......................................................................123
Chapter 7: Specifying Values.........................................................................................141
Chapter 8: Using Advanced SQL Value Expressions ..................................................163
Chapter 9: Zeroing In on the Data You Want...............................................................175
Chapter 10: Using Relational Operators ......................................................................201
Chapter 11: Delving Deep with Nested Queries..........................................................225
Chapter 12: Recursive Queries .....................................................................................243

Part IV: Controlling Operations ..................................253
Chapter 13: Providing Database Security....................................................................255
Chapter 14: Protecting Data ..........................................................................................269
Chapter 15: Using SQL within Applications ................................................................287

Part V: Taking SQL to the Real World.........................301
Chapter 16: Accessing Data with ODBC and JDBC.....................................................303
Chapter 17: Operating on XML Data with SQL............................................................313

Part VI: Advanced Topics ..........................................333
Chapter 18: Stepping through a Dataset with Cursors ..............................................335
Chapter 19: Adding Procedural Capabilities with Persistent Stored Modules.......345
Chapter 20: Handling Errors .........................................................................................361


Part VII: The Part of Tens ..........................................373
Chapter 21: Ten Common Mistakes .............................................................................375
Chapter 22: Ten Retrieval Tips .....................................................................................379

Part VIII: Appendixes................................................383
Appendix A: SQL:2003 Reserved Words ......................................................................385
Appendix B: Glossary ....................................................................................................389

Index .......................................................................397


Table of Contents
Introduction..................................................................1
About This Book...............................................................................................1
Who Should Read This Book?.........................................................................2
How This Book Is Organized...........................................................................2
Part I: Basic Concepts ............................................................................2
Part II: Using SQL to Build Databases ..................................................2
Part III: Storing and Retrieving Data.....................................................3
Part IV: Controlling Operations ............................................................3
Part V: Taking SQL to the Real World...................................................3
Part VI: Advanced Topics ......................................................................3
Part VII: The Part of Tens ......................................................................4
Part VIII: Appendixes .............................................................................4
Icons Used in This Book..................................................................................4
Getting Started .................................................................................................4

Part I: Basic Concepts ...................................................5
Chapter 1: Relational Database Fundamentals . . . . . . . . . . . . . . . . . . . .7
Keeping Track of Things .................................................................................7
What Is a Database? .........................................................................................8
Database Size and Complexity .......................................................................9
What Is a Database Management System?....................................................9
Flat Files ..........................................................................................................10
Database Models ............................................................................................12
Relational model...................................................................................12
Why relational is better .......................................................................13
Components of a relational database ................................................13
Holidays bring families together ........................................................13
Enjoy the view.......................................................................................15
Schemas, domains, and constraints ..................................................18
The object model challenges the relational model..........................19
The object-relational model................................................................19
Database Design Considerations .................................................................20

Chapter 2: SQL Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21
What SQL Is and Isn’t.....................................................................................21
A (Very) Little History ...................................................................................23
SQL Commands ..............................................................................................24
Reserved Words .............................................................................................25


x

SQL For Dummies, 6th Edition
Data Types ......................................................................................................26
Exact numerics .....................................................................................26
Approximate numerics ........................................................................28
Character strings..................................................................................30
Booleans ................................................................................................32
Datetimes...............................................................................................32
Intervals.................................................................................................34
XML type................................................................................................34
ROW types.............................................................................................35
Collection types....................................................................................36
REF types...............................................................................................37
User-defined types ...............................................................................37
Data type summary ..............................................................................40
Null Values.......................................................................................................42
Constraints......................................................................................................42
Using SQL in a Client/Server System ...........................................................43
The server .............................................................................................43
The client...............................................................................................44
Using SQL on the Internet/Intranet..............................................................45

Chapter 3: The Components of SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . .47
Data Definition Language ..............................................................................48
When “Just do it!” is not good advice ................................................48
Creating tables ......................................................................................49
A room with a view...............................................................................51
Collecting tables into schemas...........................................................56
Ordering by catalog..............................................................................57
Getting familiar with DDL commands................................................58
Data Manipulation Language ........................................................................59
Value expressions.................................................................................60
Predicates..............................................................................................63
Logical connectives..............................................................................64
Set functions .........................................................................................64
Subqueries.............................................................................................66
Data Control Language ..................................................................................66
Transactions .........................................................................................66
Users and privileges.............................................................................67
Referential integrity constraints can jeopardize your data ............70
Delegating responsibility for security ...............................................72

Part II: Using SQL to Build Databases ..........................73
Chapter 4: Building and Maintaining a Simple
Database Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75
Building a Simple Database Using a RAD Tool ...........................................76
Deciding what to track.........................................................................76
Creating a table with Design View......................................................77


Table of Contents
Altering the table structure.................................................................80
Identifying a primary key ....................................................................82
Creating an index..................................................................................83
Deleting a table .....................................................................................85
Building PowerDesign with SQL’s DDL ........................................................86
Using SQL with Microsoft Access.......................................................87
Creating a table.....................................................................................87
Creating an index..................................................................................88
Altering the table structure.................................................................89
Deleting a table .....................................................................................89
Deleting an index ..................................................................................90
Portability Considerations............................................................................90

Chapter 5: Building a Multitable Relational Database . . . . . . . . . . . . .91
Designing a Database.....................................................................................91
Step 1: Defining objects .......................................................................92
Step 2: Identifying tables and columns..............................................92
Step 3: Defining tables .........................................................................93
Domains, character sets, collations, and translations ....................97
Getting into your database fast with keys.........................................98
Working with Indexes ..................................................................................100
What’s an index, anyway? .................................................................101
Why you should want an index ........................................................102
Maintaining an index..........................................................................103
Maintaining Integrity ...................................................................................104
Entity integrity ....................................................................................104
Domain integrity.................................................................................105
Referential integrity ...........................................................................106
Just when you thought it was safe ...................................................109
Potential problem areas ....................................................................109
Constraints..........................................................................................111
Normalizing the Database ...........................................................................114
First normal form................................................................................116
Second normal form...........................................................................117
Third normal form..............................................................................118
Domain-key normal form (DK/NF)....................................................119
Abnormal form....................................................................................120

Part III: Storing and Retrieving Data ..........................121
Chapter 6: Manipulating Database Data . . . . . . . . . . . . . . . . . . . . . . . .123
Retrieving Data .............................................................................................124
Creating Views ..............................................................................................125
From tables..........................................................................................126
With a selection condition ................................................................127
With a modified attribute ..................................................................128
Updating Views.............................................................................................129

xi


xii

SQL For Dummies, 6th Edition
Adding New Data..........................................................................................130
Adding data one row at a time..........................................................130
Adding data only to selected columns ............................................132
Adding a block of rows to a table.....................................................132
Updating Existing Data ................................................................................135
Transferring Data .........................................................................................138
Deleting Obsolete Data................................................................................139

Chapter 7: Specifying Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
Values.............................................................................................................141
Row values ..........................................................................................142
Literal values.......................................................................................142
Variables ..............................................................................................144
Special variables.................................................................................146
Column references .............................................................................146
Value Expressions ........................................................................................147
String value expressions....................................................................148
Numeric value expressions ...............................................................149
Datetime value expressions ..............................................................149
Interval value expressions ................................................................150
Conditional value expressions..........................................................150
Functions.......................................................................................................151
Summarizing by using set functions ................................................151
Value functions ...................................................................................154

Chapter 8: Using Advanced SQL Value Expressions . . . . . . . . . . . . . .163
CASE Conditional Expressions ...................................................................163
Using CASE with search conditions .................................................164
Using CASE with values .....................................................................166
A special CASE — NULLIF..................................................................168
Another special CASE — COALESCE................................................170
CAST Data-Type Conversions .....................................................................170
Using CAST within SQL ......................................................................172
Using CAST between SQL and the host language...........................172
Row Value Expressions................................................................................173

Chapter 9: Zeroing In on the Data You Want . . . . . . . . . . . . . . . . . . . . .175
Modifying Clauses ........................................................................................175
FROM Clauses...............................................................................................177
WHERE Clauses ............................................................................................177
Comparison predicates .....................................................................179
BETWEEN ............................................................................................180
IN and NOT IN .....................................................................................181
LIKE and NOT LIKE.............................................................................182
SIMILAR................................................................................................184
NULL.....................................................................................................184
ALL, SOME, ANY .................................................................................185
EXISTS ..................................................................................................188


Table of Contents
UNIQUE ................................................................................................189
DISTINCT .............................................................................................189
OVERLAPS ...........................................................................................190
MATCH .................................................................................................190
Referential integrity rules and the MATCH predicate....................192
Logical Connectives.....................................................................................194
AND ......................................................................................................194
OR .........................................................................................................195
NOT ......................................................................................................195
GROUP BY Clauses.......................................................................................196
HAVING Clauses............................................................................................197
ORDER BY Clauses.......................................................................................198

Chapter 10: Using Relational Operators . . . . . . . . . . . . . . . . . . . . . . . .201
UNION ............................................................................................................201
The UNION ALL operation.................................................................203
The CORRESPONDING operation .....................................................203
INTERSECT....................................................................................................204
EXCEPT..........................................................................................................205
Various Joins.................................................................................................206
Basic join .............................................................................................206
Equi-join...............................................................................................208
Cross join.............................................................................................210
Natural join..........................................................................................210
Condition join .....................................................................................211
Column-name join ..............................................................................211
Inner join .............................................................................................212
Outer join ............................................................................................213
Union join ............................................................................................216
ON versus WHERE........................................................................................223

Chapter 11: Delving Deep with Nested Queries . . . . . . . . . . . . . . . . .225
What Subqueries Do ....................................................................................226
Nested queries that return sets of rows..........................................227
Nested queries that return a single value .......................................230
The ALL, SOME, and ANY quantifiers ..............................................233
Nested queries that are an existence test.......................................235
Other correlated subqueries ............................................................236
UPDATE, DELETE, and INSERT statements .....................................240

Chapter 12: Recursive Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243
What Is Recursion? ......................................................................................243
Houston, we have a problem ............................................................244
Failure is not an option......................................................................244
What Is a Recursive Query?........................................................................246
Where Might You Use a Recursive Query? ...............................................247
Querying the hard way ......................................................................248
Saving time with a recursive query..................................................249
Where Else Might You Use a Recursive Query? .......................................252

xiii


xiv

SQL For Dummies, 6th Edition

Part IV: Controlling Operations...................................253
Chapter 13: Providing Database Security . . . . . . . . . . . . . . . . . . . . . . .255
The SQL Data Control Language ................................................................256
User Access Levels ......................................................................................256
The database administrator .............................................................256
Database object owners ....................................................................257
The public ...........................................................................................257
Granting Privileges to Users .......................................................................258
Roles.....................................................................................................260
Inserting data ......................................................................................260
Looking at data ...................................................................................260
Modifying table data ..........................................................................261
Deleting obsolete rows from a table ................................................262
Referencing related tables.................................................................262
Using domains, character sets, collations, and translations........263
Causing SQL statements to be executed .........................................264
Granting the Power to Grant Privileges ....................................................265
Taking Privileges Away ................................................................................266
Using GRANT and REVOKE Together to Save Time and Effort ..............268

Chapter 14: Protecting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .269
Threats to Data Integrity .............................................................................269
Platform instability.............................................................................270
Equipment failure ...............................................................................270
Concurrent access..............................................................................271
Reducing Vulnerability to Data Corruption ..............................................273
Using SQL transactions......................................................................274
The default transaction .....................................................................275
Isolation levels ....................................................................................276
The implicit transaction-starting statement ...................................278
SET TRANSACTION ............................................................................278
COMMIT...............................................................................................279
ROLLBACK...........................................................................................279
Locking database objects..................................................................280
Backing up your data .........................................................................281
Savepoints and subtransactions ......................................................281
Constraints Within Transactions ...............................................................282

Chapter 15: Using SQL within Applications . . . . . . . . . . . . . . . . . . . . .287
SQL in an Application ..................................................................................288
Keeping an eye out for the asterisk .................................................288
SQL strengths and weaknesses ........................................................289
Procedural language strengths and weaknesses............................289
Problems in combining SQL with a procedural language .............290


Table of Contents
Hooking SQL into Procedural Languages..................................................291
Embedded SQL ...................................................................................291
Module language ................................................................................294
Object-oriented RAD tools ................................................................296
Using SQL with Microsoft Access.....................................................297

Part V: Taking SQL to the Real World .........................301
Chapter 16: Accessing Data with ODBC and JDBC . . . . . . . . . . . . . . .303
ODBC..............................................................................................................304
The ODBC interface............................................................................304
Components of ODBC ........................................................................304
ODBC in a Client/Server Environment.......................................................305
ODBC and the Internet ................................................................................306
Server extensions ...............................................................................307
Client extensions ................................................................................308
ODBC and an Intranet..................................................................................319
JDBC...............................................................................................................310

Chapter 17: Operating on XML Data with SQL . . . . . . . . . . . . . . . . . . .313
How XML Relates to SQL.............................................................................313
The XML Data Type......................................................................................314
When to use the XML type ................................................................314
When not to use the XML type .........................................................315
Mapping SQL to XML and XML to SQL ......................................................316
Mapping character sets .....................................................................316
Mapping identifiers ............................................................................316
Mapping data types............................................................................317
Mapping tables ...................................................................................318
Handling null values...........................................................................318
Generating the XML Schema.............................................................319
SQL Functions that Operate on XML Data ................................................320
XMLELEMENT .....................................................................................320
XMLFOREST ........................................................................................321
XMLCONCAT .......................................................................................321
XMLAGG ..............................................................................................322
XMLCOMMENT ...................................................................................322
XMLPARSE ...........................................................................................323
XMLPI ...................................................................................................323
XMLQUERY..........................................................................................323
XMLCAST.............................................................................................324
Predicates .....................................................................................................324
DOCUMENT .........................................................................................325
CONTENT ............................................................................................325

xv


xvi

SQL For Dummies, 6th Edition
XMLEXISTS ..........................................................................................325
VALID....................................................................................................326
Transforming XML Data into SQL Tables ..................................................326
Mapping Non-Predefined Data Types to XML...........................................328
Domain.................................................................................................328
Distinct UDT........................................................................................329
Row.......................................................................................................329
Array ....................................................................................................330
Multiset................................................................................................331
The Marriage of SQL and XML....................................................................332

Part VI: Advanced Topics ...........................................333
Chapter 18: Stepping through a Dataset with Cursors . . . . . . . . . . . .335
Declaring a Cursor .......................................................................................336
The query expression ........................................................................337
The ORDER BY clause........................................................................337
The updatability clause .....................................................................338
Sensitivity ............................................................................................339
Scrollability .........................................................................................340
Opening a Cursor .........................................................................................340
Fetching Data from a Single Row................................................................342
Syntax...................................................................................................342
Orientation of a scrollable cursor ....................................................343
Positioned DELETE and UPDATE statements .................................343
Closing a Cursor ...........................................................................................344

Chapter 19: Adding Procedural Capabilities with
Persistent Stored Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .345
Compound Statements ................................................................................345
Atomicity .............................................................................................346
Variables ..............................................................................................347
Cursors ................................................................................................348
Conditions ...........................................................................................348
Handling conditions ...........................................................................349
Conditions that aren’t handled.........................................................351
Assignment..........................................................................................352
Flow of Control Statements.........................................................................352
IF...THEN...ELSE...END IF ....................................................................352
CASE...END CASE ................................................................................353
LOOP...ENDLOOP................................................................................354
LEAVE ...................................................................................................355
WHILE...DO...END WHILE...................................................................355
REPEAT...UNTIL...END REPEAT .........................................................356


Table of Contents
FOR...DO...END FOR............................................................................356
ITERATE ...............................................................................................356
Stored Procedures .......................................................................................357
Stored Functions ..........................................................................................358
Privileges.......................................................................................................359
Stored Modules ............................................................................................359

Chapter 20: Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .361
SQLSTATE ......................................................................................................361
WHENEVER Clause.......................................................................................363
Diagnostics Areas.........................................................................................364
The diagnostics header area.............................................................364
The diagnostics detail area ...............................................................366
Constraint violation example............................................................368
Adding constraints to an existing table...........................................369
Interpreting the information returned by SQLSTATE.....................370
Handling Exceptions ....................................................................................371

Part VII: The Part of Tens...........................................373
Chapter 21: Ten Common Mistakes . . . . . . . . . . . . . . . . . . . . . . . . . . . .375
Assuming That Your Clients Know What They Need ..............................375
Ignoring Project Scope ................................................................................376
Considering Only Technical Factors..........................................................376
Not Asking for Client Feedback ..................................................................376
Always Using Your Favorite Development Environment ........................377
Using Your Favorite System Architecture Exclusively ............................377
Designing Database Tables in Isolation.....................................................377
Neglecting Design Reviews .........................................................................378
Skipping Beta Testing ..................................................................................378
Not Documenting Your Process .................................................................378

Chapter 22: Ten Retrieval Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .379
Verify the Database Structure.....................................................................379
Try Queries on a Test Database .................................................................380
Double-Check Queries That Include Joins ................................................380
Triple-Check Queries with Subselects.......................................................380
Summarize Data with GROUP BY ...............................................................380
Watch GROUP BY Clause Restrictions ......................................................381
Use Parentheses with AND, OR, and NOT.................................................381
Control Retrieval Privileges ........................................................................381
Back Up Your Databases Regularly............................................................382
Handle Error Conditions Gracefully ..........................................................382

xvii


xviii

SQL For Dummies, 6th Edition

Part VIII: Appendixes ................................................383
Appendix A: SQL:2003 Reserved Words . . . . . . . . . . . . . . . . . . . . . . . .385
Appendix B: Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .389

Index........................................................................397


Introduction

W

elcome to database development using the industry structured query
language (SQL). Many database management system (DBMS) tools
run on a variety of hardware platforms. The differences among the tools can
be great, but all serious products have one thing in common: They support
SQL data access and manipulation. If you know SQL, you can build relational
databases and get useful information out of them.

About This Book
Relational database management systems are vital to many organizations.
People often think that creating and maintaining these systems are extremely
complex activities — the domain of database gurus who possess enlightenment beyond that of ordinary mortals. This book sweeps away the database
mystique. In this book, you
ߜ Get to the roots of databases.
ߜ Find out how a DBMS is structured.
ߜ Discover the major functional components of SQL.
ߜ Build a database.
ߜ Protect a database from harm.
ߜ Operate on database data.
ߜ Determine how to get the information you want out of a database.
The purpose of this book is to help you build relational databases and get valuable information out of them by using SQL. SQL is the international standard
language used around the world to create and maintain relational databases.
This edition covers the latest version of the standard, SQL:2003, as augmented
in 2005 with a thorough treatment of the use of XML with SQL.
This book doesn’t tell you how to design a database (I do that in Database
Development For Dummies, also published by Wiley Publishing, Inc.). Here I
assume that you or somebody else has already created a valid design. I then
illustrate how you implement that design by using SQL. If you suspect that
you don’t have a good database design, by all means, fix your design before
you try to build the database. The earlier you detect and correct problems in
a development project, the cheaper the corrections will be.


2

SQL For Dummies, 6th Edition

Who Should Read This Book?
If you need to store or retrieve data from a DBMS, you can do a much better
job with a working knowledge of SQL. You don’t need to be a programmer to
use SQL, and you don’t need to know programming languages, such as Java,
C, or BASIC. SQL’s syntax is like English.
If you are a programmer, you can incorporate SQL into your programs. SQL
adds powerful data manipulation and retrieval capability to conventional
languages. This book tells you what you need to know to use SQL’s rich
assortment of tools and features inside your programs.

How This Book Is Organized
This book contains eight major parts. Each part contains several chapters.
You may want to read this book from cover to cover once, although you don’t
have to. After that, this book becomes a handy reference guide. You can turn
to whatever section is appropriate to answer your questions.

Part I: Basic Concepts
Part I introduces the concept of a database and distinguishes relational databases from other types. It describes the most popular database architectures,
as well as the major components of SQL.

Part II: Using SQL to Build Databases
You don’t need SQL to build a database. This part shows how to build a database by using Microsoft Access, and then you get to build the same database
by using SQL. In addition to defining database tables, this part covers other
important database features: domains, character sets, collations, translations,
keys, and indexes.
Throughout this part, I emphasize protecting your database from corruption,
which is a bad thing that can happen in many ways. SQL gives you the tools
to prevent corruption, but you must use them properly to prevent problems
caused by bad database design, harmful interactions, operator error, and
equipment failure.


Introduction

Part III: Storing and Retrieving Data
After you have some data in your database, you want to do things with it:
Add to the data, change it, or delete it. Ultimately, you want to retrieve
useful information from the database. SQL tools enable you to do all this.
These tools give you low-level, detailed control over your data.

Part IV: Controlling Operations
A big part of database management is protecting the data from harm, which
can come in many shapes and forms. People may accidentally or intentionally put bad data into database tables, for example. You can protect yourself
by controlling who can access your database and what they can do. Another
threat to data comes from unintended interaction of concurrent users’ operations. SQL provides powerful tools to prevent this too. SQL provides much of
the protection automatically, but you need to understand how the protection
mechanisms work so you get all the protection you need.

Part V: Taking SQL to the Real World
SQL is different from most other computer languages in that it operates on a
whole set of data items at once, rather than dealing with them one at a time.
This difference in operational modes makes combining SQL with other languages a challenge, but you can face it by using the information in this book.
You can exchange information with nondatabase applications by using XML.
I also describe in depth how to use SQL to transfer data across the Internet
or an intranet.

Part VI: Advanced Topics
In this part, you discover how to include set-oriented SQL statements in your
programs and how to get SQL to deal with data one item at a time.
This part also covers error handling. SQL provides you with a lot of information whenever something goes wrong in the execution of an SQL statement,
and you find out how to retrieve and interpret that information.

3


4

SQL For Dummies, 6th Edition

Part VII: The Part of Tens
This section provides some important tips on what to do, and what not to do,
in designing, building, and using a database.

Part VIII: Appendixes
Appendix A lists all of SQL’s reserved words, as of the 2005 release of Part 14 of
the ANSI/ISO SQL standard. These are words that have a very specific meaning in SQL and cannot be used for table names, column names, or anything
other than their intended meaning. Appendix B gives you a basic glossary on
some frequently used terms.

Icons Used in This Book
Tips save you a lot of time and keep you out of trouble.

Pay attention to the information marked by this icon — you may need it later.

Heeding the advice that this icon points to can save you from major grief.
Ignore it at your peril.

This icon alerts you to the presence of technical details that are interesting
but not absolutely essential to understanding the topic being discussed.

Getting Started
Now for the fun part! Databases are the best tools ever invented for keeping
track of the things you care about. After you understand databases and can use
SQL to make them do your bidding, you wield tremendous power. Co-workers
come to you when they need critical information. Managers seek your advice.
Youngsters ask for your autograph. But most importantly, you know, at a very
deep level, how your organization really works.


Part I

Basic Concepts


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×