sams teach yourself sql in 10 minutes -...

41

Upload: doanbao

Post on 06-Feb-2018

227 views

Category:

Documents


1 download

TRANSCRIPT

Page 2: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

in 10 Minutes

SQLSamsTeachYourself

Ben Forta

800 East 96th Street, Indianapolis, Indiana 46240

Fourth Edition

Page 3: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Sams 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: 9780672336072

ISBN-10: 0672336073

Library of Congress cataloging-in-Publication Data is on file.

Printed in the United States of America

Second Printing: July 2013

TrademarksAll 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 contact

U.S. Corporate and Government [email protected]

For sales outside of the U.S., please contact

International [email protected]

AcquisitionsEditorMark Taber

ManagingEditorKristy Hart

Project EditorAndy Beaster

Copy EditorApostropheEditing Services

IndexerTim Wright

ProofreaderKathy Ruiz

TechnicalEditorsChris McGeeGreg Wilson

PublishingCoordinatorVanessa Evans

DesignerAnne Jones

Page LayoutTnT Design, Inc.

Page 4: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Table of Contents

Introduction 1Who Is the Teach Yourself SQL Book For?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

DBMSs Covered in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

Conventions Used in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1 Understanding SQL 5Database Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

What Is SQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Try It Yourself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 Retrieving Data 13The SELECT Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Retrieving Individual Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Retrieving Multiple Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Retrieving All Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Retrieving Distinct Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Limiting Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Using Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3 Sorting Retrieved Data 27Sorting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Sorting by Multiple Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Sorting by Column Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Specifying Sort Direction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Page 5: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

4 Filtering Data 35Using the WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

The WHERE Clause Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

5 Advanced Data Filtering 43Combining WHERE Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

Using the IN Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Using the NOT Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

6 Using Wildcard Filtering 53Using the LIKE Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Tips for Using Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

7 Creating Calculated Fields 61Understanding Calculated Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Concatenating Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Performing Mathematical Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

8 Using Data Manipulation Functions 71Understanding Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

9 Summarizing Data 81Using Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Aggregates on Distinct Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

Combining Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

iv Sams Teach Yourself SQL in 10 Minutes

Page 6: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

10 Grouping Data 93Understanding Data Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Creating Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Filtering Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

Grouping and Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

SELECT Clause Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

11 Working with Subqueries 103Understanding Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

Filtering by Subquery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

Using Subqueries as Calculated Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

12 Joining Tables 113Understanding Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

Creating a Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

13 Creating Advanced Joins 125Using Table Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Using Different Join Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

Using Joins with Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

Using Joins and Join Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

14 Combining Queries 137Understanding Combined Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

Creating Combined Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

vTable of Contents

Page 7: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

15 Inserting Data 145Understanding Data Insertion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

Copying from One Table to Another . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

16 Updating and Deleting Data 155Updating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

Deleting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Guidelines for Updating and Deleting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

17 Creating and Manipulating Tables 163Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

Updating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

Deleting Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

Renaming Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

18 Using Views 175Understanding Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

19 Working with Stored Procedures 187Understanding Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Why to Use Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

Executing Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

Creating Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

20 Managing Transaction Processing 197Understanding Transaction Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

Controlling Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

vi Sams Teach Yourself SQL in 10 Minutes

Page 8: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

21 Using Cursors 205Understanding Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Working with Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

22 Understanding Advanced SQL Features 213Understanding Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Understanding Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

Understanding Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222

Database Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

A Sample Table Scripts 225Understanding the Sample Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Obtaining the Sample Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

B Working in Popular Applications 233Using Apache Open Office Base. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

Using Adobe ColdFusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

Using IBM DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Using MariaDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Using Microsoft Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Using Microsoft ASP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

Using Microsoft ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

Using Microsoft Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

Using Microsoft SQL Server (including Microsoft SQL ServerExpress) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Using MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240

Using Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Using Oracle Express . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Using PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

Using PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Using SQLite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244

Configuring ODBC Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

viiTable of Contents

Page 9: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

C SQL Statement Syntax 247ALTER TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

COMMIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

CREATE INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

CREATE PROCEDURE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

CREATE VIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

DELETE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

DROP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

INSERT SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

ROLLBACK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

UPDATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

D Using SQL Datatypes 253String Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

Numeric Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256

Date and Time Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257

