third edition - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7creating...

37

Upload: vodieu

Post on 10-Mar-2018

230 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49
Page 2: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

THIRD EDITION

SQLin 10MinutesBen Forta

Teach Yourself

800 East 96th Street, Indianapolis, Indiana 46240 USA

Page 3: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

Sams Teach Yourself SQL in10 Minutes, Third EditionCopyright © 2004 by Sams PublishingAll 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, with-out written 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 fordamages resulting from the use of the information containedherein.

International Standard Book Number: 0-672-32567-5

Library of Congress Catalog Card Number: 2003093137

Printed in the United States of America

First Printing: April 2004

10 09 08 18 17 16 15 14

TrademarksAll terms mentioned in this book that are known to be trademarksor service marks have been appropriately capitalized. SamsPublishing cannot attest to the accuracy of this information. Useof a term in this book should not be regarded as affecting thevalidity of any trademark or service mark.

Warning and DisclaimerEvery effort has been made to make this book as complete and asaccurate 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 SalesSams Publishing offers excellent discounts on this book whenordered in quantity for bulk purchases or special sales. For moreinformation, please contact

U.S. Corporate and Government [email protected]

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

International [email protected]

ASSOCIATE PUBLISHER

Michael Stephens

DEVELOPMENT EDITOR

Mark Renfrow

MANAGING EDITOR

Charlotte Clapp

PROJECT EDITOR

Dan Knott

INDEXER

Tom Dinse

PROOFREADER

Leslie Joseph

TECHNICAL EDITOR

Christopher McGee

PUBLISHINGCOORDINATOR

Cindy Teeters

INTERIOR DESIGNER

Gary Adair

COVER DESIGNER

Gary Adair

Page 4: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

Contents

Introduction..........................................................................................1

1 Understanding SQL 5Database Basics ..................................................................................5What Is SQL? ....................................................................................11Try It Yourself ....................................................................................12Summary ............................................................................................12

2 Retrieving Data 13The SELECT Statement........................................................................13Retrieving Individual Columns..........................................................14Retrieving Multiple Columns ............................................................16Retrieving All Columns ....................................................................17Summary ............................................................................................18

3 Sorting Retrieved Data 19Sorting Data ......................................................................................19Sorting by Multiple Columns ............................................................21Sorting by Column Position ..............................................................22Specifying Sort Direction ..................................................................23Summary ............................................................................................25

4 Filtering Data 26Using the WHERE Clause......................................................................26The WHERE Clause Operators ..............................................................28Summary ............................................................................................32

5 Advanced Data Filtering 33Combining WHERE Clauses ................................................................33Using the IN Operator........................................................................36Using the NOT Operator ......................................................................38Summary ............................................................................................39

Page 5: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

iv Sams Teach Yourself SQL in Ten Minutes

6 Using Wildcard Filtering 40Using the LIKE Operator ....................................................................40Tips for Using Wildcards ..................................................................46Summary ............................................................................................47

7 Creating Calculated Fields 48Understanding Calculated Fields ......................................................48Concatenating Fields..........................................................................49Performing Mathematical Calculations ............................................55Summary ............................................................................................56

8 Using Data Manipulation Functions 57Understanding Functions ..................................................................57Using Functions ................................................................................59Summary ............................................................................................65

9 Summarizing Data 66Using Aggregate Functions................................................................66Aggregates on Distinct Values ..........................................................72Combining Aggregate Functions ......................................................73Summary ............................................................................................74

10 Grouping Data 75Understanding Data Grouping ..........................................................75Creating Groups ................................................................................76Filtering Groups ................................................................................78Grouping and Sorting ........................................................................80SELECT Clause Ordering ....................................................................83Summary ............................................................................................83

11 Working with Subqueries 84Understanding Subqueries ................................................................84Filtering by Subquery ........................................................................84Using Subqueries As Calculated Fields ............................................88Summary ............................................................................................90

Page 6: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

vContents

12 Joining Tables 91Understanding Joins ..........................................................................91Creating a Join ..................................................................................94Summary ..........................................................................................100

13 Creating Advanced Joins 101Using Table Aliases ........................................................................101Using Different Join Types ..............................................................102Using Joins with Aggregate Functions ............................................108Using Joins and Join Conditions ....................................................110Summary ..........................................................................................110

14 Combining Queries 111Understanding Combined Queries ..................................................111Creating Combined Queries ............................................................112Summary ..........................................................................................117

15 Inserting Data 118Understanding Data Insertion ..........................................................118Copying from One Table to Another ..............................................124Summary ..........................................................................................126

16 Updating and Deleting Data 127Updating Data ..................................................................................127Deleting Data ..................................................................................129Guidelines for Updating and Deleting Data ....................................131Summary ..........................................................................................132

17 Creating and Manipulating Tables 133Creating Tables ................................................................................133Updating Tables ..............................................................................139Deleting Tables ................................................................................141Renaming Tables..............................................................................141Summary ..........................................................................................142

Page 7: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

vi Sams Teach Yourself SQL in Ten Minutes

18 Using Views 143Understanding Views ......................................................................143Creating Views ................................................................................146Summary ..........................................................................................152

19 Working with Stored Procedures 153Understanding Stored Procedures....................................................153Why to Use Stored Procedures........................................................154Executing Stored Procedures ..........................................................156Creating Stored Procedures ............................................................157Summary ..........................................................................................160

20 Managing Transaction Processing 161Understanding Transaction Processing............................................161Controlling Transactions..................................................................164Summary ..........................................................................................167

21 Using Cursors 168Understanding Cursors ....................................................................168Working with Cursors......................................................................170Summary ..........................................................................................173

22 Understanding Advanced SQL Features 174Understanding Constraints ..............................................................174Understanding Indexes ....................................................................180Understanding Triggers....................................................................183Database Security ............................................................................185Summary ..........................................................................................186

A Sample Table Scripts 187Understanding the Sample Tables ..................................................187Obtaining the Sample Tables ..........................................................191

B Working in Popular Applications 194Using Aqua Data Studio ..................................................................195Using DB2 ......................................................................................195Using Macromedia ColdFusion ......................................................196

Page 8: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

viiContents

