.9 Data Files and Databases ...9 Irreducible complexity...10 The complex program/simple data organization ...10 The simple program/complex data organization ...12 Which type of organizat
Trang 4A L L - I N - O N E D E S K R E F E R E N C E
FOR
Trang 7SQL All-in-One Desk Reference For Dummies ®
Published by
Wiley Publishing, Inc.
111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2007 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 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.
permit-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.
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 TENT 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
COMPE-IS READ
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: 2007926383 ISBN: 978-0-470-11928-0
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Trang 8About the Author
Allen G Taylor is a 30-year veteran of the computer industry and the author
of 25 books, including SQL For Dummies, Crystal Reports 10 For Dummies,
Database Development For Dummies, Access 2003 Power Programming with VBA, and SQL Weekend Crash Course He lectures internationally on data-
bases, networks, innovation, and entrepreneurship He also teaches databasedevelopment through a leading online education provider and teaches micro-processor design at Portland State University For the latest news on Allen’sactivities, check out www.DatabaseCentral.Info You can contact Allen atallen.taylor@ieee.org
Trang 10This book is dedicated to Joyce Carolyn Taylor, who still puts up with meafter all these years
Trang 12Author’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, thisbook, and indeed SQL itself as an international standard, would be of muchless value Andrew Eisenberg has also contributed to my knowledge of SQLthrough his writing I would also like to thank my project editor, NicoleSholly, and my acquisitions editor, Kyle Looper, for their key contributions tothe production of this book Thanks also to my agent, Carole McClendon ofWaterside Productions, for her support of my career
Trang 13Publisher’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
Project Editor: Nicole Sholly Acquisitions Editor: Kyle Looper Copy Editor: Linda Morris Technical Editor: Robert Schneider Editorial Manager: Kevin Kirschner Media Development and Quality Assurance:
Angela Denny, Kate Jenkins, Steven Kudirka, Kit Malone
Media Development Coordinator:
Jenny Swisher
Media Project Supervisor:
Laura Moss-Hollister
Editorial Assistant: Amanda Foxworth
Sr Editorial Assistant: Cherie Case Cartoons: Rich Tennant
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
Trang 14Contents at a Glance
Introduction 1
Book I: SQL Concepts 7
Chapter 1: Relational Database Basics 9
Chapter 2: Modeling a System 27
Chapter 3: SQL Overview 49
Chapter 4: SQL and the Relational Model 59
Chapter 5: The Major Components of SQL 67
Chapter 6: SQL Characteristics 89
Book II: Relational Database Development 117
Chapter 1: System Development Overview 119
Chapter 2: Building a Database Model 135
Chapter 3: Balancing Performance and Correctness 159
Chapter 4: Creating a Database with SQL 189
Book III: SQL Queries 201
Chapter 1: Values, Variables, Functions, and Expressions 203
Chapter 2: SELECT Statements and Modifying Clauses 227
Chapter 3: Querying Multiple Tables with Subqueries 269
Chapter 4: Querying Multiple Tables with Relational Operators 297
Chapter 5: Cursors 315
Book IV: Data Security 325
Chapter 1: Protecting Against Hardware Failure and External Threats 327
Chapter 2: Protecting Against User Errors and Conflicts 343
Chapter 3: Assigning Access Privileges 371
Chapter 4: Error Handling 383
Book V: SQL and Programming 397
Chapter 1: Database Development Environments 399
Chapter 2: Interfacing SQL to a Procedural Language 403
Chapter 3: Using SQL in an Application Program 409
Chapter 4: Designing a Sample Application 423
Chapter 5: Building a Sample Application 443
Chapter 6: SQL’s Procedural Capabilities 459
Chapter 7: Connecting to a Remote Database 475
Trang 15Book VI: SQL and XML 489
Chapter 1: XML/SQL Basics 491
Chapter 2: Storing XML Data in SQL Tables 515
Chapter 3: Retrieving Data from XML Documents 535
Book VII: Database Tuning Overview 551
Chapter 1: Tuning the Database 553
Chapter 2: Tuning the Environment 565
Chapter 3: Finding and Eliminating Bottlenecks 587
Book VIII: Appendixes 619
Appendix A: SQL:2003 Reserved Words 621
Appendix B: Glossary 629
Index 639
Trang 16Table of Contents
Introduction 1
About This Book 1
Foolish Assumptions 2
Conventions Used in This Book 2
What You Don’t Have to Read 3
How This Book Is Organized 3
Book I: SQL Concepts 3
Book II: Relational Database Development 3
Book III: SQL Queries 4
Book IV: Data Security 4
Book V: SQL and Programming 4
Book VI: SQL and XML 4
Book VII: Database Tuning Overview 5
Book VIII: Appendixes 5
Icons Used in This Book 5
Where to Go from Here 6
Book I: SQL Concepts 7
Chapter 1: Relational Database Basics 9
Data Files and Databases 9
Irreducible complexity 10
The complex program/simple data organization 10
The simple program/complex data organization 12
Which type of organization is better? 12
Databases, Queries, and Database Applications 13
Making data useful 14
Retrieving the data you want — and only the data you want 14
Competing Database Models 14
The hierarchical database model 15
The network database model 17
The relational database model 20
What makes a database relational? 20
Codd’s Rules 20
Inherent flexibility 23
The object-oriented database 23
The object-relational database 23
Why Did the Relational Model Win? 24
Trang 17SQL All-in-One Desk Reference For Dummies
xiv
Chapter 2: Modeling a System 27
Capturing the Users’ Data Model 27
Identifying and interviewing stakeholders 27
Reconciling conflicting requirements 28
Obtaining stakeholder buy-in 29
Translating the Users’ Data Model to a Relational Model 29
Entity-Relationship modeling techniques 29
Entities 30
Attributes 30
Identifiers 31
Relationships 31
Drawing Entity-Relationship diagrams 34
Maximum cardinality 34
Minimum cardinality 35
Advanced E-R model concepts 37
Strong entities and weak entities 37
ID-dependent entities 39
Supertype and subtype entities 39
Incorporating business rules 40
A simple example of an E-R model 41
A slightly more complex example 42
Problems with complex relationships 46
Simplifying relationships using normalization 47
Translating an E-R model into a relational model 47
The Relational Database Hierarchy 47
Chapter 3: SQL Overview 49
Where SQL Came From 49
What SQL Does 50
The ANSI/ISO SQL Standard 51
What SQL Does Not Do 51
Available Implementations 52
Microsoft Access 52
Microsoft SQL Server 56
IBM DB2 56
Oracle 56
InterBase 57
MySQL 57
PostgreSQL 57
Chapter 4: SQL and the Relational Model 59
Sets, Relations, Multisets, and Tables 59
Functional Dependencies 60
Keys 61
Views 62
Trang 18Table of Contents xv
Users 63
Privileges 63
Schemas 64
Catalogs 64
Connections, Sessions, and Transactions 64
Routines 65
Paths 66
Chapter 5: The Major Components of SQL 67
The Data Definition Language (DDL) 67
The containment hierarchy 67
Creating tables 68
Specifying columns 68
Specifying constraints .69
Column constraints 70
Table constraints 71
Assertions 71
Creating other objects 72
Views 72
Schemas 77
Domains 77
Modifying tables and other objects 78
Removing tables and other objects 78
The Data Manipulation Language (DML) 78
Retrieving data from a database 79
Adding data to a table 80
Adding data the dull and boring way (typing it in) 80
Adding incomplete data 81
Adding data in the fastest and most efficient way: Bypassing typing altogether 81
Updating data in a table 81
Deleting data from a table 84
Updating views 85
The Data Control Language (DCL) 86
Granting access privileges 86
Revoking access privileges 87
Preserving database integrity with transactions .87
Chapter 6: SQL Characteristics 89
Executing SQL Statements 89
Interactive SQL 90
Challenges to combining SQL with a host language 90
Embedded SQL 91
Module language 93
Using Reserved Words Correctly 94
Trang 19SQL All-in-One Desk Reference For Dummies
xvi
SQL’s Data Types 94
Exact numerics 95
INTEGER 95
SMALLINT 96
BIGINT 96
NUMERIC 96
DECIMAL 96
BINARY LARGE OBJECT (BLOB) 97
Approximate numerics 97
REAL 97
DOUBLE PRECISION 98
FLOAT 98
Character strings 99
CHARACTER 99
CHARACTER VARYING 99
CHARACTER LARGE OBJECT (CLOB) 99
NATIONAL CHARACTER, NATIONAL CHARACTER VARYING, and NATIONAL CHARACTER LARGE OBJECT 100
Booleans 101
Datetimes 101
DATE 101
TIME WITHOUT TIME ZONE 101
TIME WITH TIME ZONE 102
TIMESTAMP WITHOUT TIME ZONE 102
TIMESTAMP WITH TIME ZONE 102
Intervals 103
XML type 103
Row types 104
Collection types 105
ARRAY 105
Multiset 105
REF types 106
User-defined types 106
Distinct types 106
Structured types 107
Data type summary 109
Handling Null Values 110
Applying Constraints 111
Column constraints 111
NOT NULL 111
UNIQUE 112
CHECK 112
Table constraints 113
Foreign key constraints 114
Assertions 115
Trang 20Table of Contents xvii
Book II: Relational Database Development 117
Chapter 1: System Development Overview 119
The Components of a Database System 119
The database 120
The database engine 120
The DBMS front end 120
The database application 120
The user 121
The System Development Life Cycle 121
Definition phase 122
Requirements phase 123
Establishing requirements: An example 123
The users’ data model 124
Statement of Requirements 124
Evaluation phase 125
Determining project scope 126
Reassessing feasibility 127
Documenting the evaluation phase 127
Design phase 127
Designing the database 128
The database application 129
Documenting the design phase 129
Implementation phase 130
Final documentation and testing phase 130
Testing the system with sample data 131
Finalizing the documentation 132
Delivering the results (and celebrating) 132
Maintenance phase 132
Chapter 2: Building a Database Model 135
Finding and Listening to Interested Parties 135
Your immediate supervisor 136
The users 136
The standards organization 137
Upper management 137
Building Consensus 138
What do people want, and how badly do they want it? 138
Arriving at a consensus 139
The three-option proposal 139
The Entity-Relationship Modeling Method 140
Entities 140
Attributes 141
Identifiers 141
Relationships 142
Trang 21SQL All-in-One Desk Reference For Dummies
xviii
Maximum cardinality 145
Minimum cardinality 145
Business rules 147
Building a Relational Model 147
Different worlds, different terminology 147
The relational tradition 147
What exactly is a relation? 149
Functional dependencies 149
Keys 150
Being Aware of the Danger of Anomalies 150
Eliminating anomalies 152
The higher normal forms 155
The Database Integrity versus Performance Tradeoff 156
Chapter 3: Balancing Performance and Correctness 159
Designing a Sample Database 160
The E-R model for Honest Abe’s .160
Converting an E-R model into a relational model 161
Normalizing a relational model 162
Handling binary relationships 164
A sample conversion 168
Maintaining Integrity 170
Entity integrity 171
Domain integrity 172
Referential integrity 172
Avoiding Data Corruption 174
Speeding Data Retrievals 175
Hierarchical storage 176
Full table scans 177
How indexes work 177
Creating the right indexes 177
Indexes and the ANSI/ISO Standard 178
Index costs 178
Query type dictates the best index 178
Point query 178
Multipoint query 179
Range query 179
Prefix match query 179
Extremal query 179
Ordering query 180
Grouping query 180
Equi-join query 180
Data structures used for indexes 180
B+ trees 181
Hash structures 181
Indexes, sparse and dense 181
Index clustering 181
Composite indexes 182
Trang 22Table of Contents xix
Index effect on join performance 183Table size as an indexing consideration 183Indexes versus full-table scans 183Reading SQL Server Execution Plans 183Robust execution plans 183
A sample database 184
A typical query 185The execution plan 185Running the Database Engine Tuning Advisor 185Hot Tables and Load Balancing 187
Chapter 4: Creating a Database with SQL 189
First Things First: Planning Your Database 189Building Tables 190Locating table rows with keys 191Using the CREATE TABLE statement 192Setting Constraints 193Column constraints 193Table constraints 194Keys and Indexes 194Ensuring Data Validity with Domains 194Establishing Relationships between Tables 195Altering Table Structure 198Deleting Tables 199
Book III: SQL Queries 201
Chapter 1: Values, Variables, Functions, and Expressions 203
Entering Data Values 203Row values have multiple parts 203Identifying values in a column 204Literal values don’t change 204Variables Vary 205Special Variables Hold Specific Values 206Working with Functions 207Summarizing data with set functions 207COUNT 207AVG 208MAX 208MIN 209SUM 209Dissecting data with value functions 209String value functions 209Numeric value functions 212Datetime value functions 216
Trang 23SQL All-in-One Desk Reference For Dummies
xx
Using Expressions 217Numeric value expressions 217String value expressions 218Datetime value expressions 218Interval value expressions 219Boolean value expressions 219Array value expressions 220Conditional value expressions 220Handling different cases 221The NULLIF special CASE 222Bypassing null values with COALESCE 223Converting data types with a CAST expression 223Casting one SQL data type to another 224Using CAST to overcome data type incompatibilities
between SQL and its host language 224Row value expressions 225
Chapter 2: SELECT Statements and Modifying Clauses 227
Finding Needles in Haystacks with the SELECT Statement 227Modifying Clauses 228FROM clauses 228WHERE clauses 229Comparison predicates 230BETWEEN 231
IN and NOT IN 232LIKE and NOT LIKE 234SIMILAR 235NULL 235ALL, SOME, ANY 236EXISTS 239UNIQUE 240DISTINCT 240OVERLAPS 241MATCH 241The MATCH predicate and referential integrity 243Logical connectives 245AND 245
OR 246NOT 247GROUP BY clauses 247HAVING clauses 249ORDER BY clauses 249Tuning Queries 251SELECT DISTINCT 252Temporary tables 255The ORDER BY clause 259The HAVING clause 262The OR logical connective 266
Trang 24Table of Contents xxi
Chapter 3: Querying Multiple Tables with Subqueries 269
What Is a Subquery? 269What Subqueries Do 269Subqueries that return multiple values 270Subqueries that retrieve rows satisfying a condition 270Subqueries that retrieve rows that
don’t satisfy a condition 271Subqueries that return a single value 272Quantified subqueries return a single value 275Correlated subqueries 277Using a subquery as an existence test 278Introducing a correlated subquery with the IN keyword 279Introducing a correlated subquery
with a comparison operator 279Correlated subqueries in a HAVING clause 281Using Subqueries in INSERT, DELETE, and UPDATE Statements 282Tuning Considerations for Statements Containing Nested Queries 285Tuning Correlated Subqueries 290
Chapter 4: Querying Multiple Tables with Relational Operators 297
UNION 297UNION ALL 299UNION CORRESPONDING 300INTERSECT 300EXCEPT 302JOINS 303Cartesian product or cross join 303Equi-join 305Natural join 307Condition join 307Column-name join 308Inner join 309Outer join 310Left outer join 310Right outer join 312Full outer join 313
ON versus WHERE 313Join Conditions and Clustering Indexes 314
Chapter 5: Cursors 315
Declaring a Cursor 316The query expression 317Ordering the query result set 317Updating table rows 319Sensitive versus insensitive cursors 319Scrolling a cursor 320
Trang 25SQL All-in-One Desk Reference For Dummies
xxii
Opening a Cursor 320Fetching Data from a Single Row 322FETCH syntax 322Absolute versus relative fetches 323Deleting a row 323Updating a row 324Closing a Cursor 324
Book IV: Data Security 325
Chapter 1: Protecting Against Hardware Failure and External Threats 327
What Could Possibly Go Wrong? 327Equipment failure 328Platform instability 329Database design flaws 330Data entry error 330Operator error 331Taking Advantage of RAID 331Striping 332RAID levels 332RAID 0 332RAID 1 334RAID 5 334RAID 10 334RAID level comparison 335Backing Up Your System 335Preparing for the worst 335Full or incremental backup 336Frequency 336Backup maintenance 337Coping with Internet Threats 337Viruses 337Worms 338Denial-of-service attacks 339Phishing scams 339Zombie spambots 339Installing Layers of Protection 340Network layer firewalls 340Application layer firewalls 340Antivirus software 340Vulnerabilities, exploits, and patches 341Education 341Alertness 341
Trang 26Table of Contents xxiii
Chapter 2: Protecting Against User Errors and Conflicts 343
Reducing Data Entry Errors 343Data types: the first line of defense 344Constraints: the second line of defense 344Sharp-eyed humans: the third line of defense 345Unreliable Database Design 345Programming Errors 345Conflicts Arising from Concurrent Operation 346Atomicity, Consistency, Isolation, and Durability 347Operating with Transactions 348Using the SET TRANSACTION statement 348Starting a transaction 349Access modes 350Isolation levels 350Committing a transaction 352Rolling back a transaction 352Why roll back a transaction? 353The log file 353The write-ahead log protocol 354Checkpoints 355Implementing deferrable constraints 355Getting Familiar with Locking 360Two-phase locking 360Granularity 361Deadlock 361Tuning Locks 362Measuring performance with throughput 363Eliminating unneeded locks 363Shortening transactions 363Weaken isolation levels (but ver-r-ry carefully) 364Controlling lock granularity 365Don’t run DDL statements concurrently with transactions 365Partitioning insertions 365Cooling down hot spots 365Tuning the deadlock interval 366Enforcing Serializability with Timestamps 366Tuning the Recovery System 369
Chapter 3: Assigning Access Privileges 371
The SQL Data Control Language 371Identifying Authorized Users 372User identifiers 372Getting familiar with Roles 372Creating roles 373Destroying roles 373
Trang 27SQL All-in-One Desk Reference For Dummies
xxiv
Classifying Users 373Granting Privileges 374Looking at data 375Deleting data 375Adding data 376Changing data 376Referencing data in another table 376Using certain database facilities 378Responding to an event 378Defining new data types 378Executing an SQL statement 378Doing it all 379Passing on the power 379Revoking Privileges 380Granting Roles 381Revoking Roles 381
Chapter 4: Error Handling 383
Identifying Error Conditions 383Getting to Know SQLSTATE 384Handling Conditions 386Handler declarations 386Handler actions and handler effects 387Conditions that aren’t handled 388Dealing with Execution Exceptions: The WHENEVER Clause 388Getting More Information: The Diagnostics Areas 389The diagnostics header area 390The diagnostics detail area 391Examining a Constraint Violation Example 393Adding Constraints to an Existing Table 394Interpreting SQLSTATE Information 394Handling Exceptions 395
Book V: SQL and Programming 397
Chapter 1: Database Development Environments 399
Microsoft Access 399The Jet engine 400DAO 400ADO 400ODBC 400OLE DB 400MDB 401ACCDB 401
Trang 28Table of Contents xxv
Microsoft SQL Server 401IBM DB2 401Oracle 10g 402MySQL 402
Chapter 2: Interfacing SQL to a Procedural Language 403
Building an Application with SQL and a Procedural Language 403Access and VBA 404The ADODB library 404The ADOX library 405Other libraries 405SQL Server and the NET languages 405MySQL and C++.NET or C# 406MySQL and C 406MySQL and Perl 406MySQL and PHP 407Oracle SQL and Java 407DB2 and Java 407
Chapter 3: Using SQL in an Application Program 409
Comparison of SQL to Procedural Languages 409Classic procedural languages 410Object-oriented procedural languages 411Non-procedural languages 411Difficulties in Combining SQL with a Procedural Language 412Challenges to using SQL with a classical procedural language 412Contrasting operating modes 412Data type incompatibilities 413Challenges to using SQL with an object-oriented
procedural language 413Embedding SQL in an Application 414Embedding SQL in an Oracle Pro*C application 414Declaring host variables 416Converting data types 416Embedding SQL in an Java application 417Using SQL in a Perl application 417Embedding SQL in a PHP application 417Using SQL with a Visual Basic NET application 418Using SQL with other NET languages 418Using SQL Modules with an Application 418Module declarations 419Module procedures 420Modules in Oracle 421
Trang 29SQL All-in-One Desk Reference For Dummies
xxvi
Chapter 4: Designing a Sample Application 423
The Client’s Problem 423Approaching the Problem 424Interviewing the stakeholders 424Drafting a detailed statement of requirements 425Following up with a proposal 425Determining the Deliverables 426Finding out what’s needed now and later 426Planning for organization growth 427Nailing down project scope 428Building an Entity-Relationship Model 429Determining what the entities are 429Relating the entities to each other 429Relationships 430Maximum cardinality 430Minimum cardinality 431Business rules 431Deep thinking 432Transforming the Model 432Eliminating any many-to-many relationships 433Normalizing the E-R model 435Creating Tables 437Changing Table Structure 440Removing Tables 440Designing the User Interface 441
Chapter 5: Building a Sample Application 443
Designing from the Top Down 443Determining what the application should include 444Designing the user interface 444Connecting the user interface to the database 445Coding from the Bottom Up 447Work to do before starting to build the application 447Create the database 448Fill database tables with sample data 449Creating the application’s building blocks 454Developing screen forms 454Developing reports 455Gluing everything together 455Testing, Testing, Testing 455Fix the bugs 456Turn naive users loose 456Bring on the hackers 456Fix the newly found bugs 456Retest everything 457
Trang 30Table of Contents xxvii
Chapter 6: SQL’s Procedural Capabilities 459
Embedding SQL Statements in Your Code 459Introducing Compound Statements 460Atomicity 461Variables 462Cursors 462Conditions 462Assignment 463Following the Flow of Control Statements 463
IF THEN ELSE END IF 464CASE END CASE 464Simple CASE statement 464Searched CASE statement 465LOOP ENDLOOP 466LEAVE 466WHILE DO END WHILE 467REPEAT UNTIL END REPEAT 467FOR DO END FOR 468ITERATE 468Using Stored Procedures 469Working with Triggers 469Trigger events 471Trigger action time 471Triggered actions 471Triggered SQL statement 472Stored Functions 472Passing Out Privileges 473Stored Modules 473
Chapter 7: Connecting to a Remote Database 475
Native Drivers 475ODBC and Its Major Components 477Application 478Driver manager 479Drivers 479File-based drivers 480DBMS-based drivers 480Data sources 482What Happens When the Application Makes a Request 482Using handles to identify objects 482The six stages of an ODBC operation 484Stage 1: The application allocates environment and
connection handles in the driver manager 484Stage 2: The driver manager finds the appropriate driver 484Stage 3: The driver manager loads the driver 484
Trang 31SQL All-in-One Desk Reference For Dummies
xxviii
Stage 4: The driver manager allocates environment and connection handles in the driver 485Stage 5: The driver manager connects to
the data source through the driver 485Stage 6: The data source (finally)
executes an SQL statement 485
Book VI: SQL and XML 489
Chapter 1: XML/SQL Basics 491
Introducing XML 491The Parts of an XML Document 492XML declaration 493Elements 493Nested elements 494The document element 494Empty elements 494Attributes 494Entity references 495Numeric character references 496XML Schema 496Relating SQL to XML 497The XML Data Type 497When to use the XML type 498When not to use the XML type 499Mapping SQL to XML 499Mapping character sets to XML 499Mapping identifiers to XML 500Mapping data types to XML 500Mapping non-predefined data types to XML 501Domain 501Distinct UDT 502Row 503Array 504Multiset 505Mapping tables to XML 505Handling null values 506Creating an XML schema for an SQL table 507Operating on XML Data with SQL Functions 508XMLELEMENT 508XMLFOREST 509XMLCONCAT 509XMLAGG 510XMLCOMMENT 510
Trang 32Table of Contents xxix
XMLPARSE 511XMLPI 511XMLQUERY 511XMLCAST 512XML Predicates 512DOCUMENT 512CONTENT 513XMLEXISTS 513VALID 513
Chapter 2: Storing XML Data in SQL Tables 515
Inserting XML Data into an SQL Pseudo-Table 515Creating a Table to Hold XML Data 517Updating XML Documents 517Discovering Oracle’s Tools for Updating XML Data in a Table 518APPENDCHILDXML 518INSERTCHILDXML 519INSERTXMLBEFORE 520DELETEXML 521UPDATEXML 522Introducing Microsoft’s Tools for Updating XML Data in a Table 523Updategram namespace and keywords 523Specifying a mapping schema 525Implicit mapping 525Explicit mapping 526Element-centric mapping 531Attribute-centric mapping 531Mixed element-centric and attribute-centric mapping 532Schemas that allow null values 533
Chapter 3: Retrieving Data from XML Documents 535
XQuery 536Where XQuery came from 536What XQuery requires 536XQuery functionality 537Usage scenarios 538FLWOR Expressions 542The for clause 543The let clause 544The where clause 545The order by clause 545The return clause 546Comparing XQuery to SQL 547XQuery’s FLWOR expression and SQL’s SELECT expression 547Relating XQuery data types to SQL data types 547
Trang 33SQL All-in-One Desk Reference For Dummies
xxx
Book VII: Database Tuning Overview 551
Chapter 1: Tuning the Database 553
Analyzing the Workload 554Considering the Physical Design 555Choosing the Right Indexes 556Avoiding unnecessary indexes 556Choosing a column to index 557Multi-column indexes 557Clustering indexes 557Choosing index type 559Weighing the cost of index maintenance 559Composite indexes 559Tuning Indexes 560Tuning Queries 561Tuning Transactions 562Separating User Interactions from Transactions 562Minimizing Traffic between Application and Server 563Precompiling Frequently Used Queries 563
Chapter 2: Tuning the Environment 565
Surviving Failures with Minimum Data Loss 566What happens to transactions where there is no failure? 566What happens when a failure occurs before a committed
or aborted transaction is written to stable storage? 567Tuning the Recovery System 567Putting logs and transactions on different disks 569Put logs and transactions on different disks 569Hard disk drive construction 569Hard disk drive performance considerations 570Tuning write operations 572Dumps 573Checkpoints 574Optimizing batch transactions 575Tuning the Operating System 575Scheduling threads 575Threads improve throughput 576Context switching 577Round-robin scheduling 577Priority-based scheduling 577Priority inversion 578Deadlock 579Determining database buffer size 579Tuning page usage factor 580
Trang 34Table of Contents xxxi
Maximizing the Hardware You Have 580Optimizing placement of code and data on hard disks 580Tuning the page replacement algorithm 581Disk controller cache 581Adding Hardware 582Faster processor 583More RAM 583Faster hard disks 583More hard disks 583Performance advantages of RAID arrays 584Multiprocessor Environments 585
Chapter 3: Finding and Eliminating Bottlenecks 587
Pinpointing the Problem 587Slow query 588Slow update 588Determining the Possible Causes of Trouble 589Problems with indexes 589B+ tree indexes 589Index pluses and minuses 589Index-only queries 590Full table scans versus indexed table access 590Pitfalls in communication 591ODBC/JDBC versus native drivers 591Locking and client performance 592Application development tools making
suboptimal decisions 592Determining whether hardware is robust
enough and configured properly 593Implementing General Pointers: A First Step
Toward Improving Performance 593Avoid direct user interaction 593Examine the application/database interaction 594Don’t ask for columns that you don’t need 594Don’t use cursors unless you absolutely have to 594Precompile queries 595Tracking Down Bottlenecks 595Isolating performance problems 595Performing a top-down analysis 595Partitioning 597Locating hotspots 598Analyzing Query Efficiency 598Using query analyzers 599The Database Engine Tuning Advisor 602SQL Server Profiler 607
Trang 35SQL All-in-One Desk Reference For Dummies
xxxii
Using performance monitors 608Finding problem queries 611Analyzing a query’s access plan 611Examining a query’s execution profile 615Managing Resources Wisely 615The disk subsystem 615The database buffer manager 617The logging subsystem 617The locking subsystem 617
Book VIII: Appendixes 619
Appendix A: SQL:2003 Reserved Words 621 Appendix B: Glossary 629
Index 639
Trang 36SQL is the internationally recognized standard language for dealing withdata in relational databases Originally developed by IBM, SQL became
an international standard in 1986 The standard was updated in 1989, 1992,
1999, and 2003 It continues to evolve and gain capability Database vendorscontinually update their products to incorporate the new features of theANSI/ISO standard (ANSI is the American National Standards Institute, andISO is the International Organization for Standardization.)
SQL is not a general-purpose language, such as C++ or Java Instead, it isstrictly designed to deal with data in relational databases With SQL, you can
✦ Create a database, including all tables and relationships
✦ Fill database tables with data
✦ Change the data in database tables
✦ Delete data from database tables
✦ Retrieve specific information from database tables
✦ Grant and revoke access to database tables
✦ Protect database tables from corruption due to access conflicts or usermistakes
About This Book
This book is not just about SQL, but also about how SQL fits into theprocess of creating and maintaining databases and database applications Inthis book, I cover how SQL fits into the larger world of application develop-ment and how it handles data coming in from other computers, which may
be on the other side of the world, or even in interplanetary space
Here are some of the things you can do with this book:
✦ Create a model of a proposed system and then translate that model into
a database
✦ Find out about the capabilities and limitations of SQL
✦ Discover how to develop reliable and maintainable database systems
✦ Create databases
✦ Speed up database queries
Trang 37Foolish Assumptions
2
✦ Protect databases from hardware failures, software bugs, and Internetattacks
✦ Control access to sensitive information
✦ Write effective database applications
✦ Deal with data from a variety of non-traditional data sources using XML
Foolish Assumptions
I know this is a For Dummies book, but I don’t really expect that you are
a dummy In fact, I assume that you are a very smart person After all, youdecided to read this book, which is a sign of high intelligence indeed There-fore, I assume you may want to do a few things; for example, recreate some
of the examples in the book You may even want to enter some SQL code andexecute it To do that, you need at the very least an SQL editor, and morelikely a database management system of some sort Many choices are avail-able, both proprietary and open-source I mention several of these at variousplaces throughout the book I don’t recommend any one in particular Anyproduct that complies with the ANSI/ISO international SQL standard should
be fine
However, take claims of ANSI/ISO compliance with a grain of salt No base management system available today is 100% compliant with the ANSI/ISO SQL standard For that reason, some of the code examples I give in thisbook may not work on the particular SQL implementation that you are using.The code samples I use in this book are consistent with the international stan-dard rather than agreeing with the syntax of any particular implementation,unless I specifically specify that the code is for a particular implementation
data-Conventions Used in This Book
By conventions, I simply mean a set of rules I’ve employed in this book to present information to you consistently When you see a term italicized,
look for its definition, which I’ve included so that you know what thingsmean in the context of SQL Web site addresses and e-mail addresses appear
in monofont so that they stand out from regular text Many aspects of theSQL language, such as statements, data types, constraints, and keywordsalso appear in monofont Code appears in its own font, set off from the rest
of the text, like this:
CREATE SCHEMA RETAIL1 ;
Trang 38How This Book Is Organized 3
What You Don’t Have to Read
I’ve structured this book modularly — that is, it’s designed so that you caneasily find just the information you need — so you don’t have to read what-ever doesn’t pertain to your task at hand I include sidebars here and therethroughout the book that contain interesting information that isn’t necessar-ily integral to the discussion at hand; feel free to skip over these You alsodon’t have to read the Technical Stuff icons, which parse out über-techy tid-bits (which you may or may not be your cup of tea)
How This Book Is Organized
SQL All-in-One Desk Reference For Dummies is split into eight minibooks You
don’t have to read it sequentially; you don’t have to look at every minibook;you don’t have to review each chapter; and you don’t even have to read allthe sections in any particular chapter (Of course, you can if you want to; it’s
a good read.) And the Table of Contents and the index can help you quicklyfind whatever information you need In this section, I briefly describe whateach minibook contains
Book I: SQL Concepts
SQL is a language specifically and solely designed to create, operate on, andmanage relational databases I start with a description of databases and howrelational databases differ from other kinds I then move on to modelingbusiness and other kinds of tasks in relational terms How SQL relates torelational databases is covered next, along with a detailed description of thecomponents of SQL and how to use them The types of data that SQL dealswith are described, as are constraints that restrict the data that can beentered into a database
Book II: Relational Database Development
Many database development projects, like other software development ects, start in the middle rather than at the beginning as they should Thisfact is responsible for the notorious tendency of software development proj-ects to run behind schedule and over budget Many self-taught databasedevelopers don’t even realize that they are starting in the middle They thinkthey are doing everything right This minibook introduces the System Devel-opment Life Cycle (SDLC), which shows what the true beginning of a soft-ware development project is, as well as the middle and the end
proj-Key to the development of an effective database that does what you want is
an accurate model of the system you are abstracting in your database
Trang 39How This Book Is Organized
4
Modeling is described here, as is the delicate tradeoff between performanceand reliability The actual SQL code used to create a database rounds out thediscussion
Book III: SQL Queries
Queries sit at the core of any database system The whole reason for storingdata in databases is so that you can retrieve the information you want fromthem at a later time SQL is above all a query language Its specialty is enablingyou to extract from a database the exact information you want, without clut-tering up what you retrieve with a lot of stuff you don’t want
This book starts off with a description of values, expressions, and functions
It then gives detailed coverage to the powerful tools SQL gives you to zero in
on the information you want, even if it is scattered across multiple tables
Book IV: Data Security
Your data is one of your most valuable assets Acknowledging that fact, I cuss ways to protect it from a diverse array of threats One threat is outrightloss due to hardware failures Another is attack by hackers wielding mali-cious viruses and worms I discuss how you can protect yourself from suchthreats, whether they are random or purposeful
dis-Other sources of error, such as the entry of bad data or the harmful tion of simultaneous users, are extensively dealt with in this book I alsocover how to control access to sensitive data and how to handle errorsgracefully when they occur, as they inevitably will
interac-Book V: SQL and Programming
SQL’s primary use is as a component of an application program that operates
on a database Because SQL is a data language and not a general-purposeprogramming language, this means that SQL statements must be integratedsomehow with the commands of a language such as Visual Basic, Java, C++,
or C# This book outlines the process with the help of a fictitious sampleapplication, taking it from the beginning, when the need for a new applica-tion is perceived, to the final release of the finished application Best prac-tices are emphasized throughout
Book VI: SQL and XML
XML is the language used to transport data between dissimilar data stores The
2005 extensions to the SQL:2003 standard greatly expanded SQL’s capacity tohandle XML data This book gives the basics of XML and how it relates to SQL.SQL functions that are specifically designed to operate on data in XML formatare described as the operations of storing and retrieving data in XML format
Trang 40Icons Used in This Book 5
Book VII: Database Tuning Overview
Depending on how they are structured, databases can efficiently respond torequests for information or perform very poorly Often the performance of adatabase degrades over time as its structure and the data in it change, or asthe types of retrievals typically performed change This book describes theparts of a database that are amenable to tuning and optimization It alsogives a procedure for tracking down bottlenecks that are choking the per-formance of the entire system
Book VIII: Appendixes
Appendix A lists words that have a special meaning in SQL You can’t usethese words as the names of tables, columns, views, or anything other thanwhat they were meant to be used for If you receive a strange error message
to an SQL statement that you have entered, check to see if you have tently used a reserved word inappropriately
inadver-Appendix B is a glossary that gives brief definitions of many of the termsused in this book as well as many others that relate to SQL and databases,whether they are used in this book or not
Icons Used in This Book
For Dummies books are known for those helpful icons that point you in
the direction of really great information This section briefly describes eachicon used in this book
The Tip icon points out helpful information that is likely to make your jobeasier
This icon marks a generally interesting and useful fact — something that youmight want to remember for later use
The Warning icon highlights lurking danger When you see this icon, payattention and proceed with caution
This icon denotes that there’s techie stuff nearby If you’re not feeling verytechie, you can skip this info