Binary Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258

E SQL Reserved Words 259

Index 265

viii Sams Teach Yourself SQL in 10 Minutes

Page 10: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

About the Author

Ben 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 [email protected] and invites you to visit his website athttp://forta.com/.

Page 11: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Acknowledgments

Thanks 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 Forta

Page 12: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

We 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 we’re doing right,what we could do better, what areas you’d like to see us publish in, andany other words of wisdom you’re willing to pass our way.

You can e-mail or write directly to let us know what you did or didn’t likeabout this book—as 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 book’s title and author aswell as your name and contact information.

E-mail: [email protected]

Mail: Reader FeedbackSams Publishing/Pearson Education800 East 96th StreetIndianapolis, IN 46240 USA

Reader Services

Visit 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.

Page 13: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

This page intentionally left blank

Page 14: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Introduction

SQL 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. You’ll learn methodically, systematically, and simply—inlessons 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. You’ll be writing world classSQL in no time at all.

Page 15: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

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

. SQLite

Example 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 Minutes

Page 16: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

3Introduction

Conventions 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 ENGLISH

New Term icons provide clear definitions of new, essential terms.

Page 17: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

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 author’s line-by-line analysis of a program.

4 Sams Teach Yourself SQL in 10 Minutes

Page 18: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

LESSON 2

Retrieving Data

In this lesson, you’ll 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 you’ll probably use most frequently is the SELECT state-ment. Its purpose is to retrieve information from one or more tables.

Keyword

A 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 information—what you want to select, and from where you wantto select it.

Page 19: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

NOTE: Following Along with the Examples

The 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 you’d 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 ColumnsWe’ll 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 Data

Page 20: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Output ▼prod_name--------------------Fish bean bag toyBird bean bag toyRabbit bean bag toy8 inch teddy bear12 inch teddy bear18 inch teddy bearRaggedy AnnKing dollQueen doll

NOTE: Unsorted Data

If you tried this query yourself you might have discovered that thedata was displayed in a different order than shown here. If this isthe case, don’t worry—it is working exactly as it is supposed to. Ifquery results are not explicitly sorted (we’ll 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. We’ll discuss these topics in the next few lessons.

TIP: Terminating Statements

Multiple 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. It’ll do no harm, even if it is, in fact, not needed.

15Retrieving Individual Columns

Page 21: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

TIP: SQL Statement and Case

It 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 Space

All 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 Commas

When 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 Data

Page 22: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

The 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.4900

NOTE: Presentation of Data

As 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 Columns

Page 23: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

18 LESSON 2: Retrieving Data

Retrieving 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 Wildcards

As 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 Columns

There 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.

Page 24: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

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 you wantthe vendor ID of all vendors with products in your products table:

Input ▼SELECT vend_idFROM Products;

Output ▼vend_id----------BRS01BRS01BRS01DLL01DLL01DLL01DLL01FNG01FNG01

The SELECT statement returned 14 rows (even though there are only fourvendors in that list) because there are 14 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 Rows

Page 25: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Analysis ▼

SELECT DISTINCT vend_id tells the DBMS to only return distinct(unique) vend_id rows, and so only four rows are returned, as seen in thefollowing output. If used, the DISTINCT keyword must be placed directlyin front of the column names.

Output ▼vend_id----------BRS01DLL01FNG01

CAUTION: Can’t Be Partially DISTINCT

The 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 unless both of the specifiedcolumns 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 Data

Page 26: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Output ▼prod_name-----------------8 inch teddy bear12 inch teddy bear18 inch teddy bearFish bean bag toyBird bean bag toy

Analysis ▼

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 <=5;

If you are using MySQL, MariaDB, PostgreSQL, or SQLite, you can usethe LIMIT clause, as follows:

21Limiting Results

Page 27: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

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 doll

So, 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 Data

Page 28: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

23Using Comments

CAUTION: Row 0

The 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 Shortcut

MySQL, 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 Equal

I included this section on limiting results for one reason only, todemonstrate that while SQL is usually quite consistent across imple-mentations, you can’t 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 you’d not wantprocessed and executed? Why would you ever want to do this? Here are afew reasons:

. The SQL statements we’ve been using here are all very shortand very simple. But, as your SQL statement grow (in lengthand complexity), you’ll 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).