Using Microsoft Access ..................................................................197Using Microsoft ASP ......................................................................199Using Microsoft ASP.NET ..............................................................199Using Microsoft Query ....................................................................200Using Microsoft SQL Server ..........................................................201Using MySQL..................................................................................202Using Oracle ....................................................................................202Using PHP........................................................................................203Using PostgreSQL ..........................................................................203Using Query Tool ............................................................................203Using Sybase....................................................................................204Configuring ODBC Data Sources ..................................................205

C SQL Statement Syntax 207ALTER TABLE ....................................................................................207COMMIT ..............................................................................................208CREATE INDEX ..................................................................................208CREATE PROCEDURE ..........................................................................208CREATE TABLE ..................................................................................208CREATE VIEW ....................................................................................209DELETE ..............................................................................................209DROP ..................................................................................................209INSERT ..............................................................................................209INSERT SELECT ................................................................................210ROLLBACK ..........................................................................................210SELECT ..............................................................................................210UPDATE ..............................................................................................211

D Using SQL Datatypes 212String Datatypes ..............................................................................213Numeric Datatypes ..........................................................................215Date and Time Datatypes ................................................................216Binary Datatypes..............................................................................217

E SQL Reserved Words 219

Index 225

Page 9: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

Introduction

SQL is the most widely used database language. Whether you are anapplication developer, database administrator, Web application designer,or Microsoft Office user, a good working knowledge of SQL is an impor-tant 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. SamsTeach Yourself SQL in 10 Minutes will teach you SQL you need to know,starting with simple data retrieval and working on to more complex topicsincluding the use of joins, subqueries, stored procedures, cursors, triggers,and table constraints. You’ll learn methodically, systematically, and sim-ply—in lessons that will each take 10 minutes or less to complete.

Now in its third edition, this book has taught SQL to hundreds of thou-sands of users, and now it is your turn. So turn to Lesson 1, and get towork. You’ll be writing world class SQL 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.

Page 10: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

2 Sams Teach Yourself SQL in Ten Minutes

• 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):

• IBM DB2

• Microsoft Access

• Microsoft SQL Server

• MySQL

• Oracle

• PostgreSQL

• Sybase Adaptive Server

Example databases and SQL scripts are also available for all of theseDBMSs.

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 your

screen.

Page 11: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

3Introduction

Placeholders for variables and expressions appear in monospace italic

font. You should replace the placeholder with the specific value it repre-sents.

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.

A Note presents interesting pieces of informationrelated to the surrounding discussion.

A Tip offers advice or teaches an easier way to dosomething.

New Term icons provide clear definitions of new, essentialterms.

The Input icon identifies code that you can type in yourself.

The Output icon highlights the output produced by running aprogram.

The Analysis icon alerts you to the author’s line-by-lineanalysis of a program.

A Caution advises you about potential problems andhelps you steer clear of disaster.

INPUT

OUTPUT

ANALYSIS

Page 12: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

This page intentionally left blank

Page 13: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

LESSON 3SortingRetrievedData

In this lesson, you will learn how to use the SELECT statement’s ORDER BYclause to sort retrieved data as needed.

Sorting DataAs you learned in the last lesson, the following SQL statement returns asingle column from a database table. But look at the output. The dataappears to be displayed in no particular order at all.

SELECT prod_nameFROM Products;

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

Actually, the retrieved data is not displayed in a mere random order. Ifunsorted, data will typically be displayed in the order in which it appearsin the underlying tables. This could be the order in which the data wasadded to the tables initially. However, if data was subsequently updated ordeleted, the order will be affected by how the DBMS reuses reclaimed

INPUT

OUTPUT

Page 14: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

20 Lesson 3

storage space. The end result is that you cannot (and should not) rely onthe sort order if you do not explicitly control it. Relational databasedesign theory states that the sequence of retrieved data cannot be assumedto have significance if ordering was not explicitly specified.

Clause SQL statements are made up of clauses, some requiredand some optional. A clause usually consists of a keyword and

supplied data. An example of this is the SELECT statement’s FROM clause,which you saw in the last lesson.

To explicitly sort data retrieved using a SELECT statement, the ORDER BYclause is used. ORDER BY takes the name of one or more columns bywhich to sort the output. Look at the following example:

SELECT prod_nameFROM ProductsORDER BY prod_name;

This statement is identical to the earlier statement, except italso specifies an ORDER BY clause instructing the Database

Management System software to sort the data alphabetically by theprod_name column. The results are as follows:

prod_name--------------------12 inch teddy bear18 inch teddy bear8 inch teddy bearBird bean bag toyFish bean bag toyKing dollQueen dollRabbit bean bag toyRaggedy Ann

INPUT

ANALYSIS

OUTPUT

Position of ORDER BY Clause When specifying anORDER BY clause, be sure that it is the last clause inyour SELECT statement. Using clauses out of order willgenerate an error message.

Page 15: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

21Sorting Retrieved Data

Sorting by Multiple ColumnsIt is often necessary to sort data by more than one column. For example,if you are displaying an employee list, you might want to display it sortedby last name and first name (first by last name, and then within each lastname sort by first name). This would be useful if there are multipleemployees with the same last name.

To sort by multiple columns, simply specify the column names separatedby commas (just as you do when you are selecting multiple columns).

The following code retrieves three columns and sorts the results by two ofthem—first by price and then by name.

SELECT prod_id, prod_price, prod_nameFROM ProductsORDER BY prod_price, prod_name;

prod_id prod_price prod_name------- ---------- --------------------BNBG02 3.4900 Bird bean bag toyBNBG01 3.4900 Fish bean bag toyBNBG03 3.4900 Rabbit bean bag toyRGAN01 4.9900 Raggedy AnnBR01 5.9900 8 inch teddy bearBR02 8.9900 12 inch teddy bearRYL01 9.4900 King dollRYL02 9.4900 Queen dollBR03 11.9900 18 inch teddy bear

It is important to understand that when you are sorting by multiplecolumns, the sort sequence is exactly as specified. In other words, usingthe output in the example above, the products are sorted by the prod_namecolumn only when multiple rows have the same prod_price value. If all

Sorting by Nonselected Columns More often thannot, the columns used in an ORDER BY clause will beones that were selected for display. However, this isactually not required, and it is perfectly legal to sortdata by a column that is not retrieved.

