The Programmer's Guide to SQL- CRISTIAN DARIE, KARLI WATSON WITH CHRIS HART, KEVIN HOFFMAN, JULIAN SKINNER

APress Media, LLC The Programmer's Guide to SQL Copyright ~2003 by Cristian Darie, Karli Watson with Chris Hart, Kevin Hoffman, Julian Skinner Originally published by Apress in 2003

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

ISBN 978-1-59059-218-2 ISBN 978-1-4302-0800-6 (eBook) DOI 10.1007/978-1-4302-0800-6

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

Technical Reviewers: Cristof Falk, Slavomir Furman, Brad Maiani, Judith . Myerson, Johan Normen, David Schultz

Editorial Board: Dan Appleman, Craig Berry, Gary Cornell, Steven Rycroft, Julian Skinner, Martin Streicher, Jim Sumser, Karen Watterson, Gavin Wray, John Zukowski

Lead Editor: Tony Davis Publisher: Grace Wong Project Manager: Darren Murphy Copy Editor: Kim Wnnpsett Production Manager: Kari Brooks Production Editor: KellyWmquist Proofreader: Thistle Hill Publishing Services Compositor: Kinetic Publishing Services, LLC Indexer: John Collin Artist: Kinetic Publishing Services, LLC Cover Designer: Kurt Krames Manufacturing Manager: Tom Debolski

The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. Contents at a Glance

About the Authors ...... ix Introduction ...... xi

Chapter 1 Understanding SQL and Relational Databases ...... 1 Chapter 2 Retrieving Data with SQL ...... 29 Chapter 3 Modifying Data ...... 67 Chapter 4 Summarizing and Grouping Data ...... 83 Chapter 5 Performing Calculations and Using Functions .... 107 Chapter 6 Combining SQL Queries ...... 147 Chapter 1 Querying Multiple Tables ...... 167 Chapter 8 Hiding Complex SQL with Views ...... 193 Chapter 9 Using Stored Procedures ...... 203 Chapter 10 Transactions ...... 265 Chapter 11 Users and Security ...... 301 Chapter 12 Working with Database Objects ...... 329 Chapter 13 Triggers ...... 363 Chapter 14 Case Study: Building a Product Catalog ...... 389 Chapter 15 Case Study: Implementing Role-Based Security ...... 453 Appendix A Executing SQL Statements ...... 499 Appendix B Setting Up the InstantUniversity Database ...... 513 Appendix C Data Types ...... 531

Index ...... 539

iii Contents

About the Authors ...... ix

Introduction ...... xi

Chapter 1 Understanding SQL and Relational Databases ...... 1

What Is SQL? ...... 1 Introducing Relational Databases ...... 7 The Power of SQL ...... 25 Summary ...... 28

Chapter 2 Retrieving Data with SQL ...... 29

Understanding Simple Retrieval ...... 29 Using Aliases ...... 35 Returning Calculated Columns ...... 37 Sorting Data ...... 46 Filtering Data ...... 47 Dealing with NULL Data ...... 63 Summary ...... 64

Chapter 3 Modifying Data ...... 67

Introducing SQL Data Modification ...... 67 Adding New Data ...... 67 Changing Existing Data ...... 75 Deleting Data ...... 78 Summary ...... 81

Chapter 4 Summarizing and Grouping Data ...... 83

Summarizing Data ...... 83 Grouping Data ...... 90 Using Analytic Functions ...... 103 Summary ...... 106 v Contents Chapter 5 Performing Calculations and Using Functions...... 107......

Performing Calculations in SQL ...... ·...... 107 Using Functions in SQL ...... 111 Summary ...... 145

Chapter 6 Combining SQL Queries ...... 147

Using Subqueries ...... 147 Combining Data from Queries ...... 158 Summary ...... 166

Chapter 7 Querying Multiple Tables ...... 167

Understanding Simple Joins ...... 167 Inner vs. Outer Joins ...... 178 Exploring Additional Joins in Oracle ...... 190 Summary ...... 192

Chapter 8 Hiding Complex SQL with Views ...... 193