Page 29: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

. 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. We’ll 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 Data

Page 30: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

You 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 won’t 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 you’ll learnhow to sort the retrieved data.

25Summary

Page 31: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

This page intentionally left blank

Page 32: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

Symbols andNumerics

[] (brackets) wildcard,58-59

, (commas) characters, 16|| (concatenation)

operator, 63@ character, 193^ character, 59@@ERROR variable, 204@@IDENTITY global

variable, 195_ (underscore) wildcard,

57-58% (percent sign)

wildcard, 54| (pipe) symbol, 247

AABS() function, 79Access, using, 235accessing cursor data,

208-210adding rows to tables, 250advanced data filtering, 43advanced joins, creating,

125-128, 132-134aggregate functions, 81

ALL argument, 89AVG(), 82combining, 90COUNT(), 84-85DISTINCT

arguments, 89joins, 132-133MAX(), 85MIN(), 86-87SUM(), 87-88

aliases, 66-67, 91alternate uses, 67names, 68tables, 125-128, 132

Ccalculated fields, 61-63, 66

mathematical calcula-tions, 68-70

subqueries, 108-109views, 184

Cartesian Product, 117-119cascading delete

feature, 217case-sensitivity

sort orders, 33SQL statements, 16

CFQUERY CFQUERY tagpair, 234

CHAR string datatype, 255check constraints, 218checking

for no value, 40range of values, 40

clauses, 28ALL, 95HAVING, 96ordering, SELECT

statements, 101positioning, 42WHERE

combining, 43, 46joins, 117operators, 37positioning, 37-39

clients, formatting, 62CLOSE statements, closing

cursors, 211closing cursors, 211code, commenting, 72, 195codes, portable, 72ColdFusion (Allaire),

233-234columns, 7. See also fields

aliases, 66-68assigning new

values, 156

ALL argument, aggregatefunctions, 89

ALL clause, 95Allaire ColdFusion,

233-234ALTER TABLE statement,

169-170CHECK constraints, 219CONSTRAINT syntax,

215-217syntax, 248

AND operator, 43-44ANSI SQL, 11applications

data filtering, 36ODBC client, 245portable code, 72working in SQL, 233

Access, 235Allaire ColdFusion,

233-234DB2, 235Microsoft ASP, 236

argumentsaggregate, 90DISTINCT, 89

AS keyword, 66,126-129, 134

ASC keyword, 33ASP (Microsoft), 236-237authentication, 224authorization, 224AVG() function, 82

DISTINCT argument, 89NULL values, 83

BBETWEEN operator, 40BINARY datatype, 258BIT datatype, 256brackets ([]) wildcard,

58-59

Index

Page 33: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

breaking data correctly, 8derived, 68foreign keys, 216GROUP BY clause, 95Identity fields, 195INSERT SELECT state-

ments, 151inserting omitting

columns, 149list (using INSERT

statements), 148naming, fully

qualified, 117NULL value, 40, 166padded spaces, 64primary keys, 9-10, 167retrieving, 14

all, 18multiple, 16unknown, 18

separating names inqueries, 16

sorting data, 30by mulitple columns,

29-30by non-selected

columns, 29-31descending on multiple

columns, 33specifying by relative

position, 96updating multiple, 156values, deleting, 157

combined queries, 137creating, 138-139sorting results, 143UNION statement

rules, 140combining

aggregate functions, 90WHERE clauses, 43, 46

commas (,), 16commenting code, 23-24,

72, 195COMMIT statements,

201, 248commits, 199comparing datatypes, 258compatibility

datatype, 8operator, 37

266 columns

savepoints, 203search patterns, 53stored procedures, 188,

191-194, 249tables, 163-165, 249triggers, 223views, 179

reusable, 180rules and

restrictions, 177uses, 177

CROSS JOIN, 119CT statement results, 21currency datatypes, 256cursors, 205

accessing data, 208-210closing, 211deallocating

resources, 211limitations, 206opening, 208options, 206using, 207Web-based

applications, 206Customers table, 227

Ddata