INPUT

OUTPUT

Page 16: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

22 Lesson 3

the values in the prod_price column had been unique, no data wouldhave been sorted by prod_name.

Sorting by Column PositionIn addition to being able to specify sort order using column names, ORDERBY also supports ordering specified by relative column position. The bestway to understand this is to look at an example:

SELECT prod_id, prod_price, prod_nameFROM ProductsORDER BY 2, 3;

prod_id prod_price prod_name------- ---------- --------------------BNBG02 3.4900 Bird bean bag toyBNBG01 3.4900 Fish bean bag toyBNBG03 3.4900 Rabbit bean bag toyRGAN01 4.9900 Raggedy AnnBR01 5.9900 8 inch teddy bearBR02 8.9900 12 inch teddy bearRYL01 9.4900 King dollRYL02 9.4900 Queen dollBR03 11.9900 18 inch teddy bear

As you can see, the output is identical to that of the queryabove. The difference here is in the ORDER BY clause. Instead

of specifying column names, the relative positions of selected columns inthe SELECT list are specified. ORDER BY 2 means sort by the second col-umn in the SELECT list, the prod_price column. ORDER BY 2, 3 meanssort by prod_price and then by prod_name.

The primary advantage of this technique is that it saves retyping the col-umn names. But there are some downsides too. First, not explicitly listingcolumn names increases the likelihood of you mistakenly specifying thewrong column. Second, it is all too easy to mistakenly reorder data whenmaking changes to the SELECT list (forgetting to make the correspondingchanges to the ORDER BY clause). And finally, obviously you cannot usethis technique when sorting by columns that are not in the SELECT list.

INPUT

OUTPUT

ANALYSIS

Page 17: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

23Sorting Retrieved Data

Specifying Sort DirectionData sorting is not limited to ascending sort orders (from A to Z).Although this is the default sort order, the ORDER BY clause can also beused to sort in descending order (from Z to A). To sort by descendingorder, the keyword DESC must be specified.

The following example sorts the products by price in descending order(most expensive first):

SELECT prod_id, prod_price, prod_nameFROM ProductsORDER BY prod_price DESC;

prod_id prod_price prod_name------- ---------- --------------------BR03 11.9900 18 inch teddy bearRYL01 9.4900 King dollRYL02 9.4900 Queen dollBR02 8.9900 12 inch teddy bearBR01 5.9900 8 inch teddy bearRGAN01 4.9900 Raggedy AnnBNBG01 3.4900 Fish bean bag toyBNBG02 3.4900 Bird bean bag toyBNBG03 3.4900 Rabbit bean bag toy

But what if you were to sort by multiple columns? The following examplesorts the products in descending order (most expensive first), plus productname:

SELECT prod_id, prod_price, prod_nameFROM ProductsORDER BY prod_price DESC, prod_name;

Sorting by Nonselected Columns Obviously, thistechnique cannot be used when sorting by columnsthat do not appear in the SELECT list. However, youcan mix and match actual column names and relativecolumn positions in a single statement if needed.

INPUT

OUTPUT

INPUT

Page 18: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

24 Lesson 3

prod_id prod_price prod_name------- ---------- --------------------BR03 11.9900 18 inch teddy bearRYL01 9.4900 King dollRYL02 9.4900 Queen dollBR02 8.9900 12 inch teddy bearBR01 5.9900 8 inch teddy bearRGAN01 4.9900 Raggedy AnnBNBG02 3.4900 Bird bean bag toyBNBG01 3.4900 Fish bean bag toyBNBG03 3.4900 Rabbit bean bag toy

The DESC keyword only applies to the column name thatdirectly precedes it. In the example above, DESC was speci-

fied for the prod_price column, but not for the prod_name column.Therefore, the prod_price column is sorted in descending order, but theprod_name column (within each price) is still sorted in standard ascendingorder.

OUTPUT

ANALYSIS

Sorting Descending on Multiple Columns If youwant to sort descending on multiple columns, be sureeach column has its own DESC keyword.

It is worth noting that DESC is short for DESCENDING, and both keywordsmay be used. The opposite of DESC is ASC (or ASCENDING), which may bespecified to sort in ascending order. In practice, however, ASC is not usu-ally used because ascending order is the default sequence (and is assumedif neither ASC nor DESC are specified).

Page 19: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

25Sorting Retrieved Data

SummaryIn this lesson, you learned how to sort retrieved data using the SELECTstatement’s ORDER BY clause. This clause, which must be the last in theSELECT statement, can be used to sort data on one or more columns asneeded.

Case Sensitivity and Sort Orders When you are sort-ing textual data, is A the same as a? And does a comebefore B or after Z? These are not theoretical ques-tions, and the answers depend on how the database isset up.

In dictionary sort order, A is treated the same as a, andthat is the default behavior for most DatabaseManagement Systems. However, most good DBMSsenable database administrators to change this behav-ior if needed. (If your database contains lots of for-eign language characters, this might becomenecessary.)

The key here is that if you do need an alternate sortorder, you cannot accomplish it with a simple ORDERBY clause. You must contact your database admini-strator.

Page 20: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

SYMBOLS

% (percent sign) wildcard, 41-42[] (square brackets) wildcard, 44-46^ (caret) wildcard character, 45_ (underscore) wildcard, 43-44| (pipe) symbol, 207|| (double pipes), concatenation oper-

ator, 50’ (single quotation mark), WHERE

clause operators and, 30* (asterisk) wildcard, queries, 17-18*= (equality operator), 107+ (concatenation operator), 50+ (plus sign operator), outer joins,

107, (comma), multiple column separa-

tion, 16@ (at symbol) character, 158@@ERROR variable, 167@@IDENTITY global variable, 160

AABS( ) function, 64Access (Microsoft)

DISTINCT argument support,72

example tables for, 192

pass-through mode, 198running, 197-198sorting by alias, 82stored procedure support, 154

aggregate functionsALL argument, 72AVG( ), 67-68combining, 73-74COUNT( ), 68-69defined, 67DISTINCT argument, 72-73joins and, 108-110MAX( ), 69MIN( ), 70naming aliases, 74overview, 66SUM( ), 71