Overview of SQL Views ...... 193 Creating a View ...... 194 Modifying Data Through a View ...... 198 Updating a View ...... 199 Deleting a View ...... 201 Summary ...... 202

Chapter 9 Using Stored Procedures ...... 203

Stored Procedure Overview ...... 203 Coding in Stored Procedures ...... 225 Using Cursors ...... 234 Returning Result Sets from a Procedure ...... 247 Error Handling ...... 252 Summary ...... 263

vi Contents

Chapter 10 Transactions ...... 265

What Is a Transaction? ...... 266 Understanding Database Transactions ...... 268 Transactions at Work ...... 275 Moving onto Advanced Topics ...... 284 Summary ...... 299

Chapter 11 Users and Security ...... 301

Let's Talk About Security ...... 302 Understanding Database Security and SQL ...... 304 Working with Access Security ...... 307 Working with SQL Server Security ...... 308 Working with Oracle Security ...... 315 Working with D82 Security ...... 321 Working with MySQL Security ...... 324 Summary ...... 327

Chapter 12 Working with Database Objects ...... 329

Creating and Dropping Databases ...... 329 Creating and Dropping Data Tables ...... 331 Copying Tables ...... 339 Altering Database Tables ...... 340 Creating Temporary Tables ...... 342 Using Sequences ...... 348 Using Autonumbered Fields ...... 349 Using Indexes ...... 355 Understanding Declarative Referential Integrity and the FOREIGN KEY Constraint ...... 358 Using Database Schemas ...... 361 Summary ...... 362

Chapter 13 Triggers ...... 363

What Are Triggers? ...... 363 Working with SQL Server Triggers ...... 367 Working with Oracle Triggers ...... 375 Working with D82 Triggers ...... 382 Summary ...... 387

vii Contents Chapter 14 Case Study: Building a Product Catalog ...... 389

Setting Up the Catalog ...... 390 Creating the Data Structures ...... 395 Adding Sample Data ...... 402 Retrieving Catalog Information ...... 406 Updating Catalog Information ...... 432 Searching the Catalog ...... 442 Summary ...... 451

Chapter 15 Case Study: Implementing Role-Based Security ...... 453

What Is Role-Based Security? ...... 453 Why Implement Role-Based Security? ...... 454 Implementing Role-Based Security ...... 454 Stage 1: Creating the Database Tables ...... 457 Stage 2: Creating the Stored Procedures ...... 470 Summary ...... 497

Appendix A Executing SQL Statements ...... 499

Entering SQL Statements ...... 499 Connecting to Databases Using SQL ...... 511

Appendix B Setting Up the InstantUniversity Database ...... 513

Creating the Database ...... 514 Inserting Data into the Database ...... 523 Testing the Database Installation ...... 527

Appendix C Data Types ...... 531

RDBMS Data Types ...... 531

Index ...... 539

viii About the Authors

CRISTIAN DARIE is an independent IT consultant spe• cializing in Microsoft technologies. Having worked with computers since he was a child, he won his first prize at the age of 12 in the first programming contest he ever entered. He was actively involved with the for• mer Wrox Press as a technical reviewer and author, having contributed the OOP parts of Visual C# .NET: A Guide for VB6 Developers and coauthored Beginning ASP.NET £-Commerce with Visual Basic .NET and Visual Studio .NET. He has authored MCAD preparation material and various SkillDrill tests, such as C# Programming, Microsoft COM+, and DB2 Development, which can be taken at http: I lwww. skilldrill. com. Cristian is at Politehnica University of Bucharest, studying automatic control and industrial informatics. He can be contacted through http: I 1'-IMN. ChristianDarie. ro. My big thanks go to Dave, Julian, and Chris for being such great people to work with.

KARLI WATSON is a freelance author and IT specialist with a penchant for multicolored clothing. He started out with the intention of becoming a world-famous nanotechnologist, so perhaps one day you might recog• nize his name as he receives a Nobel Prize. For now, though, Karli's computing interests include all things mobile and everything .NET. Karli is also a snowboard• ing enthusiast and wishes he had a cat.