breaking correctly, 8calculated fields, 61Cartesian Product, 119consistency with stored

procedures, 189copying, table to

table, 152deleting, 157, 160filtering, 35

advanced, 43application level, 36checking against single

values, 38checking for a range of

values, 40checking for non-

matches, 38-39indexes, 221views, 183wildcards, 53

formatting, 17

complex joins, views, 179concatenating fields, 62concatenation operators, 63conditions (joins), 134configuring ODBC data

sources, 245CONSTRAINT syntax,

ALTER TABLE state-ments, 217

constraints, 213-214cautions, 214check, 218foreign keys, 216speed, 223syntax, 215unique, 217

copyingdata, table to table, 152tables, 152-153, 164

COS() 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, 249

CREATE VIEW statement,179, 249

creatingcalculated fields,

61-63, 66mathmatical calcula-

tions, 68-70subqueries, 108-109

ColdFusion pages,234, 242

combined queries,138-139

cursors, 207groups, 94-95indexes, 221, 248joins, 116

advanced, 125-126,132, 134

self, 126-127

Page 34: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

How can we make this index more useful? Email us at [email protected]

267DELETE statement

grouping, 93, 99filtering groups, 96GROUP BY clause, 99nesting, 95ORDER BY

clause, 100inserting, 145-146, 219joins, 115manipulation

functions, 71date and time, 73,

76, 78numeric, 79

multiple occurences, 114numeric functions, 73ODBC database integra-

tion, 245referential integrity, 213retrieved

inserting, 150reformatting with

views, 180-183retrieving, 13, 81, 84-85

all columns, 18multiple columns, 16

security, 224sorting, 27, 99

by column position, 30by mulitple columns,

29-30by non-selected

columns, 29-31descending on multiple

columns, 33specifying direction, 31

summarizing, 81, 84-85text functions, 73transaction

processing, 198unsorted, 15updating, 155-156, 160

data and time datatypes, 257

Database ManagementSystem. See DBMS

databases, 5-6constraints, 214

check, 218syntax, 215unique, 217

datatypes, 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, 219views

creating, 176rules and

restrictions, 178DECIMAL datatype, 256DECLARE statements

creating, cursors, 207stored procedures, 193

DEFAULT keyword, 168defining

datatypes, 216, 219foreign keys, 216ODBC Data Sources, 246primary keys, 10, 215

DELETE FROM statement, 158

DELETE statement, 157FROM keyword, 159guidelines, 160rollbacks, 201security privileges, 158syntax, 250transaction

processing, 199triggers, 222TRUNCATE TABLE

statement, 160WHERE clause, 158

cursorsaccessing data,

208-210closing, 211creating, 207opening, 208using, 207

dropping objects, 250filtering, 36indexes

cautions, 221creating, 221searching, 220

ODBC, 245order entry systems, 226scalability, 115schemas, 7search patterns, 53security, 224software, 6subqueries, 103tables, 6

creating, 163, 249triggers, 222

transaction processing, 197

datatypes, 8, 254binary, 258compatibility, 8currency, 256data and time, 257defining, 216, 219numeric, 256reasons for use, 253string, 254

date and time functions,73, 76-78

DATE dataype, 257DATEPART() function, 77DATETIME datatype, 257DB2, 235DBMS (Database

Management System), 6accidental table

deletion, 172affecting sort order, 28cascading delete

feature, 217constraints, 214cursor options, 206

Page 35: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

deletingcascading delete

feature, 217column values, 157data, 157, 160rows, 250tables, 171

preventing accidentaldeletion, 172

derived columns. Seealiases

DESC keyword, 31dictionary sort order, 33displaying statement

output, 14DISTINCT argument

AVG() function, 89COUNT() function, 90

downloading ready-to-usedata files, 230

DROP statement,syntax, 250

DROP TABLE statement, 171

dropping database objects, 250

duplicate rows,eliminating, 141-142

Eeliminating duplicate rows,

141-142EQUIJOIN, 120establishing primary

keys, 10EXCEPT statements, 143EXECUTE statements,

190-191executing stored proce-

dures, 190-191EXP() function, 79explicit commits, 201extensions, 11

FFETCH statement,