aliasesalternative uses, 54columns, creating, 101concatenating fields, 53-54names, 54

aggregate functions and,74

self joins, 102-104table names, 101-102

ALL argument, aggregate functions,72

ALL clause, grouping data, 77alphabetical sort order, 23-24

INDEX

Page 21: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

226 SAMS TEACH YOURSELF SQL IN TEN MINUTES

ALTER TABLE statements, 139-140CHECK constraints, 180CONSTRAINT syntax, 177syntax, 207

AND keyword, 31AND operator, 33-34ANSI SQL, 12applications

filtering query results, 27SQL compatibility

Aqua Data Studio, 195ColdFusion (Macromedia),

196DB2 (IBM), 195-196Microsoft Access, 197-198Microsoft ASP, 199Microsoft ASP.NET,

199-200Microsoft Query, 200-201Microsoft SQL Server, 201MySQL, 202ODBC configuration,

205-206Oracle, 202PHP scripting language,

203PostgreSQL, 203Query Tool, 203-204selection criteria, 194Sybase Adaptive Server,

204-205Aqua Data Studio

running, 195Web site, 194

argumentsALL, aggregate functions, 72DBMS support, 73DISTINCT, aggregate func-

tions, 72-73AS keyword, 53-54

Oracle support, 102ASC keyword, query results sort

order, 24ASP (Microsoft), running, 199ASP.NET (Microsoft), running,

199-200

authentication, 185authorization, 185AVG( ) function, 67-68

DISTINCT argument, 72NULL values, 68

BBETWEEN operator, 63

WHERE clause, 30between specified values operator

(WHERE clause), 28BINARY datatype, 217BIT datatype, 215

Ccalculated fields

concatenating fields, 49-52column aliases, 53-54

mathematical calculations,55-56

overview, 48-49subqueries, 88-90views, 151-152

calculated values, totaling, 71Cartesian Product, joins and, 95-97cascading deletes, 178case sensitivity

query result sort order, 25SQL statements, 16

CHAR string datatype, 214characters, searching for

% (percent sign) wildcard,41-42

[ ] (square brackets) wildcard,44-46

_ (underscore) wildcard, 43-44check constraints, 179-180clauses, 20

ALL, grouping data, 77GROUP BY, 76-77HAVING, grouping data, 78

Page 22: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

227INDEX

IS NULL, 31SELECT statements, order of,

83WHERE, 26

AND operator, 33-34checking against single

value, 29checking for nonmatches,

29-30checking for NULL value,

31checking for range of val-

ues, 30-31IN operator, 36-38joins and, 95-97multiple query criteria, 33NOT operator, 38-39operator support by

DBMS, 30operators, 28OR operator, 34-35order of evaluation, 35-36positioning, 27SOUNDEX function, 61

client-based results formatting, com-pared to server-based, 49

CLOSE statements, closing cursors,173

code (programming)commenting, 59

stored procedures, 159portability, 58

ColdFusion (Macromedia), running,196

columns. See also fieldsaliases

alternative uses, 54concatenating fields, 53-54creating, 101names, 54

AVG( ) function, individualcolumns, 68

breaking data correctly, 8concepts, 8Customers example table, 189

derived, 54fully qualified names, 95GROUP BY clause, 77grouping data, specifying by

relative position, 77Identity fields, 160INSERT SELECT statements,

124INSERT statement, omitting

columns, 122insert STATEMENT AND, 120multiple, sorting query results

by, 21-22nonselected, sorting query

results by, 23NULL value, checking for, 31NULL value columns, 136-137OrderItems example table, 191Orders example table, 190padded spaces, RTRIM( ) func-

tion, 51-52position, sorting query results

by, 22primary keys, 10Products example table, 189retrieving

all, 17-18individual, 14-15multiple, 16-17unknown, 18

separating names in queries, 16sorting data, descending on

multiple columns, 24subquery result restrictions, 88updating multiple, 128values, deleting, 129Vendors example table, 188

combined queriescreating, 112-113duplicate rows and, 114-115overview, 111performance, 114rules, 114sorting results, 116

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

Page 23: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

228 SAMS TEACH YOURSELF SQL IN TEN MINUTES

Command Center utility, running,195-196

commas (,), multiple column separa-tion, 16

commentingprogramming code, importance

of, 59stored procedure code, 159

COMMIT statement (transactionprocessing), 165

commits defined, 163syntax, 208

compatibilitydatatypes, 9functions, DBMS support con-

siderations, 57-58WHERE clause operators, 28

compatibility (SQL code), applica-tion selection criteria, 194

concatenating fields, 49-52column aliases, 53-54mathematical calculations,

55-56MySQL, 51

concatenation operators, 50configuring ODBC, 205-206CONSTRAINT syntax, ALTER

TABLE statements, 177constraints (referential integrity)

check constraints, 179-180foreign keys, 176-177overview, 174-175primary keys, 175-176speed, 184unique constraints, 178-179

copying tables, 126COS( ) function, 64COUNT( ) function, 67-69

DISTINCT argument, 73joins and, 108NULL values, 69

COUNT* subquery, 89CREATE INDEX statement, 182

syntax, 208

CREATE TABLE statement, 133-135DEFAULT keyword, 137-138syntax, 208

CREATE VIEW statement, 146syntax, 209

cross joins, 97currency datatypes, 216cursors

accessing, 171-173closing, 173creating, 170-171implementing, 170limitations, 169opening, 171options, support for, 168overview, 168Web-based applications, 169

Customers table, 189

Ddata

breaking correctly (columns), 8deleting

guidelines, 131TRUNCATE TABLE state-

ment, 131filtering, indexes and, 182manipulation functions, date

and time, 63security, 185updating, guidelines, 131

Database Management System. SeeDBMS

databases. See also tablesconcepts, 5-6defined, 6dropping objects, 209indexes

cautions, 182creating, 182

scalability, 93schemas, 7

Page 24: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

229INDEX

security, 185tables

creating, 208triggers, 183

DATALENGTH( ) function, 60datatypes, 8

binary, 217compatibility, 9currency, 216data and time, 216defining, 180numeric, 215string, 213usefulness of, 212

