Sams Teach Yourself SQL in 10 Minutes - Teach Yourself SQL in 10 Minutes, Fourth Edition ... Now in its fourth edition, this book has taught SQL to over a quarter mil-lion English speaking users, ...

  • Published on
    17-May-2018

  • View
    215

  • Download
    3

Transcript

http://www.facebook.com/share.php?u=http://www.informIT.com/title/9780672336072http://twitter.com/?status=RT: download a free sample chapter http://www.informit.com/title/9780672336072https://plusone.google.com/share?url=http://www.informit.com/title/9780672336072http://www.linkedin.com/shareArticle?mini=true&url=http://www.informit.com/title/9780672336072http://www.stumbleupon.com/submit?url=http://www.informit.com/title/9780672336072/Free-Sample-Chapterin 10 MinutesSQLSamsTeachYourselfBen Forta800 East 96th Street, Indianapolis, Indiana 46240Fourth EditionSams Teach Yourself SQL in 10 Minutes, Fourth EditionCopyright 2013 by Pearson Education, Inc.All rights reserved. No part of this book shall be reproduced,stored in a retrieval system, or transmitted by any means, elec-tronic, mechanical, photocopying, recording, or otherwise, withoutwritten permission from the publisher. No patent liability isassumed with respect to the use of the information containedherein. Although every precaution has been taken in the prepara-tion of this book, the publisher and author assume no responsibil-ity for errors or omissions. Nor is any liability assumed for dam-ages resulting from the use of the information contained herein.ISBN-13: 9780672336072ISBN-10: 0672336073Library of Congress cataloging-in-Publication Data is on file.Printed in the United States of AmericaSeventh Printing: December 2014TrademarksAll terms mentioned in this book that are known to be trademarksor service marks have been appropriately capitalized. Pearsoncannot attest to the accuracy of this information. Use of a term inthis book should not be regarded as affecting the validity of anytrademark or service mark.Warning and DisclaimerEvery effort has been made to make this book as complete andas accurate as possible, but no warranty or fitness is implied. Theinformation provided is on an as is basis. The author and thepublisher shall have neither liability nor responsibility to any per-son or entity with respect to any loss or damages arising from theinformation contained in this book.Bulk SalesPearson offers excellent discounts on this book when ordered inquantity for bulk purchases or special sales. For more informa-tion, please contactU.S. Corporate and Government Sales1-800-382-3419corpsales@pearsontechgroup.comFor sales outside of the U.S., please contactInternational Salesinternational@pearsoned.comAcquisitionsEditorMark TaberManagingEditorKristy HartProject EditorAndy BeasterCopy EditorApostropheEditing ServicesIndexerTim WrightProofreaderKathy RuizTechnicalEditorsChris McGeeGreg WilsonPublishingCoordinatorVanessa EvansDesignerAnne JonesPage LayoutTnT Design, Inc.Table of ContentsIntroduction 1Who Is the Teach Yourself SQL Book For?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2DBMSs Covered in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Conventions Used in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Understanding SQL 5Database Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5What Is SQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Try It Yourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Retrieving Data 13The SELECT Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Retrieving Individual Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Retrieving Multiple Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Retrieving All Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Retrieving Distinct Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Limiting Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Using Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Sorting Retrieved Data 27Sorting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Sorting by Multiple Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Sorting by Column Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Specifying Sort Direction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 Filtering Data 35Using the WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35The WHERE Clause Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 Advanced Data Filtering 43Combining WHERE Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Using the IN Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Using the NOT Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516 Using Wildcard Filtering 53Using the LIKE Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53Tips for Using Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 Creating Calculated Fields 61Understanding Calculated Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Concatenating Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Performing Mathematical Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708 Using Data Manipulation Functions 71Understanding Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 Summarizing Data 81Using Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Aggregates on Distinct Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Combining Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91iv Sams Teach Yourself SQL in 10 Minutes10 Grouping Data 93Understanding Data Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Creating Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94Filtering Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Grouping and Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99SELECT Clause Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10211 Working with Subqueries 103Understanding Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Filtering by Subquery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104Using Subqueries as Calculated Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11112 Joining Tables 113Understanding Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Creating a Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12313 Creating Advanced Joins 125Using Table Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125Using Different Join Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Using Joins with Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Using Joins and Join Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13514 Combining Queries 137Understanding Combined Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137Creating Combined Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144vTable of Contents15 Inserting Data 145Understanding Data Insertion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Copying from One Table to Another . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15416 Updating and Deleting Data 155Updating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Deleting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157Guidelines for Updating and Deleting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16117 Creating and Manipulating Tables 163Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163Updating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Deleting Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Renaming Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17318 Using Views 175Understanding Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18519 Working with Stored Procedures 187Understanding Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187Why to Use Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188Executing Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190Creating Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19620 Managing Transaction Processing 197Understanding Transaction Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Controlling Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204vi Sams Teach Yourself SQL in 10 Minutes21 Using Cursors 205Understanding Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205Working with Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21122 Understanding Advanced SQL Features 213Understanding Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213Understanding Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220Understanding Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222Database Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224A Sample Table Scripts 225Understanding the Sample Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225Obtaining the Sample Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229B Working in Popular Applications 233Using Apache Open Office Base. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233Using Adobe ColdFusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234Using IBM DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235Using MariaDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235Using Microsoft Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235Using Microsoft ASP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236Using Microsoft ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237Using Microsoft Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238Using Microsoft SQL Server (including Microsoft SQL ServerExpress) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239Using MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240Using Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241Using Oracle Express . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241Using PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242Using PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243Using SQLite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244Configuring ODBC Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245viiTable of ContentsC SQL Statement Syntax 247ALTER TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248COMMIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248CREATE INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248CREATE PROCEDURE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249CREATE VIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249DELETE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250DROP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250INSERT SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251ROLLBACK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252UPDATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252D Using SQL Datatypes 253String Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254Numeric Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Date and Time Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257Binary Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258E SQL Reserved Words 259Index 265viii Sams Teach Yourself SQL in 10 MinutesAbout the AuthorBen Forta is Adobe Systems Director of Developer Relations and hasmore than 20 years of experience in the computer industry in productdevelopment, support, training, and product marketing. He is the author ofthe best-selling Sams Teach Yourself SQL in 10 Minutes, spinoff titles onMySQL and SQL Server T-SQL, ColdFusion Web ApplicationConstruction Kit and Advanced ColdFusion Application Development(both published by Adobe Press), Sams Teach Yourself RegularExpressions in 10 Minutes, as well as books on Flash, Java, Windows, andother subjects. He has extensive experience in database design and devel-opment, has implemented databases for several highly successful com-mercial software programs and websites, and is a frequent lecturer andcolumnist on Internet and database technologies. Ben lives in Oak Park,Michigan, with his wife Marcy and their seven children. Ben welcomesyour e-mail at ben@forta.com and invites you to visit his website athttp://forta.com/.http://forta.com/AcknowledgmentsThanks to the team at Sams for all these years of support, dedication, andencouragement. A special thank-you to Mark Taber for encouraging thislong awaited update and for suggesting and facilitating the code coloring,which significantly enhances the readability and value of this new edition.Thanks to my colleague Greg Wilson for his thorough technical review.Thanks to the many hundreds of you who provided feedback on the firstthree editions of this book. Fortunately, most of it was positive, and all ofit was appreciated. The enhancements and changes in this edition are adirect response to your feedback, which I continue to welcome.Thanks to the dozens of colleges and universities who have made thisbook part of their IT and computer science curriculums. Being includedand trusted by professors and teachers this way is immensely rewardingand equally humbling.And finally, thanks to the more than one-quarter million of you whobought the previous editions of this book, making it not just my best-selling title, but also one of the best-selling books on the subject. Yourcontinued support is the highest compliment an author can ever be paid.Ben FortaWe Want to Hear from You!As the reader of this book, you are our most important critic and commen-tator. We value your opinion and want to know what were doing right,what we could do better, what areas youd like to see us publish in, andany other words of wisdom youre willing to pass our way.You can e-mail or write directly to let us know what you did or didnt likeabout this bookas well as what we can do to make our books stronger.Please note that we cannot help you with technical problems related tothe topic of this book, and that due to the high volume of mail we receive,we might not reply to every message.When you write, please be sure to include this books title and author aswell as your name and contact information. E-mail: feedback@samspublishing.comMail: Reader FeedbackSams Publishing/Pearson Education800 East 96th StreetIndianapolis, IN 46240 USAReader ServicesVisit our website and register this book at informit.com/register for conve-nient access to any updates, downloads, or errata that might be availablefor this book.This page intentionally left blank IntroductionSQL is the most widely used database language. Whether you are anapplication developer, database administrator, web application designer,mobile app developer, or Microsoft Office user, a good working knowl-edge of SQL is an important part of interacting with databases.This book was born out of necessity. I had been teaching Web applicationdevelopment for several years, and students were constantly asking forSQL book recommendations. There are lots of SQL books out there.Some are actually very good. But they all have one thing in common: formost users they teach just too much information. Instead of teaching SQLitself, most books teach everything from database design and normaliza-tion to relational database theory and administrative concerns. And whilethose are all important topics, they are not of interest to most of us whojust need to learn SQL.And so, not finding a single book that I felt comfortable recommending, Iturned that classroom experience into the book you are holding. Sams TeachYourself SQL in 10 Minutes will teach you SQL you need to know, startingwith simple data retrieval and working on to more complex topics includingthe use of joins, subqueries, stored procedures, cursors, triggers, and tableconstraints. Youll learn methodically, systematically, and simplyinlessons that will each take 10 minutes or less to complete.Now in its fourth edition, this book has taught SQL to over a quarter mil-lion English speaking users, and has been translated into over a dozenother languages too so as to help users the globe over. And now it is yourturn. So turn to Lesson 1, and get to work. Youll be writing world classSQL in no time at all.Who Is the Teach Yourself SQLBook For?This book is for you if. You are new to SQL.. You want to quickly learn how to get the most out of SQL.. You want to learn how to use SQL in your own applicationdevelopment.. You want to be productive quickly and easily in SQL withouthaving to call someone for help.DBMSs Covered in This BookFor the most part, the SQL taught in this book will apply to any DatabaseManagement System (DBMS). However, as all SQL implementations arenot created equal, the following DBMSs are explicitly covered (and spe-cific instructions or notes are included where needed):. Apache Open Office Base. IBM DB2. Microsoft Access. Microsoft SQL Server (including Microsoft SQL ServerExpress). MariaDB. MySQL. Oracle (including Oracle Express). PostgreSQL. SQLiteExample databases (or SQL scripts to create the example databases) are available for all of these DBMSs on the book webpage athttp://forta.com/books/0672336073/.2 Sams Teach Yourself SQL in 10 Minuteshttp://forta.com/books/0672336073/3IntroductionConventions Used in This BookThis book uses different typefaces to differentiate between code and regu-lar English, and also to help you identify important concepts.Text that you type and text that should appear on your screen is presentedin monospace type.It will look like this to mimic the way text looks on yourscreen.Placeholders for variables and expressions appear in monospace italic font. You should replace the placeholder with the specific value it represents.This arrow () at the beginning of a line of code means that a single lineof code is too long to fit on the printed page. Continue typing all the char-acters after the as though they were part of the preceding line.NOTE:A Note presents interesting pieces of information related to the sur-rounding discussion.TIP:A Tip offers advice or teaches an easier way to do something.CAUTION:A Caution advises you about potential problems and helps you steerclear of disaster.PLAIN ENGLISHNew Term icons provide clear definitions of new, essential terms.Input The Input icon identifies code that you can type in. It usually appears nextto a listing.Output The Output icon highlights the output produced by running a program. Itusually appears after a listing.Analysis The Analysis icon alerts you to the authors line-by-line analysis of a program.4 Sams Teach Yourself SQL in 10 MinutesLESSON 2Retrieving DataIn this lesson, youll learn how to use the SELECT statement to retrieveone or more columns of data from a table.The SELECT StatementAs explained in Lesson 1, Understanding SQL, SQL statements aremade up of plain English terms. These terms are called keywords, andevery SQL statement is made up of one or more keywords. The SQLstatement that youll probably use most frequently is the SELECT state-ment. Its purpose is to retrieve information from one or more tables.KeywordA reserved word that is part of the SQL language. Never name atable or column using a keyword. Appendix E, SQL ReservedWords, lists some of the more common reserved words.To use SELECT to retrieve table data you must, at a minimum, specify twopieces of informationwhat you want to select, and from where you wantto select it.NOTE: Following Along with the ExamplesThe sample SQL statements (and sample output) throughout thelessons in this book use a set of data files that are described inAppendix A, Sample Table Scripts. If youd like to follow along andtry the examples yourself (I strongly recommend that you do so),refer to Appendix A which contains instructions on how to downloador create these data files.It is important to understand that SQL is a language, not an applica-tion. The way that you specify SQL statements and display state-ment output varies from one application to the next. To assist you inadapting the examples to your own environment, Appendix B,Working in Popular Applications, explains how to issue the state-ments taught throughout this book using many popular applicationsand development environments. And if you need an application withwhich to follow along, Appendix B has recommendations for you too.Retrieving Individual ColumnsWell start with a simple SQL SELECT statement, as follows:Input SELECT prod_nameFROM Products;Analysis The previous statement uses the SELECT statement to retrieve a single col-umn called prod_name from the Products table. The desired columnname is specified right after the SELECT keyword, and the FROM keywordspecifies the name of the table from which to retrieve the data. The outputfrom this statement is shown in the following:14 LESSON 2: Retrieving DataOutput prod_name--------------------Fish bean bag toyBird bean bag toyRabbit bean bag toy8 inch teddy bear12 inch teddy bear18 inch teddy bearRaggedy AnnKing dollQueen dollNOTE: Unsorted DataIf you tried this query yourself you might have discovered that thedata was displayed in a different order than shown here. If this isthe case, dont worryit is working exactly as it is supposed to. Ifquery results are not explicitly sorted (well get to that in the nextlesson) then data will be returned in no order of any significance. Itmay be the order in which the data was added to the table, but itmay not. As long as your query returned the same number of rowsthen it is working.A simple SELECT statement similar to the one used above returns all therows in a table. Data is not filtered (so as to retrieve a subset of theresults), nor is it sorted. Well discuss these topics in the next few lessons.TIP: Terminating StatementsMultiple SQL statements must be separated by semicolons (the ;character). Most DBMSs do not require that a semicolon be specifiedafter single statements. But if your particular DBMS complains, youmight have to add it there. Of course, you can always add a semi-colon if you wish. Itll do no harm, even if it is, in fact, not needed.15Retrieving Individual ColumnsTIP: SQL Statement and CaseIt is important to note that SQL statements are case-insensitive, soSELECT is the same as select, which is the same as Select. ManySQL developers find that using uppercase for all SQL keywords andlowercase for column and table names makes code easier to readand debug. However, be aware that while the SQL language is case-insensitive, the names of tables, columns, and values may not be(that depends on your DBMS and how it is configured).TIP: Use of White SpaceAll extra white space within a SQL statement is ignored when thatstatement is processed. SQL statements can be specified on onelong line or broken up over many lines. So, the following three state-ments are functionality identical:SELECT prod_nameFROM Products;SELECT prod_name FROM Products;SELECTprod_nameFROMProducts;Most SQL developers find that breaking up statements over multiplelines makes them easier to read and debug.Retrieving Multiple ColumnsTo retrieve multiple columns from a table, the same SELECT statement isused. The only difference is that multiple column names must be specifiedafter the SELECT keyword, and each column must be separated by a comma.TIP: Take Care with CommasWhen selecting multiple columns be sure to specify a commabetween each column name, but not after the last column name.Doing so will generate an error.16 LESSON 2: Retrieving DataThe following SELECT statement retrieves three columns from the prod-ucts table:Input SELECT prod_id, prod_name, prod_priceFROM Products;Analysis Just as in the prior example, this statement uses the SELECT statement toretrieve data from the Products table. In this example, three columnnames are specified, each separated by a comma. The output from thisstatement is shown below:Output prod_id prod_name prod_price--------- -------------------- ----------BNBG01 Fish bean bag toy 3.4900BNBG02 Bird bean bag toy 3.4900BNBG03 Rabbit bean bag toy 3.4900BR01 8 inch teddy bear 5.9900BR02 12 inch teddy bear 8.9900BR03 18 inch teddy bear 11.9900RGAN01 Raggedy Ann 4.9900RYL01 King doll 9.4900RYL02 Queen dool 9.4900NOTE: Presentation of DataAs you will notice in the above output, SQL statements typicallyreturn raw, unformatted data. Data formatting is a presentationissue, not a retrieval issue. Therefore, presentation (for example,displaying the above price values as currency amounts with the cor-rect number of decimal places) is typically specified in the applica-tion that displays the data. Actual retrieved data (without application-provided formatting) is rarely used.17Retrieving Multiple Columns18 LESSON 2: Retrieving DataRetrieving All ColumnsIn addition to being able to specify desired columns (one or more, as seenabove), SELECT statements can also request all columns without having tolist them individually. This is done using the asterisk (*) wildcard charac-ter in lieu of actual column names, as follows:Input SELECT *FROM Products;Analysis When a wildcard (*) is specified, all the columns in the table are returned.The column order will typically, but not always, be the physical order inwhich the columns appear in the table definition. However, SQL data is sel-dom displayed as is. (Usually, it is returned to an application that formats orpresents the data as needed). As such, this should not pose a problem.CAUTION: Using WildcardsAs a rule, you are better off not using the * wildcard unless you real-ly do need every column in the table. Even though use of wildcardsmay save you the time and effort needed to list the desired columnsexplicitly, retrieving unnecessary columns usually slows down theperformance of your retrieval and your application.TIP: Retrieving Unknown ColumnsThere is one big advantage to using wildcards. As you do not explic-itly specify column names (because the asterisk retrieves every col-umn), it is possible to retrieve columns whose names are unknown.Retrieving Distinct RowsAs you have seen, SELECT returns all matched rows. But what if you donot want every occurrence of every value? For example, suppose youwant the vendor ID of all vendors with products in your products table:Input SELECT vend_idFROM Products;Output vend_id----------BRS01BRS01BRS01DLL01DLL01DLL01DLL01FNG01FNG01The SELECT statement returned 9 rows (even though there are only fourvendors in that list) because there are 9 products listed in the productstable. So how could you retrieve a list of distinct values?The solution is to use the DISTINCT keyword which, as its name implies,instructs the database to only return distinct values.Input SELECT DISTINCT vend_idFROM Products;19Retrieving Distinct RowsAnalysis SELECT DISTINCT vend_id tells the DBMS to only return distinct(unique) vend_id rows, and so only three rows are returned, as seen inthe following output. If used, the DISTINCT keyword must be placeddirectly in front of the column names.Output vend_id----------BRS01DLL01FNG01CAUTION: Cant Be Partially DISTINCTThe DISTINCT keyword applies to all columns, not just the one itprecedes. If you were to specify SELECT DISTINCT vend_id,prod_price, all rows would be retrieved because both of the speci-fied columns were distinct.Limiting ResultsSELECT statements return all matched rows, possibly every row in thespecified table. What if you want to return just the first row or a set num-ber of rows? This is doable, but unfortunately, this is one of those situa-tions where all SQL implementations are not created equal.In Microsoft SQL Server and Microsoft Access you can use the TOP key-word to limit the top number of entries, as seen here:Input SELECT TOP 5 prod_nameFROM Products;20 LESSON 2: Retrieving DataOutput prod_name-----------------8 inch teddy bear12 inch teddy bear18 inch teddy bearFish bean bag toyBird bean bag toyAnalysis The previous statement uses the SELECT TOP 5 statement to retrieve justthe first five rows.If you are using DB2, well, then you get to use SQL unique to thatDBMS, like this:Input SELECT prod_nameFROM ProductsFETCH FIRST 5 ROWS ONLY;Analysis FETCH FIRST 5 ROWS ONLY does exactly what it suggests.If you are using Oracle you need to count rows based on ROWNUM (a rownumber counter) like this:Input SELECT prod_nameFROM ProductsWHERE ROWNUM Input SELECT prod_nameFROM ProductsLIMIT 5;Analysis The previous statement uses the SELECT statement to retrieve a single col-umn. LIMIT 5 instructs the supported DBMSs to return no more than fiverows. The output from this statement is shown in the following code.To get the next five rows, specify both where to start and the number ofrows to retrieve, like this:Input SELECT prod_nameFROM ProductsLIMIT 5 OFFSET 5;Analysis LIMIT 5 OFFSET 5 instructs supported DBMSs to return five rows start-ing from row 5. The first number is the number of rows to retrieve, andthe second is where to start. The output from this statement is shown inthe following code:Output prod_name-------------------Rabbit bean bag toyRaggedy AnnKing dollQueen dollSo, LIMIT specifies the number of rows to return. LIMIT with an OFFSETspecifies where to start from. In our example there are only nine productsin the Products table, so LIMIT 5 OFFSET 5 returned just four rows (asthere was no fifth).22 LESSON 2: Retrieving Data23Using CommentsCAUTION: Row 0The first row retrieved is row 0, not row 1. As such, LIMIT 1 OFFSET1 will retrieve the second row, not the first one.TIP: MySQL, MariaDB, and SQLite ShortcutMySQL, MariaDB, and SQLite support a shorthand version of LIMIT4 OFFSET 3, enabling you to combine them as LIMIT 3,4. Usingthis syntax, the value before the , is the LIMIT and the value afterthe , is the OFFSET.NOTE: Not ALL SQL Is Created EqualI included this section on limiting results for one reason only, todemonstrate that while SQL is usually quite consistent across imple-mentations, you cant rely on it always being so. While very basicstatements tend to be very portable, more complex ones tend to beless so. Keep that in mind as you search for SQL solutions to spe-cific problems.Using CommentsAs you have seen, SQL statements are instructions that are processed byyour DBMS. But what if you wanted to include text that youd not wantprocessed and executed? Why would you ever want to do this? Here are afew reasons:. The SQL statements weve been using here are all very shortand very simple. But, as your SQL statement grow (in lengthand complexity), youll want to include descriptive comments(for your own future reference or for whoever has to work on theproject next). These comments need to be embedded in the SQLscripts, but they are obviously not intended for actual DBMSprocessing. (For an example of this, see the create.sql andpopulate.sql files used in Appendix B).. The same is true for headers at the top of SQL file, perhaps con-taining the programmer contact information and a descriptionand notes. (This use case is also seen in the Appendix B .sqlfiles.).. Another important use for comments is to temporarily stop SQLcode from being executed. If you were working with a long SQLstatement, and wanted to test just part of it, you could commentout some of the code so that DBMS saw it as comments andignored it.Most DBMSs supports several forms of comment syntax. Well Start withinline comments:Input SELECT prod_name -- this is a commentFROM Products;Analysis Comments may be embedded inline using -- (two hyphens). Anythingafter the -- is considered comment text, making this a good option fordescribing columns in a CREATE TABLE statement, for example.Here is another form of inline comment (although less commonly sup-ported):Input # This is a commentSELECT prod_nameFROM Products;Analysis A # at the start of a line makes the entire line a comment. You can see thisformat comment used in the accompanying create.sql andpopulate.sql scripts.24 LESSON 2: Retrieving DataYou can also create multi line comments, and comments that stop andstart anywhere within the script:Input /* SELECT prod_name, vend_idFROM Products; */SELECT prod_nameFROM Products;Analysis /* starts a comments, and */ ends it. Anything between /* and */ iscomment text. This type of comment is often used to comment out code,as seen in this example. Here, two SELECT statements are defined, but thefirst wont execute because it has been commented out.SummaryIn this lesson, you learned how to use the SQL SELECT statement toretrieve a single table column, multiple table columns, and all tablecolumns. You also learned how to return distinct values and how to com-ment your code. And unfortunately, you were also introduced to the factthat more complex SQL tends to be less portable SQL. Next youll learnhow to sort the retrieved data.25SummaryThis page intentionally left blank This page intentionally left blank Symbols andNumerics[] (brackets) wildcard,58-59, (commas) characters, 16|| (concatenation) operator, 63@ character, 193^ character, 59@@ERROR variable, 204@@IDENTITY globalvariable, 195_ (underscore) wildcard,57-58% (percent sign) wildcard, 54| (pipe) symbol, 247AABS() function, 79Access, using, 235accessing cursor data,208-210adding rows to tables, 250advanced data filtering, 43advanced joins, creating,125-128, 132-134aggregate functions, 81ALL argument, 89AVG(), 82combining, 90COUNT(), 84-85DISTINCT arguments, 89joins, 132-133MAX(), 85MIN(), 86-87SUM(), 87-88aliases, 66-67, 91alternate uses, 67names, 68tables, 125-128, 132Ccalculated fields, 61-63, 66mathematical calcula-tions, 68-70subqueries, 108-109views, 184Cartesian Product, 117-119cascading delete feature, 217case-sensitivitysort orders, 33SQL statements, 16CFQUERY CFQUERY tagpair, 234CHAR string datatype, 255check constraints, 218checkingfor no value, 40range of values, 40clauses, 28ALL, 95HAVING, 96ordering, SELECT statements, 101positioning, 42WHEREcombining, 43, 46joins, 117operators, 37positioning, 37-39clients, formatting, 62CLOSE statements, closingcursors, 211closing cursors, 211code, commenting, 72, 195codes, portable, 72ColdFusion (Allaire),233-234columns, 7. See also fieldsaliases, 66-68assigning new values, 156ALL argument, aggregatefunctions, 89ALL clause, 95Allaire ColdFusion,233-234ALTER TABLE statement,169-170CHECK constraints, 219CONSTRAINT syntax,215-217syntax, 248AND operator, 43-44ANSI SQL, 11applicationsdata filtering, 36ODBC client, 245portable code, 72working in SQL, 233Access, 235Allaire ColdFusion,233-234DB2, 235Microsoft ASP, 236argumentsaggregate, 90DISTINCT, 89AS keyword, 66,126-129, 134ASC keyword, 33ASP (Microsoft), 236-237authentication, 224authorization, 224AVG() function, 82DISTINCT argument, 89NULL values, 83BBETWEEN operator, 40BINARY datatype, 258BIT datatype, 256brackets ([]) wildcard,58-59Indexbreaking data correctly, 8derived, 68foreign keys, 216GROUP BY clause, 95Identity fields, 195INSERT SELECT state-ments, 151inserting omittingcolumns, 149list (using INSERT statements), 148naming, fully qualified, 117NULL value, 40, 166padded spaces, 64primary keys, 9-10, 167retrieving, 14all, 18multiple, 16unknown, 18separating names inqueries, 16sorting data, 30by mulitple columns,29-30by non-selectedcolumns, 29-31descending on multiplecolumns, 33specifying by relativeposition, 96updating multiple, 156values, deleting, 157combined queries, 137creating, 138-139sorting results, 143UNION statement rules, 140combiningaggregate functions, 90WHERE clauses, 43, 46commas (,), 16commenting code, 23-24,72, 195COMMIT statements,201, 248commits, 199comparing datatypes, 258compatibilitydatatype, 8operator, 37266 columnssavepoints, 203search patterns, 53stored procedures, 188,191-194, 249tables, 163-165, 249triggers, 223views, 179reusable, 180rules and restrictions, 177uses, 177CROSS JOIN, 119CT statement results, 21currency datatypes, 256cursors, 205accessing data, 208-210closing, 211deallocating resources, 211limitations, 206opening, 208options, 206using, 207Web-based applications, 206Customers table, 227Ddatabreaking correctly, 8calculated fields, 61Cartesian Product, 119consistency with storedprocedures, 189copying, table to table, 152deleting, 157, 160filtering, 35advanced, 43application level, 36checking against singlevalues, 38checking for a range ofvalues, 40checking for non-matches, 38-39indexes, 221views, 183wildcards, 53formatting, 17complex joins, views, 179concatenating fields, 62concatenation operators, 63conditions (joins), 134configuring ODBC datasources, 245CONSTRAINT syntax,ALTER TABLE state-ments, 217constraints, 213-214cautions, 214check, 218foreign keys, 216speed, 223syntax, 215unique, 217copyingdata, table to table, 152tables, 152-153, 164COS() function, 79COUNT() function, 82-85,90, 133COUNT* subquery, 108CREATE INDEX state-ment, 221, 248-249CREATE TABLE state-ment, 163CONSTRAINT syntax, 215DEFAULT keyword, 168required information, 164syntax, 249CREATE VIEW statement,179, 249creatingcalculated fields,61-63, 66mathmatical calcula-tions, 68-70subqueries, 108-109ColdFusion pages,234, 242combined queries,138-139cursors, 207groups, 94-95indexes, 221, 248joins, 116advanced, 125-126,132, 134self, 126-127How can we make this index more useful? Email us at indexes@samspublishing.com267DELETE statementgrouping, 93, 99filtering groups, 96GROUP BY clause, 99nesting, 95ORDER BY clause, 100inserting, 145-146, 219joins, 115manipulation functions, 71date and time, 73,76, 78numeric, 79multiple occurences, 114numeric functions, 73ODBC database integra-tion, 245referential integrity, 213retrievedinserting, 150reformatting withviews, 180-183retrieving, 13, 81, 84-85all columns, 18multiple columns, 16security, 224sorting, 27, 99by column position, 30by mulitple columns,29-30by non-selectedcolumns, 29-31descending on multiplecolumns, 33specifying direction, 31summarizing, 81, 84-85text functions, 73transaction processing, 198unsorted, 15updating, 155-156, 160data and time datatypes, 257Database ManagementSystem. See DBMSdatabases, 5-6constraints, 214check, 218syntax, 215unique, 217datatypes, 254DB2, 235functions, 71indexes, 221interactive tools, 115joins, 121LIKE operator, 54security mechanisms, 224separating statements, 15specific operators, 41SQL extensions, 11stored procedures, 190transaction processing, 200triggers, 223TRIM functions, 66UNION keyword, 139UNION statements, 143UPDATE statements, 155user-defined datatypes, 219viewscreating, 176rules and restrictions, 178DECIMAL datatype, 256DECLARE statementscreating, cursors, 207stored procedures, 193DEFAULT keyword, 168definingdatatypes, 216, 219foreign keys, 216ODBC Data Sources, 246primary keys, 10, 215DELETE FROM statement, 158DELETE statement, 157FROM keyword, 159guidelines, 160rollbacks, 201security privileges, 158syntax, 250transaction processing, 199triggers, 222TRUNCATE TABLEstatement, 160WHERE clause, 158cursorsaccessing data,208-210closing, 211creating, 207opening, 208using, 207dropping objects, 250filtering, 36indexescautions, 221creating, 221searching, 220ODBC, 245order entry systems, 226scalability, 115schemas, 7search patterns, 53security, 224software, 6subqueries, 103tables, 6creating, 163, 249triggers, 222transaction processing, 197datatypes, 8, 254binary, 258compatibility, 8currency, 256data and time, 257defining, 216, 219numeric, 256reasons for use, 253string, 254date and time functions,73, 76-78DATE dataype, 257DATEPART() function, 77DATETIME datatype, 257DB2, 235DBMS (DatabaseManagement System), 6accidental table deletion, 172affecting sort order, 28cascading delete feature, 217constraints, 214cursor options, 206deletingcascading delete feature, 217column values, 157data, 157, 160rows, 250tables, 171preventing accidentaldeletion, 172derived columns. SeealiasesDESC keyword, 31dictionary sort order, 33displaying statement output, 14DISTINCT argumentAVG() function, 89COUNT() function, 90downloading ready-to-usedata files, 230DROP statement,syntax, 250DROP TABLE statement, 171dropping database objects, 250duplicate rows,eliminating, 141-142Eeliminating duplicate rows,141-142EQUIJOIN, 120establishing primary keys, 10EXCEPT statements, 143EXECUTE statements,190-191executing stored proce-dures, 190-191EXP() function, 79explicit commits, 201extensions, 11FFETCH statement,208, 210fields, 62aliases, 66alternate uses, 67names, 68268 deletingdate and time, 73, 76-78numeric, 73, 79problems, 71system, 73text, 73text manipulation, 74SOUNDEX() function, 75UPPER() function, 73Gglobal variables,@@IDENTITY, 195GRANT statements, 224graphical interfaces, 115GROUP BY clause. Seealso ORDER BY clausecreating groups, 94-95relative position ofcolumns, 96groupingdata, 93, 99GROUP BY clause, 99ORDER BY clause, 100operators, 46groupscreating, 94-95filtering, 96nested, 95H-IHAVING clauses, 96Identity fields, 195implementing transactions, 200IN operator, 47advantages, 49combining with NOToperator, 51including duplicate rows,141-142indexes, 220cautions, 221creating, 221, 248revisiting, 222searching, 220inner joins, 120, 129INSERT SELECT statement, 151calculated, 61-63, 66mathematical calculations, 68-70subqueries, 108-109views, 184concatenating, 62filteringby subquery, 104-105data, 35advanced, 43application level, 36checking against singlevalues, 38checking for a range ofvalues, 40checking for non-matches, 38-39indexes, 221views, 183groups, 96wildcards, 53fixed length strings, 254FLOAT datatype, 256foreign keys, 159, 216benefits, 217defining, 216formattingclients, 62data, 17retrieved data with views,180-183servers, 62statements, 165subqueries, 106FROM clause, 116FROM keywordDELETE statement, 159UPDATE statement, 157full outer joins, 132fully qualified columnnames, 117functions, 71-72, 75aggregate, 81AVG(), 82combining, 90COUNT(), 84-85DISTINCT, 89MAX(), 85MIN(), 86-87SUM(), 87-88data manipulation, 71How can we make this index more useful? Email us at indexes@samspublishing.com269NOT operatorSELECT INTO state-ment comparison, 152syntax, 251INSERT statementcolumns lists, 148INTO keyword, 146omitting columns, 149partial rows, 149rollbacks, 204safety, 146security privileges, 145syntax, 250table layout, 147transaction processing, 199triggers, 222VALUES, 148insertingcolumns, 149data, 145-146INTO keyword, 146retrieved, 150rows, 146multiple, 152partial, 149-150INT datatype, 256interactive DBMS tools, 115INTERSECT statements, 143INTO keyword, 146IS NULL clause, 41Jjoining tables, 113, 115aliases, 125-128, 132multiple, 121-123natural joins, 129performance concerns, 121joinsaggregate functions,132-133Cartesian Product, 117conditions, 134creating, 116advanced, 125-128,132-134self, 126-128M managing transactions, 199COMMIT statements, 201ROLLBACK statements, 201SAVEPOINT statements, 202manipulating tables, 163complex structurechanges, 170deleting, 171manipulation functions, 71date and time, 73, 76-78numeric, 79text, 74mathematical calculations,performing, 68-70mathematical operators, 69MAX() function, 82,85-86, 90Microsoft Access. SeeAccessMicrosoft ASP, 236-237Microsoft Query, 238MIN() function, 82, 86DISTINCT argument, 90non-numeric data, 87multiple tables,joining, 123multiple rows,inserting, 152MySQL, 240-241Nnames, aliases, 126namingaliases, 68, 91columns, fully qualified, 117indexes, 221tables, renaming, 172natural joins, 129navigating tables, 205NCHAR string datatype, 255nested groups, 95NOT NULL values, 166NOT operator, 49-51, 60CROSS, 119DBMS interactive tools, 115EQUIJOIN, 120Inner, 120natural, 129outer, 129, 132full, 132types, 132performance considerations, 121pros, 115self, instead of sub-queries, 128types, 126views, 179WHERE clause, 117-119Kkeysforeign, 216primary, 9keywords, 13AND, 44AS, 66, 126-129, 134DEFAULT, 168FROM, 157IN, 49INTO, 146NOT, 50OR, 45REFERENCES, 217UNION, 138UNIQUE, 218Llanguages, SQL, 10,259-263LEFT keyword, 131LIKE operator, 53-54limiting SELECT state-ment results, 20-23local variables, @ character, 193LONG RAW datatype, 258LTRIM() function, 66NULL values, 40AVG() functions, 83empty strings, 167primary keys, 167specifying, 167tables, 166numeric datatypes, 256numeric functions, 73numeric manipulationfunctions, 79NVARCHAR stringdatatype, 255Oobtaining sample tablesand scripts, 229ODBCASP, 236data sources, 245-246dates, 257versions, 245omitting columns, 149OPEN CURSOR state-ments, 208OPEN statements, openingcursors, 208, 211opening cursors, 208, 211operators, 38AND, 43-44BETWEEN, 40compatibility, 37concatenation, 63DBMS specific, 41grouping related, 46HAVING clause, 96IN, 47-49LIKE, 53mathematical, 69NOT, 49-51OR, 45predicates, 54WHERE clause, 37OR operator, 45Oraclecommits, 202copying data betweentables, 153cursorsclosing, 211creating, 208retrieving data, 208270 NULL valuespredicates, 54primary keys, 9-10Customer table, 227defining, 10, 215NULL values, 167OrderItems table, 229Orders table, 228Products table, 227unique constraints, 217Vendors table, 226processingstored procedures, 189subqueries, 106transactions, 198transactions. Seetransaction processingProducts table, 226-227QQMF (Qery ManagementFacility) utility, 235queries, 103aggregate functions, 81combined, 137creating, 138-139sorting results, 143UNION statementrules, 140WHERE clauses, 137combining, 105data formatting, 17filtering results, 35internal query optimizer, 140multiple WHEREclauses, 140result sets, 205subqueries, 103table aliases, 126unsorted data results, 15views, 176wild cards (*), 18quotesnumeric values, 256string values, 255quotes (), 39RRAW datatype, 258ready-to-use data files,downloading, 230date and time manipula-tion functions, 77savepoints, 203stored procedures,191-194triggers, 223Oracle 8, 241Oracle Express, 241ORDER BY clause, 99positioning, 29SELECT statement, 28UNION statements, 142order entry systems, 226order of evaluationparenthesis, 47WHERE clauses, 46ordering clauses, SELECTstatements, 101OrderItems table, 228-229Orders table, 228outer joins, 129full, 132syntax, 130types, 132overwriting tables, 165Ppadded spaces, 64parenthesis, 46-47partial rows, inserting,149-150percent sign (%) wildcard, 54performanceindexes, 221joins, 121SQL experimentation, 123subqueries, 108UNION statements, 140views, 177PHP, 242PI() function, 79pipe (|) symbol, 247placeholders. See savepointsportable code, 72positioningsorting data by columnposition, 30WHERE clause, 37-39PostgreSQL, 243How can we make this index more useful? Email us at indexes@samspublishing.com271sortingREAL datatype, 256REFERENCES keyword, 217referential integrity,213, 217reformatting retrieved datawith views, 180-183relational databasesreferential integrity, 213sort order, 28relational tables, 113-114relative position,columns, 96RENAME statement, 172renaming tables, 172replacing tables, 165reserved words, 259-263restrictions, views, 177result sets, 205retrievingcolumns, unknown, 18data, 13, 81, 84-85all columns, 18FETCH statements,208-210individual columns, 14inserting, 150mulitiple columns, 16reusable views,creating, 180revisiting indexes, 222REVOKE statements, 224RIGHT keyword, 131ROLLBACK statement,201, 251rollbacks, 201savepoints, 203statements, 204using, 199rows, 9adding to tables, 250cursors, 205default values, 168deleting, 250duplicate, 141-142filtering, 96inserting, 146check constraints, 219multiple, 152partial, 149-150DISTINCT keyword,19-20FROM clause, 116GROUP BY clause, 94inner joins, 130, 133IS NULL clause, 41joins, 115-116ORDER BY clause, 28DESC keyword, 31positioning, 29results, limiting, 20-23retrieving individualcolumns, 14subqueries, 104-106, 110syntax, 252UNION keyword,138-140WHERE clause, 35combined queries, 137combining, 44IN operator, 47NOT operator, 49-51OR operators, 45quotes, 39self-joins, creating,126-128semicolons (;), 15separating statements, 15sequence (clauses), 101servers, formatting, 62SET command, 156simplifying joins withviews, 179SIN() function, 79Single Column Only subqueries, 107SMALLDATETIMEdatatype, 257SMALLINT datatype, 256sortingby non-selected columns, 29case-sensitivity issues, 33combined query results, 143data, 27, 99by column position, 30descending on multiplecolumns, 33joins, 129returning with UNIONstatements, 141updating, 252RTRIM() function, 64-65rulesconstraints, 214views, 177Ssamplesscripts, obtaining, 229tables, 226, 229SAVEPOINT statements, 202savepoints, 199, 203-204scalablity, 115scale, 115schemas, 7scriptsASP.NET, 237comments, 23-24downloading, 230PHP, 242samples, obtaining, 229search patterns, 53-55searchingindexes, 220wildcards, 53% character, 54[] characters, 58-59^ character, 59_ character, 57-58securitydata, 224DELETE statement, 158INSERT statements, 145UPDATE statement, 155SELECT * FROM statements, 179SELECT INTO statements, 152SELECT statement, 13AS keyword, 66AVG() function, 82clauses, ordering, 101concatenating columns,63-64creating groups, 94-95multiple columns,29-30non-selected columns, 31ORDER BY clause, 100retrieved, 27specifying direction, 31datatype functionality,253, 262SOUNDEX() function, 75spaces, padded, 64specifyingdates, 257defualt values, 168NULL values, 167sort direction, 31statements, 14speedconstraints versus triggers, 223deleting data, 160SQL, 10advanced features, 213advantages, 11ALL clause, 95column aliases, 66commits, 201cursorsclosing, 211creating, 207retrieving data, 210DATEPART() function, 77deleting/updating data, 161experimentation withoperations, 123extensions, 11Identity fields, 195INNER JOIN syntax, 120INSERT statements, 146keywords, 13local variables, @ character, 193reserved words, 259-263savepoints, 203statements, clauses, 28stored procedures, 193272 sortingresults, limiting, 20-23syntax, 252specifying, 14stored procedures. Seestored proceduressyntax, 247terminating, 15UNION, 138-140UPDATE, 155-156,160, 252white space, 16writing, 225stored procedures, 187benefits, 189commenting code, 195creating, 188,191-194, 249executing, 190-191functionality, 194Identity fields, 195justification, 188Oracle, 191-194syntax, 189triggers, 222storingdatatype functionality, 253date and time values, 257numeric values, 255strings, 254string datatypes, 254stringsfixed length, 254quotes, 255search, wildcards, 54variable-length, 254subqueries, 103calculated fields, 108-109COUNT*, 108filtering by, 104-105formatting, 106joins, 127performance, 108processing, 106SELECT statement, 104self joins instead, 128Single Column Only, 107UPDATE statement, 157WHERE lauses, 107SUM() function, 82, 87-88transaction processing, 200triggers, 223working in popular appli-cations, 233SQL Server ManagementStudio, 239SQRT() function, 79statementsALTER TABLE,169-170, 248case, 16CFQUERY/CFQUERYtag pairs, 234clauses, 28COMMIT, 248CREATE INDEX, 221,248-249CREATE TABLErequired information, 164syntax, 249CREATE VIEW,179, 249DELETE, 157, 160FROM keyword, 159syntax, 250displaying output, 14DROP, 250DROP TABLE, 171formatting, 165GRANT, 224grouping related operators, 46INSERTomitting columns, 149safety, 146security privileges, 145syntax, 250VALUES, 148INSERT SELECT,syntax, 251OPEN CURSOR, 208RENAME, 172REVOKE, 224ROLLBACK,syntax, 251rollbacks, 199, 204SELECT, 13DISTINCT keyword,19-20How can we make this index more useful? Email us at indexes@samspublishing.com273trimming padded spacessummarizing data,81, 84-85syntaxALTER TABLE statement, 248COMMIT statement, 248constraints, 215CREATE INDEX statement, 248-249CREATE TABLE statement, 249CREATE TABLE statements, 163CREATE VIEW statement, 249DELETE statement, 250DROP statement, 250INERT statement, 251INSERT statement, 250outer joins, 130ROLLBACK statement, 251SELECT statement, 252statements, 247stored procedures, 189transaction processing, 200triggers, 223UPDATE statement, 252system functions, 73Ttables, 6aliases, 125-128, 132calculated fields, 61columns, 7NULL value, 40primary keys, 10constraints, 214check, 218syntax, 215unique, 217copying, 152-153, 164copying data to tables, 152creating, 163-165, 249cursorsaccessing data,208-210viewscreating, 249uses, 176virtual, 175-176tags, ColdFusion, 234TAN() function, 79terminating statements, 15text manipulation func-tions, 74SOUNDEX() function, 75UPPER() function, 73TEXT string datatype, 255TINYINT datatype, 256tools, DBMS interactive, 115TOP argument, 90TOP PERCENT argument, 90to_char() function, 78to_number() functions, 78transactions, 197blocks, ROLLBACKstatements, 251COMMIT statements, 201implementing, 200managing, 199COMMIT statements, 201ROLLBACK statements, 201SAVEPOINT statements, 202ROLLBACK statements, 201SAVEPOINT statements, 202savepoints, 199, 204writing to databases, 248triggerscreating, 223functionality, 222speed, 223syntax examples, 223TRIM() function, 66trimming padded spaces, 64closing, 211creating, 207opening, 208Customer, 227data, copying, 153datatypes, 8deleting, 171-172deleting data, 157-159indexescautions, 221creating, 221searching, 220inserting data, 146multiple rows, 152partial rowas, 149retrieved, 150joining, 113-115aliases, 132Cartesian Product, 117multiple, 121-123natural joins, 129performance concerns, 121manipulating, 163NULL values, 166OrderItems, 228-229Orders, 228Products, 226-227referential integrity, 213relational, 113-114renaming, 172replacing existing, 165rows, 9adding, 250cursors, 205deleting, 250filtering, 96updating, 252samples, 226, 229schemas, 7security, 224stored procedures, 189triggers, 222creating, 223functionality, 222updating, 155-156,169-170Vendors, 226troubleshooting accidentaltable deletion, 172TRUNCATE TABLE statement, 160Uunderscore (_) wildcard, 57-58UNION ALL statements, 142UNION statementscombined queries,creating, 138-139duplicate row handling, 141limits, 140ORDER BY clause, 142rules, 140types, 143UNION, 140unions. See combinedqueriesunique constraints, 217UNIQUE keyword, 218unsorted data, 15UPDATE statementcautions, 155FROM keyword, 157guidelines, 160security privileges, 155SET command, 156subqueries, 157syntax, 252table names, 156transaction processing, 199triggers, 222WHERE clause, 156updatingdata, 155-156, 160multiple columns, 156tables, 169-170UPPER() function, 73user-defined datatypes, 219274 troubleshooting accidental table deletionoperators, 37OR operators, 45parenthesis, 47positioning, 37, 39quotes, 39SOUNDEX() function, 76subqueries, 107UPDATE statements,155-156wildcards, 53white space, SQL statements, 16whitespace, 16wildcards, 18, 53[] (brackets) characters,58-59_ (underscore) character,57-58^ character, 59natural joins, 129positioning in search patterns, 55search patterns, 55wrappers, ODBC, 245writingSQL statements, 225stored procedures, 189Vvaluescolumns, deleting, 157concatenation, 63default, 168NULL, 167searching for (indexes), 220trimming padded space, 65VARBINARY datatype, 258variable-length strings, 254Vendors table, 226viewscalculated fields, 184creating, 177-180, 249DBMS consistency, 176filtering unwanted data, 183joins, 179performance concerns, 177reformatting retrieveddata, 180-183rules and restrictions, 177SELECT statement, 175uses, 176virtual tables, 175-176W-X-Y-Zweb-based applications,cursors, 206WHERE clause, 35BETWEEN operator, 40combining, 43order of evaluation, 46with queries, 137DELETE statements, 158filtering, 97IN operator, 47joins, 117-119NOT operators, 49, 51Table of ContentsIntroductionWho Is the Teach Yourself SQL Book For?DBMSs Covered in This BookConventions Used in This Book2 Retrieving DataThe SELECT StatementRetrieving Individual ColumnsRetrieving Multiple ColumnsRetrieving All ColumnsRetrieving Distinct RowsLimiting ResultsUsing CommentsSummaryIndexABCDEFGH-IJKLMNOPQRSTUVW-X-Y-Z

Recommended

View more >