208, 210fields, 62

aliases, 66alternate uses, 67names, 68

268 deleting

date and time, 73, 76-78numeric, 73, 79problems, 71system, 73text, 73text manipulation, 74

SOUNDEX() function, 75

UPPER() function, 73

Gglobal variables,

@@IDENTITY, 195GRANT statements, 224graphical interfaces, 115GROUP BY clause. See

also ORDER BY clausecreating groups, 94-95relative position of

columns, 96grouping

data, 93, 99GROUP BY clause, 99ORDER BY clause, 100

operators, 46groups

creating, 94-95filtering, 96nested, 95

H-IHAVING clauses, 96

Identity fields, 195implementing

transactions, 200IN operator, 47

advantages, 49combining with NOT

operator, 51including duplicate rows,

141-142indexes, 220

cautions, 221creating, 221, 248revisiting, 222searching, 220

inner joins, 120, 129INSERT SELECT

statement, 151

calculated, 61-63, 66mathematical

calculations, 68-70subqueries, 108-109views, 184

concatenating, 62filtering

by subquery, 104-105data, 35

advanced, 43application level, 36checking against single

values, 38checking for a range of

values, 40checking for non-

matches, 38-39indexes, 221views, 183

groups, 96wildcards, 53

fixed length strings, 254FLOAT datatype, 256foreign keys, 159, 216

benefits, 217defining, 216

formattingclients, 62data, 17retrieved data with views,

180-183servers, 62statements, 165subqueries, 106

FROM clause, 116FROM keyword

DELETE statement, 159UPDATE statement, 157

full outer joins, 132fully qualified column

names, 117functions, 71-72, 75

aggregate, 81AVG(), 82combining, 90COUNT(), 84-85DISTINCT, 89MAX(), 85MIN(), 86-87SUM(), 87-88

data manipulation, 71

Page 36: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

How can we make this index more useful? Email us at [email protected]

269NOT operator

SELECT INTO state-ment comparison, 152

syntax, 251INSERT statement

columns lists, 148INTO keyword, 146omitting columns, 149partial rows, 149rollbacks, 204safety, 146security privileges, 145syntax, 250table layout, 147transaction

processing, 199triggers, 222VALUES, 148

insertingcolumns, 149data, 145-146

INTO keyword, 146retrieved, 150

rows, 146multiple, 152partial, 149-150

INT datatype, 256interactive DBMS

tools, 115INTERSECT

statements, 143INTO keyword, 146IS NULL clause, 41

Jjoining tables, 113, 115

aliases, 125-128, 132multiple, 121-123natural joins, 129performance

concerns, 121joins

aggregate functions,132-133

Cartesian Product, 117conditions, 134creating, 116

advanced, 125-128,132-134

self, 126-128

M managing transactions, 199

COMMIT statements, 201

ROLLBACK statements, 201

SAVEPOINT statements, 202

manipulating tables, 163complex structure

changes, 170deleting, 171

manipulation functions, 71date and time, 73, 76-78numeric, 79text, 74

mathematical calculations,performing, 68-70

mathematical operators, 69MAX() function, 82,

85-86, 90Microsoft Access. See

AccessMicrosoft ASP, 236-237Microsoft Query, 238MIN() function, 82, 86

DISTINCT argument, 90non-numeric data, 87

multiple tables,joining, 123

multiple rows,inserting, 152

MySQL, 240-241

Nnames, aliases, 126naming

aliases, 68, 91columns, fully

qualified, 117indexes, 221tables, renaming, 172

natural joins, 129navigating tables, 205NCHAR string

datatype, 255nested groups, 95NOT NULL values, 166NOT operator, 49-51, 60

CROSS, 119DBMS interactive

tools, 115EQUIJOIN, 120Inner, 120natural, 129outer, 129, 132

full, 132types, 132

performance considerations, 121

pros, 115self, instead of sub-

queries, 128types, 126views, 179WHERE clause, 117-119

Kkeys

foreign, 216primary, 9

keywords, 13AND, 44AS, 66, 126-129, 134DEFAULT, 168FROM, 157IN, 49INTO, 146NOT, 50OR, 45REFERENCES, 217UNION, 138UNIQUE, 218