BIT, 215CHAR, 217compatibility, 9currency, 216DATE, 216DATETIME, 216DBMS differences, 213DECIMAL, 215defining, 180INT, 215NCHAR, 214NVARCHAR, 214TEXT, 214TINYINT, 215user-defined, 180VARBINARY, 217

date (system), default value syntax,138

date and time datatypes, 216date and time functions, 59, 62-64DATE datatype, 216DATEPART( ) function, 62DATETIME datatype, 216DB2 (IBM), running, 195-196DBMS (Database Management

System), 6accidental table deletion, 141datatype differences, 213functions, support considera-

tions, 57-58indexes, 182

interactive tools, 93ISAM databases, 169LIKE operator, search patterns

and, 41NULL value differences, 137query sort order, 20security mechanisms, 185SQL extensions, 12transaction processing, imple-

mentation differences, 164triggers, 184TRIM functions, 52UNION statements, 117user-defined datatypes, 180view creation, 144views, rules and restrictions,

145WHERE clause, allowed opera-

tors, 32DECIMAL datatype, 215DECLARE statements

cursors, creating, 170-171stored procedures, 158

default values, tables, 137-138defining datatypes, 180DELETE FROM statements, 130DELETE statement, 129-130

FROM keyword, 130guidelines, 131security privileges, 130syntax, 209transaction processing, 163TRUNCATE TABLE statement,

131DELETE statements

rollbacks, 165triggers, 183WHERE clause, 130

deletingcolumn values, 129data

guidelines, 131TRUNCATE TABLE state-

ment, 131

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

Page 25: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

230 SAMS TEACH YOURSELF SQL IN TEN MINUTES

rows, 209preventing accidental, 178

tables, 141preventing accidental, 141

derived columns. See aliasesDESC keyword, query results sort

order, 23-24dictionary sort order (query results),

25DISTINCT argument

AVG( ) function, 72COUNT( ) function, 73

double pipes (||), concatenation oper-ator, 50

downloading example tables, 191Microsoft Access MDB file,

192SQL scripts, 192

DROP statement, syntax, 209DROP TABLE statement, 141dropping database objects, 209

Eempty strings, compared to NULL

values, 137equality (*=) operator, 107equality operator (WHERE clause),

28establishing primary keys, 10example tables

Customers table, 189downloading, 191functions of, 187Microsoft Access MDB file,

192OrderItems table, 191Orders table, 190Products table, 189SQL scripts, 192Vendors table, 188

EXCEPT statement, 117EXECUTE statement, stored proce-

dures, 156-160

EXP( ) function, 64explicit commits, 165extensions, 12

FFETCH statement, accessing cursors,

171-173fields. See also calculated fields;

columnsaliases, names, 54calculated

concatenating fields, 49-54mathematical calculations,

55-56overview, 48-49subqueries, 88-90views, 151-152

filtering% (percent sign) wildcard,

41-42[] (square brackets) wildcard,

44-46_ (underscore) wildcard, 43-44data, indexes, 182data groups, 78-80LIKE operator, 40-41query results, 26

AND operator, 33-34application level, 27IN operator, 36-38multiple criteria, 33NOT operator, 38-39OR operator, 34-35order of evaluation, 35-36WHERE clause operators,

28-31by subqueries, 84-88with views, 150

fixed length strings, 213FLOAT datatype, 215foreign keys, 176-177

Page 26: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

231INDEX

formattingquery data, 17retrieved data with views,

148-149server-based compared to

client-based, 49statements, 135subqueries, 87

FROM clause, creating joins, 94FROM keyword, 14

DELETE statement, 130UPDATE statement, 129

full outer joins, 108fully qualified column names, 95functions

ABS( ), 64advisability of using, 59aggregate

ALL argument, 72AVG( ), 67-68combining, 73-74COUNT( ), 68-69defined, 67DISTINCT argument,

72-73joins and, 108-110MAX( ), 69MIN( ), 70naming aliases, 74overview, 66SUM( ), 71

AVG( ), 67-68DISTINCT argument, 72NULL values, 68

COS( ), 64COUNT( ), 67-69

DISTINCT argument, 73NULL values, 69

DATALENGTH( ), 60date and time, 59, 62-64DATEPART( ), 62defined, 57EXP( ), 64LCASE( ), 60LEFT( ), 60

LEN( ), 60LENGTH( ), 60LOWER( ), 60LTRIM( ), 60MAX( ), 67-69

DISTINCT argument, 73non-numeric data, 70NULL values, 70

MIN( ), 67, 70DISTINCT argument, 73non-numeric data, 70NULL values, 71

numeric, 59, 64-65PI( ), 65RIGHT( ), 60RTRIM( ), 51-52, 60SIN( ), 65SOUNDEX( ), 60-61

support for, 61SQRT( ), 65SUM( ), 67, 71

multiple columns and, 72NULL values, 72

support considerations, 57-58system, 59TAN( ), 65text, 59-60

list of common, 60to_char, 63to_number, 63TRIM, 52types of, 59UCASE( ), 60UPPER( ), 59-60YEAR( ), 63

Gglobal variables, @@IDENTITY,

160GRANT statement, 185greater than operator (WHERE

clause), 28

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

Page 27: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

232 SAMS TEACH YOURSELF SQL IN TEN MINUTES

greater than or equal to operator(WHERE clause), 28

GROUP BY clause, 76-77compared to ORDER BY

clause, 80-82grouping

data, 75columns, specifying by

position, 77compared to sorting, 80-82filtering groups, 78-80GROUP BY clause, 76-77nested groups, 76

operators, 35

H-IHAVING clause, grouping data, 78

IBM DB2, running, 195-196Identity fields, 160IN operator, 36-38indexes

cautions, 182creating, 182, 208overview, 180-182revisiting, 182

inner joins, 97-98INSERT SELECT statement,

122-124SELECT INTO statement com-

parison, 125syntax, 210

INSERT statementcolumns lists, 121completing rows, 118-120INTO keyword, 119omitting columns, 122overview, 118partial rows, 121-122query data, 122-124rollbacks, 167security privileges, 118syntax, 209

transaction processing, 163triggers, 183VALUES, 121