JuLIAN SKINNER studied Germanic etymology before joining the formerWrox Press. He has consequently spent most of the last four-and-a-half years reading, editing, and writing books about programming, focusing on Microsoft technolo• gies and, in particular, on C# and the .NET Framework. He contributed many sections and code samples, and often entire chapters, for the books he worked on at Wrox, mostly hiding behind the relative anonymity of an "additional mater• ial" credit, but he is credited as a coauthor of, among other titles, Professional ADO.NET.

ix About the Authors

CHRIS HART is a developer and author based in Birmingham (in the United Kingdom, not Alabama). Chris spent most of the last four years as a member of the technical editorial team at the former Wrox Press and has been programming on a variety of systems since the age of 10. She spends most of her time working with Microsoft technologies and has been heavily involved with .NET since it was first released as an early alpha preview. She's currently working for Business Post and is developing .NET Compact Framework/SQL CE applications and 20 barcode scanning components in Delphi.

KEVIN HoFFMAN started programming at the age of 10 when his grandfather gave him a Commodore VIC-20 that he refurbished, and he's been addicted to pro• gramming ever since. He has worked on everything from writing interfaces for scientific instruments to building e-commerce Web sites to providing second• tier technical support for Unix. He got hold of .NET when it was first handed out in early pre-beta form and has been coding with it ever since. He's currently employed in Houston, Texas, where he creates enterprise applications with the .NET Framework for a financial services company.

X Introduction

STRUCTURED QUERY LANGUAGE (SQL) is the language of the database. It's a stan• dard that defines how to manipulate almost every aspect of database, from creating the database and tables themselves to creating, reading, inserting, updating, and deleting data in the database. This standard is then implemented and extended differently by each database system vendor. The current version of the SQL standard is SQL-99. Most major database platforms now adhere fairly closely to this standard with a couple of exceptions. Microsoft Access, for example, has only recently (with Access XP) adopted the SQL-92 standard. Previous editions of Access supported only SQL-89. In this book, we'll walk through all the major SQL statements you're likely to need when programming databases. We'll highlight differences between the standard and implementations used in five major database systems:

• SQLServer

• Oracle

• DB2

• MySQL

• Access

Who Is This Book For?

This book is designed to meet the needs of both the novice SQL programmer who needs a bit of syntactical help and the developer using SQL day to day who needs a handy desktop SQL reference. You don't need to have done much data• base programming before, but some experience with databases will be useful. You should also have one of the five database systems mentioned earlier to gain the most benefits from this book.

xi Introduction What Does This Book Cover?

This book covers the following topics:

Chapter 1, "Understanding SQL and Relational Databases": Introduces and clarifies key concepts you'll use throughout the book. This chapter also looks at relational database design theory. Chapter 2, "Retrieving Data with SQI.:': Discusses the use of simple SELECT statements to retrieve data from a table. Chapter 3, "Modifying Data'': Covers modifying data in a table using INSERT and UPDATE statements. Chapter 4, "Summarizing and Grouping Data'': Shows how to use some built-in functions for counting rows and averaging columns and then moves on to look at the GROUP BY and HAVING statements. This chapter also highlights differences between platforms when it comes to display• ing selected rows. Chapter 5, "Performing Calculations and Using Functions": Describes many more available functions that can be used for performing calcula• tions, manipulating strings, working with dates and times, and so on. It also covers creating your own functions. Chapter 6, "Combining SQL Queries": Talks about subqueries and how to refine queries by combining data from different queries. Chapter 7, "Querying Multiple Tables": Introduces joins between tables and using the built-in relationships defined in the database to present the correct results when building up a query. Chapter 8, "ffiding Complex: SQL with Views": Discusses creating views for storing queries. It also discusses how you can use views to grant restricted access to data to users without having to worry about them harming the underlying data. Chapter 9, "Using Stored Procedures": Shows how to create and work with stored procedures on each of the supporting database platforms. It also shows how to use conditional execution, loops, and cursors, and how to handle errors. Chapter 10, "Transactions": Covers the topic of transactions and how they're implemented on different platforms to handle updates to a data• base. This chapter also covers different locking methods that can be applied to data while a transaction is processed. Chapter 11, "Users and Security'': Discusses the key concepts of user authentication and authorization, focusing on the use of roles and per• missions to restrict or enable certain database functionality. xii Introduction