Llanguages, SQL, 10,

259-263LEFT keyword, 131LIKE operator, 53-54limiting SELECT state-

ment results, 20-23local variables, @

character, 193LONG RAW datatype, 258LTRIM() function, 66

Page 37: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

NULL values, 40AVG() functions, 83empty strings, 167primary keys, 167specifying, 167tables, 166

numeric datatypes, 256numeric functions, 73numeric manipulation

functions, 79NVARCHAR string

datatype, 255

Oobtaining sample tables

and scripts, 229ODBC

ASP, 236data sources, 245-246dates, 257versions, 245

omitting columns, 149OPEN CURSOR state-

ments, 208OPEN statements, opening

cursors, 208, 211opening cursors, 208, 211operators, 38

AND, 43-44BETWEEN, 40compatibility, 37concatenation, 63DBMS specific, 41grouping related, 46HAVING clause, 96IN, 47-49LIKE, 53mathematical, 69NOT, 49-51OR, 45predicates, 54WHERE clause, 37

OR operator, 45Oracle

commits, 202copying data between

tables, 153cursors

closing, 211creating, 208retrieving data, 208

270 NULL values

predicates, 54primary keys, 9-10

Customer table, 227defining, 10, 215NULL values, 167OrderItems table, 229Orders table, 228Products table, 227unique constraints, 217Vendors table, 226

processingstored procedures, 189subqueries, 106transactions, 198transactions. See

transaction processingProducts table, 226-227

QQMF (Qery Management

Facility) utility, 235queries, 103

aggregate functions, 81combined, 137

creating, 138-139sorting results, 143UNION statement

rules, 140WHERE clauses, 137

combining, 105data formatting, 17filtering results, 35internal query

optimizer, 140multiple WHERE

clauses, 140result sets, 205subqueries, 103table aliases, 126unsorted data results, 15views, 176wild cards (*), 18

quotesnumeric values, 256string values, 255

quotes (‘’), 39

RRAW datatype, 258ready-to-use data files,

downloading, 230

date and time manipula-tion functions, 77

savepoints, 203stored procedures,

191-194triggers, 223

Oracle 8, 241Oracle Express, 241ORDER BY clause, 99

positioning, 29SELECT statement, 28UNION statements, 142

order entry systems, 226order of evaluation

parenthesis, 47WHERE clauses, 46

ordering clauses, SELECTstatements, 101

OrderItems table, 228-229Orders table, 228outer joins, 129

full, 132syntax, 130types, 132

overwriting tables, 165

Ppadded spaces, 64parenthesis, 46-47partial rows, inserting,

149-150percent sign (%)

wildcard, 54performance

indexes, 221joins, 121SQL experimentation, 123subqueries, 108UNION statements, 140views, 177

PHP, 242PI() function, 79pipe (|) symbol, 247placeholders. See savepointsportable code, 72positioning

sorting data by columnposition, 30

WHERE clause, 37-39PostgreSQL, 243

Page 38: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

How can we make this index more useful? Email us at [email protected]

271sorting

REAL datatype, 256REFERENCES

keyword, 217referential integrity,

213, 217reformatting retrieved data

with views, 180-183relational databases

referential integrity, 213sort order, 28

relational tables, 113-114relative position,

columns, 96RENAME statement, 172renaming tables, 172replacing tables, 165reserved words, 259-263restrictions, views, 177result sets, 205retrieving

columns, unknown, 18data, 13, 81, 84-85

all columns, 18FETCH statements,

208-210individual columns, 14inserting, 150mulitiple columns, 16

reusable views,creating, 180

revisiting indexes, 222REVOKE statements, 224RIGHT keyword, 131ROLLBACK statement,

201, 251rollbacks, 201

savepoints, 203statements, 204using, 199

rows, 9adding to tables, 250cursors, 205default values, 168deleting, 250duplicate, 141-142filtering, 96inserting, 146

check constraints, 219multiple, 152partial, 149-150

DISTINCT keyword,19-20

FROM clause, 116GROUP BY clause, 94inner joins, 130, 133IS NULL clause, 41joins, 115-116ORDER BY clause, 28

DESC keyword, 31positioning, 29