INT datatype, 215integrity. See referential integrityinteractive DBMS tools, 93INTERSECT statements, 117INTO keyword, 119IS NULL clause, 31ISAM (Indexed Sequential Access

Method) databases, 169ISTINCT argument, aggregate func-

tions, 72-73

J-Kjoins

aggregate functions and,108-110

Cartesian Product, 95-97creating, 94cross joins, 97inner joins, 97-98multiple tables, 98-100natural joins, 104-105outer, 105-108

full, 108left, 107right, 107syntax, 107types, 108

overview, 91performance considerations, 99self joins, 102-104usefulness of, 93views, 147-148WHERE clause, 95-97

keys, primary, 9-11keywords, 13

AND, 31, 34AS, 53-54

Oracle support, 102ASC, query results sort order,

24

Page 28: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

233INDEX

DEFAULT, table values,137-138

DESC, query results sort order,23-24

FROM, 14, 129IN, 38INTO, 119NOT, 38OR, 35REFERENCES, 177UNIQUE, 179

Llanguages, SQL, 11LCASE( ) function, 60LEFT keyword (outer joins), 106left outer joins, 107LEFT( ) function, 60LEN( ) function, 60LENGTH( ) function, 60less than operator (WHERE clause),

28less than or equal to operator

(WHERE clause), 28LIKE operator, 40-41

% (percent sign) wildcard,41-42

[] (square brackets), 44-46_ (underscore) wildcard, 43-44

local variables, @ character, 158logical operators, defined, 33LONG RAW datatype, 217LOWER( ) function, 60LTRIM( ) function, 52, 60

MMacromedia ColdFusion, running,

196mathematical

calculations, 55-56operators, 56

MAX( ) function, 67-69DISTINCT argument, 73non-numeric data, 70NULL values, 70

Microsoft AccessDISTINCT argument support,

72example tables for, 192pass-through mode, 198running, 197-198sorting by alias, 82stored procedure support, 154

Microsoft ASP, running, 199Microsoft ASP.NET, running,

199-200Microsoft Query, running, 200-201Microsoft SQL Server, running, 201MIN( ) function, 67, 70

DISTINCT argument, 73non-numeric data, 70NULL values, 71

MySQLconcatenation, 51cursor support, 168NOT operator, 39running, 202stored procedure support, 154subquery support, 84views, support for, 143

Nnaming

aliases, 54aggregate functions and,

74columns, fully qualified names,

95indexes, 182tables, 7

reserved words and, 13aliases, 101-102

natural joins, 104-105navigating tables, cursors, 168

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

Page 29: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

234 SAMS TEACH YOURSELF SQL IN TEN MINUTES

NCHAR string datatype, 214nested data groups, 76non-equality operator (WHERE

clause), 28non-numeric data

MAX( ) function, 70MIN( ) function, 70

not greater than operator (WHEREclause), 28

not less than operator (WHEREclause), 28

NOT operator, 38-39character searching and, 46

NULL keyword, updating columns,129

NULL value operator (WHEREclause), 28

NULL valuesAVG( ) function, 68checking for, 31compared to empty strings, 137COUNT( ) function, 69MAX( ) function, 70MIN( ) function, 71primary keys, 137SUM( ) function, 72table columns, 136-137

numericdatatypes, 215functions, 59, 64-65values, quotes, 215

NVARCHAR string datatype, 214

OODBC

configuration, 205-206dates, 217

OPEN CURSOR statement, 171OPEN statement, opening cursors,

173

operators*= (equality), 107% (percent sign) wildcard,

41-42+ (plus sign), outer joins, 107[] (square brackets) wildcard,

44-46_ (underscore) wildcard, 43-44AND, 33-34BETWEEN, 63concatenation, 50defined, 33grouping related, 35HAVING clause, 78IN, 36-38LIKE, 40-41mathematical, 56NOT, 38-39OR, 34-35order of evaluation, 35-36predicates, 41WHERE clause, 28

checking against singlevalue, 29

checking for nonmatches,29-30

checking for NULL value,31

checking for range of val-ues, 30-31

compatibility, 28OR operator, 34-35Oracle

commits, 165cursors

closing, 173creating, 170retrieving data, 171

date and time manipulationfunctions, 63

date formatting, 64running, 202savepoints, 166stored procedures, 157triggers, 184

Page 30: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

235INDEX

ORDER BY clause (SELECT state-ment), 20

ascending/descending sortorder, 23-24

compared to GROUP BYclause, 80-82

positioning, 20sorting by column position, 22sorting by multiple columns,

21-22sorting by nonselected columns,

23OrderItems table, 191Orders table, 190outer joins, 105-108

full, 108left, 107right, 107syntax, 106-107types, 108

overwriting tables, 135

Pparentheses, multiple query criteria

order of evaluation, 35pass-through mode (Microsoft

Access), 198patterns (searching), wildcards,

40-41% (percent sign), 41-42[] (square brackets), 44-46_ (underscore), 43-44

percent sign (%) wildcard, 41-42performance

combining queries, 114deleting data, 131indexes, 181joins and, 99subqueries, 88views, 145

PHP scripting language, running,203

PI( ) function, 65

pipe (|) symbol, 207placeholders. See savepointsplus sign (+)

concatenation operator, 50outer joins, 107

portabilitydefined, 58INSERT statements and, 121

PostgreSQLfilter query data, 27running, 203

predicates (operators), 41primary keys, 175-176

concepts, 9-11Customer example table, 190importance, 10NULL values, 137OrderItems example table, 191Orders example table, 190Products example table, 189Vendors example table, 188

processingsubqueries, 86transactions, 161

Products table, 189programming code

commenting, 59portability, 58

Qqueries

calculated fieldsconcatenating fields, 49-54mathematical calculations,

55-56overview, 48-49

combinedcreating, 112-113duplicate rows and,

114-115overview, 111performance, 114rules, 114

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

Page 31: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

236 SAMS TEACH YOURSELF SQL IN TEN MINUTES

sorting results, 116WHERE clauses, 111

combining, 86data formatting, 17defined, 84filtering results, 26

AND operator, 33-34IN operator, 36-38multiple criteria, 33NOT operator, 38-39OR operator, 34-35order of evaluation, 35-36WHERE clause operators,

28-31INSERT statement and,