Chapter 12, "Working with Database Objects'': Discusses how to create (and delete) databases, tables, temporary tables, sequences, and indexes and how to apply constraints to columns in a table. Chapter 13, "Triggers": Discusses how to create and use triggers to react to events in databases; for example, the insertion of a row or the dele• tion of a table. Chapter 14, "Case Study: Building a Product Catalog": Drawing on much of the knowledge gained throughout the rest of the book, this case study demonstrates how to create and query the underlying database for a real e-commerce application Chapter 15, "Case Study: Implementing Role-Based Security": Examines how to use SQL and stored procedures to implement a role• based security system.

Also in this book are three appendixes that cover the following:

Appendix~ "Executing SQL Statements'': Provides an overview of how to get up and running so that you're ready to start executing SQL statements against each of the database platforms. Appendix B, "Setting Up the lnstantUniversity Database": Describes how to create and populate the InstantUniversity sample database that's used throughout the examples in this book. Appendix C, "Data Types": Lists the different data types available to SQL programmers on each of the different database platforms.

What You Need to Use This Book

To run the code in this book, you'll need to have one of the following database platforms installed on a compatible operating system:

• SQLServer

• Oracle

• DB2UDB

• MySQL

• Access

xiii Introduction

All the SQL code in the book has been tested against each of these systems. Specifically, the versions we used to test the code were as follows:

• SQL Server 2000

• Oracle 9i R2

• DB2 8.1 beta

• MySQL 4.0 gamma

• Access 2000

Customer Support and Feedback

We always value hearing from our readers, and we want to know what you about this book: what you liked, what you didn't like, and what you think we can do better next time.

How to Tell Us Exactly What You Think

You might just want to tell us how much you liked or loathed the book in ques• tion. Or you might have ideas about how this whole process could be improved. In either case, you should e-mail support@apress. com. Please be sure to mention the book's ISBN and title in your message. You'll always find a sympathetic ear, no matter what the problem is. Above all you should remember that we do care about what you have to say, and we will do our utmost to act upon it.

What We Can't Answer

Obviously with an ever-growing range of books and an ever-changing technol• ogy base, there's an increasing volume of data requiring support. Although we endeavor to answer all questions about the book, we can't solve bugs in your own programs that you've adapted from our code. However, do tell us if you're especially pleased with the routine you developed with our help.

Downloading the Source Code for the Book

The source code for this book is available to readers at http: I lwww. apress. com in the Downloads section. xiv Introduction Finding Support and Errata on www.apress.com

We understand that errors can destroy the enjoyment of a book and can cause many wasted and frustrated hours, so we seek to minimize the distress they can cause. The following sections will explain how to find and post errata on our Web site to get book-specific help.

Finding Errata

Before you send in a query, you might be able to save time by finding the answer to your problem on our Web site at http: I /www. a press. com. Locate this book in the online catalog or within the book's category and go to the book's Web page. Check to see if there is a Corrections link. If there is, click the link to see the posted errata.

Adding an Erratum to the Web Site

If you want to point out an erratum or directly query a problem in the book, then click the Submit Errata link on the book's Web page. Please be sure to include your name and e-mail and the chapter number, page number, and a brief description of the problem, as requested. We won't send you junk mail. We need the details to save your time and ours. Queries will be forwarded to the book's authors and editor. You may receive a direct e-mail reply, and/ or the erratum will be posted to the Web site so all readers can benefit.

Participating in Peer-to-Peer Forums

For author and peer discussion, join the Apress discussion groups. If you post a query to our forums, you can be confident that many Apress authors, editors, and industry experts are examining it. At forums. a press. com you'll find a number of different lists that will help you, not only while you read this book but also as you develop your own applications. To sign up for the Apress forums, go to forums. a press. com and select the New User link.

XV