results, limiting, 20-23retrieving individual

columns, 14subqueries, 104-106, 110syntax, 252UNION keyword,

138-140WHERE clause, 35

combined queries, 137combining, 44IN operator, 47NOT operator, 49-51OR operators, 45quotes, 39

self-joins, creating,126-128

semicolons (;), 15separating statements, 15sequence (clauses), 101servers, formatting, 62SET command, 156simplifying joins with

views, 179SIN() function, 79Single Column Only

subqueries, 107SMALLDATETIME

datatype, 257SMALLINT datatype, 256sorting

by non-selected columns, 29

case-sensitivity issues, 33combined query

results, 143data, 27, 99

by column position, 30descending on multiple

columns, 33

joins, 129returning with UNION

statements, 141updating, 252

RTRIM() function, 64-65rules

constraints, 214views, 177

Ssamples

scripts, obtaining, 229tables, 226, 229

SAVEPOINT statements, 202

savepoints, 199, 203-204scalablity, 115scale, 115schemas, 7scripts

ASP.NET, 237comments, 23-24downloading, 230PHP, 242samples, obtaining, 229

search patterns, 53-55searching

indexes, 220wildcards, 53

% character, 54[] characters, 58-59^ character, 59_ character, 57-58

securitydata, 224DELETE statement, 158INSERT statements, 145UPDATE statement, 155

SELECT * FROM statements, 179

SELECT INTO statements, 152

SELECT statement, 13AS keyword, 66AVG() function, 82clauses, ordering, 101concatenating columns,

63-64creating groups, 94-95

Page 39: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

multiple columns,29-30

non-selected columns, 31

ORDER BY clause, 100

retrieved, 27specifying direction, 31

datatype functionality,253, 262

SOUNDEX() function, 75spaces, padded, 64specifying

dates, 257defualt values, 168NULL values, 167sort direction, 31statements, 14

speedconstraints versus

triggers, 223deleting data, 160

SQL, 10advanced features, 213advantages, 11ALL clause, 95column aliases, 66commits, 201cursors

closing, 211creating, 207retrieving data, 210

DATEPART() function, 77

deleting/updating data, 161

experimentation withoperations, 123

extensions, 11Identity fields, 195INNER JOIN

syntax, 120INSERT statements, 146keywords, 13local variables, @

character, 193reserved words, 259-263savepoints, 203statements, clauses, 28stored procedures, 193

272 sorting

results, limiting, 20-23syntax, 252

specifying, 14stored procedures. See

stored proceduressyntax, 247terminating, 15UNION, 138-140UPDATE, 155-156,

160, 252white space, 16writing, 225

stored procedures, 187benefits, 189commenting code, 195creating, 188,

191-194, 249executing, 190-191functionality, 194Identity fields, 195justification, 188Oracle, 191-194syntax, 189triggers, 222

storingdatatype

functionality, 253date and time values, 257numeric values, 255strings, 254

string datatypes, 254strings

fixed length, 254quotes, 255search, wildcards, 54variable-length, 254

subqueries, 103calculated fields, 108-109COUNT*, 108filtering by, 104-105formatting, 106joins, 127performance, 108processing, 106SELECT statement, 104self joins instead, 128Single Column Only, 107UPDATE statement, 157WHERE lauses, 107

SUM() function, 82, 87-88

transaction processing, 200

triggers, 223working in popular appli-

cations, 233SQL Server Management

Studio, 239SQRT() function, 79statements

ALTER TABLE,169-170, 248

case, 16CFQUERY/CFQUERY

tag pairs, 234clauses, 28COMMIT, 248CREATE INDEX, 221,

248-249CREATE TABLE

required information, 164

syntax, 249CREATE VIEW,

179, 249DELETE, 157, 160

FROM keyword, 159syntax, 250

displaying output, 14DROP, 250DROP TABLE, 171formatting, 165GRANT, 224grouping related

operators, 46INSERT

omitting columns, 149safety, 146security privileges, 145syntax, 250VALUES, 148

INSERT SELECT,syntax, 251

OPEN CURSOR, 208RENAME, 172REVOKE, 224ROLLBACK,