122-124multiple WHERE clauses, 113result sets, 168sorting results, 19-20

ascending/descendingorder, 23-24

by column position, 22by multiple columns, 21-22by nonselected columns,

21, 23case sensitivity, 25

subqueriesas calculated fields, 88-90filtering by, 84-88overview, 84processing, 86self joins and, 103

table aliases, 102unsorted results, 15views, 144wild cards (*), 17-18

Query (Microsoft), running, 200-201Query Tool

running, 203-204Web site, 194

quotation marksnumeric values, 215single (‘), 30string values, 214

RRAW datatype, 217REAL datatype, 215records, compared to rows, 9REFERENCES keyword, 177referential integrity

cascading deletes, 178constraints

check constraints, 179-180foreign keys, 176-177overview, 174-175primary keys, 175-176unique constraints,

178-179natural joins, 104-105outer joins, 105-108self joins, 102-104

reformatting retrieved data withviews, 148-149

relational databases (DBMS)nonrelational behavior, induc-

ing, 169sort order and, 20

relational tables, 91-92relationships

constraintscheck constraints, 179-180foreign keys, 176-177overview, 174-175primary keys, 175-176unique constraints,

178-179natural joins, 104-105outer joins, 105-108self joins, 102-104

RENAME statement, 141renaming tables, 141reserved words, 13, 219

list of, 220-224restrictions, views, 145-146result sets, 168reusable views, creating, 148revisiting indexes, 182

Page 32: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

237INDEX

REVOKE statements, 185RIGHT keyword (outer joins), 106right outer joins, 107RIGHT( ) function, 60ROLLBACK command (transaction

processing), 164-165ROLLBACK statement, syntax, 210rollbacks (transaction processing),

163COMMIT statement, 165defined, 163ROLLBACK command,

164-165savebacks and, 166-167statements, 167

rowsadding to tables, 209compared to records, 9concepts, 9cursors, 168deleting, 209INSERT statement, 118-120

partial rows, 121-122preventing accidental deletion,

178updating, 211

RTRIM( ) function, 51-52, 60rules

combining queries, 114constraints, 175views, 145-146

Ssavepoints (transaction processing),

166-167defined, 163

scalablity, 93schemas, 7scripting, PHP, 203scripts, example tables, 192

search patternsdefined, 40wildcards, 40-41

% (percent sign) wildcard,41-42

[] (square brackets) wild-card, 44-46

_ (underscore) wildcard,43-44

cautions, 46searching

indexes, overview, 180-182trailing spaces and, 43wildcards

^ (caret) character, 45% character, 41-42[] (square brackets), 44-46_ (underscore), 43-44

securitydata, 185DELETE statement, 130INSERT statements, 118UPDATE statement, 127

SELECT INTO statement, 125INSERT SELECT statement

comparison, 125SELECT statement, 13

aggregate functions, combining,73-74

AS keyword, 53-54AVG( ) function, 67clauses, ordering of, 83columns

retrieving all, 17-18retrieving individual, 14-15retrieving multiple, 16-17retrieving unknown, 18

combiningcreating, 112-113duplicate rows and,

114-115overview, 111rules, 114sorting results, 116

concatenating fields, 50-51

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

Page 33: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

238 SAMS TEACH YOURSELF SQL IN TEN MINUTES

COUNT( ) function, 69FROM clause, creating joins,

94grouping data, 76-77IS NULL clause, 31ORDER BY clause, 20

positioning, 20syntax, 210

SELECT statementssubqueries, formatting, 87WHERE clause, 26WHERE clauses

combined queries, 111combining, 33NOT operator, 38

self joins, 102-104compared to subqueries, 104

semicolons (;), multiple statements,16

sequence (SELECT statementclauses), 83

server-based results formatting, com-pared to client-based, 49

SET command, updating tables, 128SIN( ) function, 65single quotation marks (‘)

WHERE clause operators and,30

SMALLDATETIME datatype, 216SMALLINT datatype, 215sorting

combined query results, 116compared to grouping, 80-82datatype functionality, 212indexes, overview, 180-182query results, 19-20

ascending/descendingorder, 23-24

by column position, 22by multiple columns, 21-22by nonselected columns,

21-23case sensitivity, 25

SOUNDEX( ) function, 60-61support for, 61

spacesremoving, RTRIM function,

51-52search results and, 43

specifying dates, 216speed, constraints versus triggers,

184SQL

deleting/updating data, 132extensions, 12overview, 11scripts, example tables, 192

SQL Servercursors, closing, 173Identity fields, 160local variables, @ character,

158running, 201savepoints, 166stored procedures, 158triggers, 184

SQRT( ) function, 65square brackets ([]) wildcard, 44-46statements

ALTER TABLE, 139-140syntax, 207

case sensitivity, 16clauses, 20COMMIT, 165

syntax, 208CREATE INDEX, 182

syntax, 208CREATE TABLE, 133-135

syntax, 208CREATE VIEW, 146

syntax, 209DELETE, 129-131

FROM keyword, 130syntax, 209transaction processing, 163

DROP, syntax, 209DROP TABLE, 141formatting, 135GRANT, 185grouping related operators, 35

Page 34: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

239INDEX

INSERTcompleting rows, 118-120omitting columns, 122overview, 118partial rows, 121-122query data, 122-124security privileges, 118syntax, 209transaction processing,

163VALUES, 121

INSERT SELECT, syntax, 210multiple, separating, 16OPEN CURSOR, 171RENAME, 141REVOKE, 185ROLLBACK, syntax, 210rollbacks, 163, 167

defined, 163SELECT, 13

AVG( ) function, 67combining, 111-116combining aggregate func-

tions, 73-74concatenating fields, 50-51COUNT( ) function, 69grouping data, 76-77retrieving all columns,

17-18retrieving individual

columns, 14-15retrieving multiple

columns, 16-17retrieving unknown

columns, 18syntax, 210

stored procedurescreating, 157-160disadvantages of, 155-156executing, 156-157overview, 153-154usefulness of, 154-155

syntax, 207-211

UPDATE, 127-131syntax, 211transaction processing, 163

white space, 15stored procedures

