Wiley SQL For Dummies 6th Edition Aug 2006 ISBN 047004652X pdf

  www.dbebooks.com - Free Books & magazines

  

SQL

FOR

DUMmIES

  ‰

  6 TH EDITION

by Allen G. Taylor

  

Author of Database Development For Dummies

® and Crystal Reports

  ®

  10 For Dummies ®

  

SQL

FOR

DUMmIES

  ‰

  6 TH 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 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 permit-

ted 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 REP-

RESENTATIONS 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 CRE-

ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON-

TAINED 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 FUR-

THER 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 archi- tecture 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 .

  Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development

  Project Editor: Nicole Haims (Previous Edition: Kala Schrager)

  Acquisitions Editor: Tiffany Ma Technical Editor: Greg Guntle Editorial Manager: Jodi Jensen Media Development Manager:

  Laura VanWinkle Editorial Assistant: Amanda Foxworth Sr. Editorial Assistant: Cherie Case Cartoons: Rich Tennant

  (www.the5thwave.com) Composition Services

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

  Proofreaders: Leeann Harney, Christy Pingleton, Techbooks

  Indexer: Techbooks 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

  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

  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

  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

  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