syntax, 251rollbacks, 199, 204SELECT, 13

DISTINCT keyword,19-20

Page 40: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

How can we make this index more useful? Email us at [email protected]

273trimming padded spaces

summarizing data,81, 84-85

syntaxALTER 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, 252

system functions, 73

Ttables, 6

aliases, 125-128, 132calculated fields, 61columns, 7

NULL value, 40primary keys, 10

constraints, 214check, 218syntax, 215unique, 217

copying, 152-153, 164copying data to

tables, 152creating, 163-165, 249cursors

accessing data,208-210

viewscreating, 249uses, 176

virtual, 175-176tags, ColdFusion, 234TAN() function, 79terminating statements, 15text manipulation func-

tions, 74SOUNDEX()

function, 75UPPER() function, 73

TEXT string datatype, 255TINYINT datatype, 256tools, DBMS

interactive, 115TOP argument, 90TOP PERCENT

argument, 90to_char() function, 78to_number() functions, 78transactions, 197

blocks, ROLLBACKstatements, 251

COMMIT statements, 201

implementing, 200managing, 199

COMMIT statements, 201

ROLLBACK statements, 201

SAVEPOINT statements, 202

ROLLBACK statements, 201

SAVEPOINT statements, 202

savepoints, 199, 204writing to databases, 248

triggerscreating, 223functionality, 222speed, 223syntax examples, 223

TRIM() function, 66trimming padded

spaces, 64

closing, 211creating, 207opening, 208

Customer, 227data, copying, 153datatypes, 8deleting, 171-172deleting data, 157-159indexes

cautions, 221creating, 221searching, 220

inserting data, 146multiple rows, 152partial rowas, 149retrieved, 150

joining, 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, 9

adding, 250cursors, 205deleting, 250filtering, 96updating, 252

samples, 226, 229schemas, 7security, 224stored procedures, 189triggers, 222

creating, 223functionality, 222

updating, 155-156,169-170

Vendors, 226

Page 41: Sams Teach Yourself SQL in 10 Minutes - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672336072/samplepages/... · Table of Contents Introduction 1 Who Is the Teach Yourself SQL

troubleshooting accidentaltable deletion, 172

TRUNCATE TABLE statement, 160

Uunderscore (_)

wildcard, 57-58UNION ALL

statements, 142UNION statements

combined queries,creating, 138-139

duplicate row handling, 141

limits, 140ORDER BY clause, 142rules, 140types, 143UNION, 140

unions. See combinedqueries

unique constraints, 217UNIQUE keyword, 218unsorted data, 15UPDATE statement

cautions, 155FROM keyword, 157guidelines, 160security privileges, 155SET command, 156subqueries, 157syntax, 252table names, 156transaction

processing, 199triggers, 222WHERE clause, 156

updatingdata, 155-156, 160multiple columns, 156tables, 169-170

UPPER() function, 73user-defined datatypes, 219

274 troubleshooting accidental table deletion

operators, 37OR operators, 45parenthesis, 47positioning, 37, 39quotes, 39SOUNDEX()

function, 76subqueries, 107UPDATE statements,

155-156wildcards, 53

white space, SQL statements, 16

whitespace, 16wildcards, 18, 53

[] (brackets) characters,58-59

_ (underscore) character,57-58

^ character, 59natural joins, 129positioning in search

patterns, 55search patterns, 55

wrappers, ODBC, 245writing

SQL statements, 225stored procedures, 189

Vvalues

columns, deleting, 157concatenation, 63default, 168NULL, 167searching for

(indexes), 220trimming padded

space, 65VARBINARY

datatype, 258variable-length strings, 254Vendors table, 226views

calculated fields, 184creating, 177-180, 249DBMS consistency, 176filtering unwanted

data, 183joins, 179performance

concerns, 177reformatting retrieved

data, 180-183rules and

restrictions, 177SELECT statement, 175uses, 176

virtual tables, 175-176

W-X-Y-Zweb-based applications,

cursors, 206WHERE clause, 35

BETWEEN operator, 40combining, 43

order of evaluation, 46with queries, 137

DELETE statements, 158filtering, 97IN operator, 47joins, 117-119NOT operators, 49, 51