commenting code, 159creating, 157-160, 208disadvantages of, 155-156executing, 156-157Identity fields, 160Oracle, 157overview, 153-154triggers, 183usefulness of, 154-155

storingdate and time values, 216numeric values, cautions, 214strings, 213

string datatypes, 213strings

empty, compared to NULL val-ues, 137

fixed length, 213quotes, 214TRIM functions, 52variable-length, 213wildcard searching and, 41

subqueriesas calculated fields, 88-90compared to self joins, 104COUNT*, 89filtering by, 84-88formatting, 87multiple columns, 72NULL values, 72overview, 84performance, 88processing, 86self joins and, 103SUM( ) function, 67, 71UPDATE statement, 129WHERE clauses, 88

support, DBMS function support,57-58

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

Page 35: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

240 SAMS TEACH YOURSELF SQL IN TEN MINUTES

Sybase Adaptive Serverrunning, 204-205statements, ending, 16

syntaxALTER TABLE statements,

207column aliases, 101COMMIT statement, 208CREATE INDEX statement,

208CREATE TABLE statement,

133, 208CREATE VIEW statement, 209DELETE statement, 209DROP statement, 209INERT statement, 210INSERT statement, 209outer joins, 106ROLLBACK statement, 210SELECT statement, 210statements, 207-211transaction processing, 164triggers, 184UPDATE statement, 211

system date, default value syntax,138

system functions, 59

Ttables

calculated fieldsconcatenating fields, 49-54mathematical calculations,

55-56overview, 48-49

columns, 8aliases, creating, 101NULL value, checking for,

31primary keys, 10

concepts, 7copying, 126

copying data into tables,124-126

creating, 208CREATE TABLE statement,

134-135overview, 133-134

datatypes, 8default values, 137-138deleting, 141

preventing accidental dele-tion, 141

examplesCustomers table, 189downloading, 191

indexescautions, 182creating, 182searching, 181

INSERT statement, multiplerows, 124

inserting data, 118-120partial rows, 121-122from queries, 122-124

joinsCartesian Product, 95-97creating, 94cross joins, 97inner joins, 97-98multiple tables, 98-100overview, 91performance considera-

tions, 99usefulness of, 93WHERE clause, 95-97

Microsoft Access MDB file,192

naming, 7reserved words and, 13

natural joins, 104-105NULL value columns, 136-137outer joins, 105-108relational, 91-92renaming, 141replacing, 135

Page 36: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

241INDEX

rows, 9adding, 209deleting, 209updating, 211

schemas, 7security, 185SQL scripts, 192

functions of, 187OrderItems table, 191Orders table, 190Products table, 189Vendors table, 188

table name aliases, 101-102self joins, 102-104

triggers, 183creating, 184functionality, 183

updating, 127-129, 139-140deleting data, 129-130

views, creating, 209TAN( ) function, 65testing, Query Tool and, 203-204text functions, 59-60

list of common, 60TEXT string datatype, 214time functions, 59, 62-64TINYINT datatype, 215tools (DBMS), interactive, 93TOP argument, 73TOP PERCENT argument, 73totaling values

calculated values, 71SUM( ) function, 71

to_char( ) function, 63to_number( ) function, 63transaction processing, 166-167

blocks, ROLLBACK state-ments, 210

COMMIT command, 165defined, 163explicit commits, 165managing, 164overview, 161-162ROLLBACK command,

164-165

terminology, 163writing to databases, 208

triggers, 183creating, 184functionality, 183overview, 183-184speed, 184syntax examples, 184

TRIM( ) function, 52trimming padded spaces, 51-52troubleshooting

accidental table deletion, 141Query Tool and, 203-204

TRUNCATE TABLE statement, 131

UUCASE( ) function, 60underscore (_) wildcard, 43-44UNION operator

combined queries, 112-113compared to WHERE clauses,

115duplicate rows and, 114-115

rules, 114sorting results, 116

limits, 113UNION statements, types, 117unions (queries)

creating, 112-113duplicate rows and, 114-115overview, 111rules, 114sorting results, 116

unique constraints, 178-179UNIQUE keyword, 179unsorted data, query results, 15UPDATE statement, 127-129

FROM keyword, 129guidelines, 131security privileges, 127subqueries, 129syntax, 211

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

Page 37: THIRD EDITION - pearsoncmg.comptgmedia.pearsoncmg.com/images/9780672325670/samplepages/...7Creating Calculated Fields 48 Understanding Calculated Fields .....48 Concatenating Fields.....49

242 SAMS TEACH YOURSELF SQL IN TEN MINUTES

transaction processing, 163triggers, 183

updatingdata, guidelines, 131tables, 127-129, 139-140

deleting data, 129-130UPPER( ) function, 59-60user-defined datatypes, 180

Vvalues

concatenation, 50searching for (indexes), 181trimming padded space, 52

VARBINARY datatype, 217variable-length strings, 213Vendors table, 188views (tables)

calculated fields, 151-152creating, 145

creating, 209DBMS consistency, 144filtering data, 150joins, simplifying, 147-148overview, 143-146performance concerns, 145reformatting retrieved data,

148-149reusable, 148rules and restrictions, 145-146usefulness of, 144-145

virtual tables. See views

W-X-Y-ZWeb sites

Aqua Data Studio, 194example table download site,

191Query Tool, 194, 204

Web-based applications, cursors, 169

WHERE clause, 26. See also HAV-ING clause

BETWEEN operator, 30combining in queries, 111compared to UNION statement,

115DELETE statement, 130filtering groups, 79joins, 97joins and, 95-97multiple query criteria, 33

AND operator, 33-34IN operator, 36-38NOT operator, 38-39OR operator, 34-35order of evaluation, 35-36

NOT operator, 38operators, 28

checking against singlevalue, 29

checking for nonmatches,29-30

checking for NULL value,31

checking for range of val-ues, 30-31

quotes and, 30operators support by DBMS, 30parentheses and, 36positioning, 27SOUNDEX( ) function, 61subqueries, 87UPDATE statements, 127-128wildcards, 40

white space, SQL statements, 15wildcards

asterisk (*) character, 17-18caret (^) character, 45cautions, 46defined, 40LIKE operator and, 40-41natural joins, 105

writing stored procedures, 155

YEAR( ) function, 63