0% found this document useful (0 votes)
380 views

SQL Querying Fundamentals

SQL Fundamentos

Uploaded by

LotteDomine
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
380 views

SQL Querying Fundamentals

SQL Fundamentos

Uploaded by

LotteDomine
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 220

FO

INSTRUCTOR'S EDITION
(C
EV
)2 AL
01
7L UA
DO og

Fundamentals
SQL Querying:
NO ica TI

(Second Edition)
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,I nc
.
ON
LY
Read Me First!

LY
ON
Congratulations on selecting CHOICE courseware! This quick guide
will give you access to key instructor resources so you can present the best possible
CHOICE learning experience.

E
The CHOICE Instructor’s Edition

.
nc
US
This Instructor’s Edition is a crucial tool that provides you with all the course-specific
technical and setup information, delivery notes, and instructional material that you need

,I
as a training professional to deliver an excellent learning experience to your students.

AT ns
The CHOICE Facilitator’s Guide
ON
io
Before presenting this or any CHOICE course, make sure you explore the CHOICE
Facilitator’s Guide for critical information about virtual and blended course delivery

E
PL rat
techniques and the CHOICE instructional philosophy and learning experience. Get access
to the CHOICE Facilitator’s Guide through the CHOICE Facilitator’s Course.
DU pe
TI

IC
The CHOICE Facilitator’s Course
lO
UA

You can find the CHOICE Facilitator’s Guide and other great resources for delivering
Logical Operations courseware products through the free CHOICE Facilitator’s Course.
ica

To access the free Facilitator’s Course, simply:


1. Visit www.lo-choice.com
AL
og

2. Enter access key LCSYB24YEF


T

3. Download and explore the CHOICE Facilitator’s Guide!


7L
NO

The Logical Operations Instructor Community


EV
01

Logical Operations leads a very active online community and resource center where
DO

instructors from all over the world share their ideas, interact, and engage with each other.
)2

Join the community from the CHOICE Facilitator’s Course, or search www.linkedin.com for
R

the “Logical Operations Instructor Community” group to join the conversation.


(C

Again, congratulations on your choice—the right choice—the Logical CHOICE!


FO
FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
Fundamentals
SQL Querying:

AT ns E
(Second Edition)

E ,I nc
.
ON
LY
SQL Querying: Fundamentals (Second

LY
Edition)

ON
Part Number: 094018
Course Edition: 1.0

Acknowledgements

E
.
PROJECT TEAM

nc
US
Authors Media Designer Content Editor

,I
Rozanne Whalen Brian J. Sullivan Joe McElveney

AT ns
Brian S. Wilson ON
io
Logical Operations wishes to thank the Logical Operations Instructor Community, and in particular Sally Howard and Gary
Leenhouts, for their instructional and technical expertise during the creation of this course.

E
PL rat
Notices
DU pe
TI

DISCLAIMER
IC
While Logical Operations, Inc. takes care to ensure the accuracy and quality of these materials, we cannot guarantee their
lO

accuracy, and all materials are provided without any warranty whatsoever, including, but not limited to, the implied warranties of
UA

merchantability or fitness for a particular purpose. The name used in the data files for this course is that of a fictitious company. Any
resemblance to current or future companies is purely coincidental. We do not believe we have used anyone's name in creating this
ica

course, but if we have, please notify us and we will change the name in the next revision of the course. Logical Operations is an
independent provider of integrated training solutions for individuals, businesses, educational institutions, and government agencies.
The use of screenshots, photographs of another entity's products, or another entity's product name or service in this book is for
editorial purposes only. No such use should be construed to imply sponsorship or endorsement of the book by nor any affiliation of
AL
og

such entity with Logical Operations. This courseware may contain links to sites on the Internet that are owned and operated by third
parties (the "External Sites"). Logical Operations is not responsible for the availability of, or the content located on or through, any
T

External Site. Please contact Logical Operations if you have any concerns regarding such links or External Sites.
7L
NO

TRADEMARK NOTICES
EV

Logical Operations and the Logical Operations logo are trademarks of Logical Operations, Inc. and its affiliates.
01

® ® ® ® ®
Microsoft SQL Server 2017 and Microsoft SQL Server Management Studio 2017 are registered trademarks of Microsoft
DO

Corporation in the U.S. and other countries; the SQL Server 2017 products and services discussed or described may be trademarks
)2

®
of Microsoft Corporation.
All other product names and services used throughout this course may be common law or registered trademarks of their respective
R

proprietors.
(C

Copyright © 2017 Logical Operations, Inc. All rights reserved. Screenshots used for illustrative purposes are the property of the
software proprietor. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means,
FO

electronic or mechanical, including photocopying, recording, storage in an information retrieval system, or otherwise, without
express written permission of Logical Operations, 3535 Winton Place, Rochester, NY 14623, 1-800-456-4677 in the United States
and Canada, 1-585-350-7000 in all other countries. Logical Operations’ World Wide Web site is located at
www.logicaloperations.com.
This book conveys no rights in the software or other products about which it was written; all use or licensing of such software or
other products is the responsibility of the user according to terms and conditions of the owner. Do not make illegal copies of books
or software. If you believe that this book, related materials, or any other Logical Operations materials are being reproduced or transmitted
without permission, please call 1-800-456-4677 in the United States and Canada, 1-585-350-7000 in all other countries.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
SQL Querying:

LY
Fundamentals (Second

ON
Edition)

E
.
nc
US
,I
AT ns
Lesson 1: Executing a Simple Query................................1
ON
io
Topic A: Connect to the SQL Database............................................2

E
Topic B: Query a Database............................................................14
PL rat
Topic C: Save a Query...................................................................23
DU pe
TI

Topic D: Modify and Execute a Saved Query................................. 25


IC
lO
UA

Lesson 2: Performing a Conditional Search................... 35


ica

Topic A: Search Using One or More Conditions............................. 36


AL
og

Topic B: Search for a Range of Values and NULL Values................ 56


T

Topic C: Search Data Based on String Patterns.............................. 63


7L
NO
EV

Lesson 3: Working with Functions................................. 71


01
DO

Topic A: Perform Date Calculations.............................................. 72


)2

Topic B: Calculate Data Using Aggregate Functions...................... 82


R
(C

Topic C: Manipulate String Values................................................ 88


FO

Lesson 4: Organizing Data............................................99


Topic A: Sort Data...................................................................... 100
| SQL Querying: Fundamentals (Second Edition) |

Topic B: Rank Data............................................................................... 104


Topic C: Group Data............................................................................. 113
Topic D: Filter Grouped Data................................................................ 120

LY
Topic E: Summarize Grouped Data....................................................... 123
Topic F: Use PIVOT and UNPIVOT Operators......................................... 128

ON
Lesson 5: Retrieving Data from Multiple Tables.................. 135
Topic A: Combine the Results of Two Queries...................................... 136
Topic B: Compare the Results of Two Queries.......................................142

E
Topic C: Retrieve Data by Joining Tables...............................................145

.
nc
US
,I
Lesson 6: Exporting Query Results......................................165

AT ns
Topic A: Generate a Text File................................................................166
ON
Topic B: Generate an XML File...............................................................170

io
E
PL rat
Appendix A: The Pub1 Database......................................................... 177
DU pe
TI

Mastery Builders................................................................................. 181


IC
Glossary............................................................................................. 191
lO
UA

Index.................................................................................................. 195
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
Using the SQL Querying:

LY
Fundamentals (Second

ON
Edition) Instructor's
Edition

E
.
nc
US
,I
AT ns
Welcome to the Instructor
ON
io
Welcome and congratulations on your choice to use the finest materials available on the

E
PL rat
market today for expert-facilitated learning in any presentation modality. You can utilize the
SQL Querying: Fundamentals (Second Edition) curriculum to present world-class instructional
experiences whether:
DU pe
TI

• Your students are participating with you in the classroom or virtually.


IC
• You are presenting in a continuous event or in an extended teaching plan, such as an
lO

academic semester.
UA

• Your presentation takes place synchronously with the students or asynchronously.


• Your students have physical courseware or are using digital materials.
ica

• You have any combination of these instructional dimensions.


To make the best use of the SQL Querying: Fundamentals (Second Edition) materials in any or all
AL
og

of these dimensions, be sure to review the contents of the CHOICE Facilitator's Guide for
an orientation to all of the components of the CHOICE experience.
T
7L
NO

Preparing to Present the CHOICE Experience


EV

Effectively presenting the information and skills in this course requires adequate preparation
01

in any presentation modality. As such, as an instructor, you should familiarize yourself with
the content of the entire course, including its organization and instructional approaches.
DO

You should review each of the student activities, exercises, and Mastery Builders so you can
)2

facilitate them during the learning event. Also, make sure you review the tips for presenting
in the different dimensions; these instructor tips are available as notes in the margins of your
R
(C

Instructor's Edition.
In addition to the curriculum itself, Microsoft® PowerPoint® slides, data files, and other
FO

course-specific support material may be available by downloading the files from the
CHOICE Course screen. Be sure to obtain the course files prior to your learning event and
make sure you distribute them to your students.
| SQL Querying: Fundamentals (Second Edition) |

Course Facilitator Icons


Throughout the Instructor’s Edition, you may see various instructor-focused icons that provide
suggestions, answers to problems, and supplemental information for you, the instructor.

Icon Description

LY
A display slide note provides a prompt to the instructor to display a specific slide
from the provided PowerPoint files.
Content delivery tips provide guidance for specific delivery techniques you may

ON
want to utilize at particular points in the course, such as lectures, whiteboard
sketching, or performing your own demonstrations for the class.
Managing learning interactions provide suggested places to interact with the class
as a whole. You might poll the class with closed-ended questions, check
comprehension with open-ended questions, conduct planned discussion activities,
or take notes and questions from the group to "park" and address at a later point in

E
the class.

.
Monitoring learner progress notes suggest when you might want to monitor

nc
US
individual students as they perform activities, or have private sidebar conversations
with specific individual participants.

,I
Engaging learners notes suggest opportunities to involve the students in active

AT ns
ways with the course presentation, such as enabling them to demonstrate their work
to the class as a whole, or checking in on the logistics of the presentation.
ON
io
Incorporating other assets notes suggest when and how to include other types of
media, such as visiting CHOICE social media sites, accessing specific web resources,

E
PL rat
or utilizing media assets provided with the course, such as Logical Operations'
Spotlights.
DU pe
TI

Digital Software Updates


IC
The software vendor may at any time deploy software updates digitally, resulting in changes that
lO
UA

may not be reflected dynamically in this course. Stay up to date with product updates and be ready
to adapt the material to any changes in the user interface.
ica

Course-Specific Technical Requirements


AL
og

Hardware
T

For this course, you will need one computer for each student and one for the instructor. Each
7L

computer will need the following minimum hardware configurations:


NO

• 2 GHz or faster 64-bit (x64) processor


EV

• 4 gigabytes (GB) RAM


01

• 40 GB available hard disk space


DO

• CD-ROM drive (if installing any software from a CD-ROM)


)2

• Keyboard and mouse (or other pointing device)


• 1024 x 768 (or higher) resolution monitor recommended
R
(C

• Network cards and cabling for local network access


• Internet access (contact your local network administrator)
FO

• Printer (optional) or an installed printer driver


• Projection system to display the instructor's computer screen

| Using the SQL Querying: Fundamentals (Second Edition) Instructor's Edition |


| SQL Querying: Fundamentals (Second Edition) |

Software
To prepare a student or instructor system for the class, install the following software according to
the instructions provided. You will need the following software for each student and instructor
computer:
• Microsoft® Windows® 10 64-bit with sufficient licenses.

LY
Windows 10 requires activation unless you have volume-licensing agreements. There is a grace
period for activation. If the duration of your class will exceed the activation grace period (for
example, if you are teaching the class over the course of an academic semester), you should
activate the installations at some point before the grace period expires. Otherwise, the operating

ON
system may stop working before the class ends.
• Microsoft® SQL Server® 2017 Express. (When this course was written, the installation file for
this free software was available for download from https://www.microsoft.com/en-us/sql-
server/sql-server-downloads.)
• Microsoft® SQL Server® Management Studio (SSMS). (When this course was written, the
installation file for this free software was available for download from https://

E
docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms.)

.
nc
US
Setting Up the Course

,I
For each student and the instructor:
1. Prepare a Windows 10 computer.

AT ns
a. Install Microsoft Windows 10 with a local administrator account. You will need to provide
ON
the student or instructor using the computer with a local administrator account, so create a

io
separate user account for that purpose if you do not want to provide them with the main
administrator account on the computer.

E
b. Download and install any available Windows updates. PL rat
c. Restart the computer and log in using the local administrator account.
DU pe
TI

2. Change how Windows updates are delivered to avoid Windows updates during the class.
IC
a. Select the Start button.
lO

b. Select Settings.
UA

c. Select Update & Security.


d. In the Update settings group, select Advanced options.
ica

e. Select the Delivery Optimization link.


AL

Note: If you are using a version of Windows prior to the 2017 Fall Creator's Update,
og

select the Choose how updates are delivered link, and slide the toggle to Off.
T

f. Select the option to Allow downloads from other PCs.


7L
NO

g. Close the Settings app.


EV

3. Ensure Windows 10 displays file extensions and hidden items.


01

a. Open File Explorer.


DO

b. On the ribbon, select the View tab.


)2

c. On the ribbon, in the Show/hide group, check the File name extensions and Hidden
items check boxes.
R

d. Close File Explorer.


(C

4. Install SQL Server 2017 Express.


FO

a. Download SQL Server 2017 Express from the Microsoft website.


b. Right-click the installation file for SQL Server 2017 Express that you just downloaded from
the Microsoft website, and select Run as administrator.
c. If you are prompted by the User Account Control message box to allow the installation of
SQL Server 2017 Express Edition, select Yes.
d. In the SQL Server 2017 Express Edition dialog box, select the Basic installation option.

| Using the SQL Querying: Fundamentals (Second Edition) Instructor's Edition |


| SQL Querying: Fundamentals (Second Edition) |

e. Select Accept to accept the license terms.


f. When prompted for the install location, select Install to use the default location.
g. When the installer shows the message Installation has completed successfully!, select
Close, and select Yes to confirm.
h. Restart the computer, and log back in to Windows with the local administrator account.

LY
5. Install SQL Server Management Studio.
a. Download Microsoft SQL Server Management Studio (SSMS) from the Microsoft
website.
b. Right-click the installation file for SQL Server Management Studio that you just downloaded

ON
from the Microsoft website, and select Run as administrator.
c. If you are prompted by the User Account Control message box to allow the installation of
SQL Server Management Studio, select Yes.
d. At the Welcome page, select Install.
e. When installation completes, select Close.
6. Install the course data files.

E
a. From the course Files tile on CHOICE, download the 094018Files<ver>.zip file to any

.
nc
US
location that is convenient for you.
Note: The default download folder will vary depending on your browser version and

,I
local settings.

AT ns
b. Go to the download folder and locate and unzip (extract) the 094018Files<ver>.zip file.
This will create a local 094018Files<ver> folder. It contains separate subfolders with your
ON
course overheads and the course data files.

io
c. Open the 094018Files<ver> folder.

E
PL rat
d. Move or copy the 094018Data folder to the root of your C drive. This installs the data files to
the location specified in the course activities.
DU pe
TI

Note: If you prefer to place the data files in a different location, simply inform your
students that they will be accessing the files from that alternate path.
IC
lO

The data files folder contains all the lesson-specific subfolders and data files you will need to run
UA

this course. There is a separate folder with the starter files for each lesson or Mastery Builder,
and there may be a Solutions folder with completed files students can use to check their results.
ica

7. Connect to the database server in SQL Server Management Studio.


a. Use the student login account to log in to Windows.
AL
og

b. Show the Windows Start menu. Locate the SQL Server Management Studio tile. Right-
click the tile, select More, and select Run as administrator.
T

c. In the Connect to Server dialog box, in the Server type drop-down list, verify that
7L
NO

Database Engine is selected.


EV

d. In the Server name drop-down list, select the down arrow, and select <Browse for
01

more...>.
DO

e. Before Database Engine, select + to expand the list, showing available database engines.
f. Select the database engine identified by the computer's name followed by SQLEXPRESS,
)2

and select OK.


g. In the Authentication drop-down list, make sure that Windows Authentication is selected.
R
(C

h. Select Connect to connect to the server.


8. Attach the Pub1 database provided in the course setup files.
FO

a. In the Object Explorer pane (left side of the application), make sure the top icon is
expanded so you can see the Databases folder. Right-click the Databases folder, and select
Attach.
b. Select Add.

| Using the SQL Querying: Fundamentals (Second Edition) Instructor's Edition |


| SQL Querying: Fundamentals (Second Edition) |

c. In the left pane, select the C:\094018Data folder. You may need to scroll and expand folders
in order to see this folder.
d. In the right pane, select Pub1.mdf.
e. Select OK to return to the Attach Databases dialog box.
f. Select OK to return to the main window of the SQL Server Management Studio.

LY
g. In the Object Explorer pane, expand the Databases folder and verify that the Pub1
database is shown.
Note: This course is often delivered as the first day in a two-day series, along with SQL
Querying: Advanced (Second Edition). The software setup for these two courses is identical. If

ON
you plan to deliver these courses back-to-back, at this point you should install the course
data files for SQL Querying: Advanced (Second Edition), using the steps shown in Step 8 to
attach the Pub2 database from the C:\094019Data folder. If you do this, then no
additional setup steps will be required for the SQL Querying: Advanced (Second Edition)
(094019) course.

E
9. Select File→Exit to exit SQL Server Management Studio.

.
nc
Presentation Planners

US
The lesson durations given in the course content are estimates based on a typical class experience.

,I
The following planners show examples of how the content could be presented in either a
continuous flow or separately across a multi-session seminar series. Your presentation flow may vary

AT ns
based on a number of factors, including the size of the class, whether students are in specialized job
roles, whether you plan to incorporate Spotlights or other assets from the CHOICE Course screen
ON
io
into the course, and so on. Use the samples and blank planners to determine how you will conduct
the class to meet the needs of your own situation.

E
Continuous Presentation: Model Class Flow PL rat
This planner provides a sample presentation flow based on one 8-hour day of training with breaks
DU pe
TI

and lunch factored in.


IC
Section Duration Day Planner
lO
UA

Welcome and Introductions 0:30 8:30 - 9:00


ica

Lesson 1: Executing a Simple Query 0:45 9:00 - 9:45


Lesson 2: Performing a Conditional Search 0:30 9:45 - 10:15
AL
og

BREAK 0:15 10:15 - 10:30


T

Lesson 2: Performing a Conditional Search 1:15 10:30 - 11:45


7L
NO

(Cont.)
EV

Lesson 3: Working with Functions 0:30 11:45 - 12:15


01

LUNCH 0:30 12:15 - 12:45


DO

Lesson 3: Working with Functions (Cont.) 0:30 12:45 - 1:15


)2

Lesson 4: Organizing Data 1:30 1:15 - 2:45


R
(C

BREAK 0:15 2:45 - 3:00


Lesson 5: Retrieving Data from Multiple Tables 1:30 3:00 - 4:30
FO

Lesson 6: Exporting Query Results 0:30 4:30 - 5:00

Continuous Presentation: Your Class Flow

| Using the SQL Querying: Fundamentals (Second Edition) Instructor's Edition |


| SQL Querying: Fundamentals (Second Edition) |

Use this planner to plan the flow of your own training day based on the needs of your students, the
schedule for your own day, and/or any other modifications you choose.

Section Duration Day Planner

Welcome and Introductions

LY
Lesson 1: Executing a Simple Query

Lesson 2: Performing a Conditional Search

ON
Lesson 3: Working with Functions

E
Lesson 4: Organizing Data

.
nc
US
Lesson 5: Retrieving Data from Multiple Tables

,I
AT ns
Lesson 6: Exporting Query Results ON
io
Non-continuous Presentation: Model Class Flow

E
PL rat
This planner provides a sample presentation flow based on separate sessions presented over
multiple days or weeks.
DU pe
TI

Session Number Material Covered Session Duration


IC
lO

One Welcome and Introductions 1:15


UA

Lesson 1: Executing a Simple Query


ica

Two Lesson 2: Performing a Conditional Search 1:45


Three Lesson 3: Working with Functions 2:30
AL
og

Lesson 4: Organizing Data


T
7L

Four Lesson 5: Retrieving Data from Multiple Tables 2:00


NO

Lesson 6: Exporting Query Results


EV
01

Non-continuous Presentation: Your Class Flow


DO
)2
R
(C
FO

| Using the SQL Querying: Fundamentals (Second Edition) Instructor's Edition |


| SQL Querying: Fundamentals (Second Edition) |

Use this planner to plan how you will present the course content based on the needs of your
students, your conventions for the number and length of sessions, and any other modifications you
choose.

Session Number Material Covered Session Duration

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

| Using the SQL Querying: Fundamentals (Second Edition) Instructor's Edition |


FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
About This Course

LY
ON
Organizations typically store their most critical information—the information used to
manage day-to-day operations—within a database. The ability to retrieve and analyze this

E
information is essential to the functioning of the organization. Structured Query Language

.
(SQL) is the primary language used to accomplish such tasks. Essentially, SQL is the

nc
US
language you use to interact with a database.
The ability to write SQL is an essential job skill for those who need to manage large

,I
volumes of data, produce reports, mine data, or combine data from multiple sources. Even
if someone else on your team creates reports for you, having a fundamental understanding

AT ns
of SQL querying will help you ask the right questions and know what you're looking for in
your data analysis tools.
ON
io
This course, SQL Querying: Fundamentals (Second Edition), will teach you to use SQL as a tool
to retrieve the information you need from databases.

E
PL rat
Course Description
DU pe
TI

IC
Target Student
lO

This course is intended for individuals with basic computer skills, familiar with concepts
UA

related to database structure and terminology, who want to use SQL to query databases.
ica

Course Prerequisites
Basic end-user computer skills and some familiarity with database terminology and structure
AL
og

are required. Completion of one of the following Logical Operations courses or equivalent
knowledge and skill is highly recommended:
T

• Using Microsoft® Windows® 10


7L
NO

• Microsoft® Windows® 10: Transition from Windows® 7


EV

Course Objectives
01
DO

In this course, you will compose SQL queries to retrieve desired information from a
database.
)2

You will:
R
(C

• Connect to the SQL Server database and execute a simple query.


• Include a search condition in a simple query.
FO

• Use various functions to perform calculations on data.


• Organize the data obtained from a query before it is displayed onscreen.
• Retrieve data from multiple tables.
• Export the results of a query.
| SQL Querying: Fundamentals (Second Edition) |

The CHOICE Home Screen


Logon and access information for your CHOICE environment will be provided with your class
experience. The CHOICE platform is your entry point to the CHOICE learning experience, of
which this course manual is only one part.
On the CHOICE Home screen, you can access the CHOICE Course screens for your specific

LY
courses. Visit the CHOICE Course screen both during and after class to make use of the world of
support and instructional resources that make up the CHOICE experience.
Each CHOICE Course screen will give you access to the following resources:

ON
• Classroom: A link to your training provider's classroom environment.
• eBook: An interactive electronic version of the printed book for your course.
• Files: Any course files available to download.
• Checklists: Step-by-step procedures and general guidelines you can use as a reference during
and after class.
• Spotlights: Brief animated videos that enhance and extend the classroom learning experience.

E
• Assessment: A course assessment for your self-assessment of the course content.

.
• Social media resources that enable you to collaborate with others in the learning community

nc
US
using professional communications sites such as LinkedIn or microblogging tools such as
Twitter.

,I
Depending on the nature of your course and the components chosen by your learning provider, the
CHOICE Course screen may also include access to elements such as:

AT ns
• LogicalLABS, a virtual technical environment for your course.
ON
• Various partner resources related to the courseware.

io
• Related certifications or credentials.

E
PL rat
• A link to your training provider's website.
• Notices from the CHOICE administrator.
• Newsletters and other communications from your learning provider.
DU pe
TI

• Mentoring services.
IC
Visit your CHOICE Home screen often to connect, communicate, and extend your learning
lO
UA

experience!
ica

How to Use This Book


As You Learn
AL
og

This book is divided into lessons and topics, covering a subject or a set of related subjects. In most
T

cases, lessons are arranged in order of increasing proficiency.


7L
NO

The results-oriented topics include relevant and supporting information you need to master the
content. Each topic has various types of activities designed to enable you to solidify your
EV

understanding of the informational material presented in the course. Information is provided for
01

reference and reflection to facilitate understanding and practice.


DO

Data files for various activities as well as other supporting files for the course are available by
)2

download from the CHOICE Course screen. In addition to sample data for the course exercises, the
course files may contain media components to enhance your learning and additional reference
R
(C

materials for use both during and after the course.


Checklists of procedures and guidelines can be used during class and as after-class references when
FO

you're back on the job and need to refresh your understanding.


At the back of the book, you will find a glossary of the definitions of the terms and concepts used
throughout the course. You will also find an index to assist in locating information within the
instructional components of the book. In many electronic versions of the book, you can click links
on key words in the content to move to the associated glossary definition, and on page references in

| About This Course |


| SQL Querying: Fundamentals (Second Edition) |

the index to move to that term in the content. To return to the previous location in the document
after clicking a link, use the appropriate functionality in your PDF viewing software.

As You Review
Any method of instruction is only as effective as the time and effort you, the student, are willing to

LY
invest in it. In addition, some of the information that you learn in class may not be important to you
immediately, but it may become important later. For this reason, we encourage you to spend some
time reviewing the content of the course after your time in the classroom.

As a Reference

ON
The organization and layout of this book make it an easy-to-use resource for future reference.
Taking advantage of the glossary, index, and table of contents, you can use this book as a first
source of definitions, background information, and summaries.

Course Icons

E
Watch throughout the material for the following visual cues.

.
nc
US
Icon Description

A Note provides additional information, guidance, or hints about a topic or task.

,I
AT ns
A Caution note makes you aware of places where you need to be particularly careful
with your actions, settings, or decisions so that you can be sure to get the desired
results of an activity or task.
ON
io
Spotlight notes show you where an associated Spotlight is particularly relevant to

E
PL rat
the content. Access Spotlights from your CHOICE Course screen.
Checklists provide job aids you can use after class as a reference to perform skills
back on the job. Access checklists from your CHOICE Course screen.
DU pe
TI

IC
Social notes remind you to check your CHOICE Course screen for opportunities to
interact with the CHOICE community using social media.
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

| About This Course |


FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
1 Executing a Simple

LY
Query

ON
Lesson Time: 45 minutes

E
.
nc
US
Lesson Introduction

,I
AT ns
In this course, you will query an SQL database using fundamental query techniques. Simple
queries form the basis of building your querying skills. In this lesson, you will begin by
ON
composing and executing a simple SQL statement to retrieve information from a database.

io
You will then modify and save a query so that you can use it later.

E
Lesson Objectives
PL rat
DU pe
TI

In this lesson, you will:


IC
lO

• Connect to the database using SQL Server Management Studio.


UA

• Query the database.


ica

• Save a query for future use.


• Modify an existing query.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
2 | SQL Querying: Fundamentals (Second Edition)

TOPIC A
Connect to the SQL Database

LY
In this lesson, you will execute a simple query to retrieve information. To do so, you must first
connect to the server that contains the database. In this topic, you will access the database that
contains the appropriate information.

ON
Databases
A typical database can be a vast collection of information. Organizations use databases to store
large amounts of data such as inventory, sales, and customer information. For example, a publishing
Database
company might have a database containing information about books, customers, orders placed,

E
representatives, and sales.

.
For optimal performance, organizations typically store these databases on servers located either on

nc
US
the corporate network or even stored in the cloud. When you need to retrieve information from the
databases, you do so by first connecting to the server and then using a querying tool to select the

,I
data you want to view.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01

Figure 1-1: Objects in a database.


DO
)2

Information within a database is organized within various objects. An example of a database object
is a table. You use tables to store the information within a database. You can search, retrieve,
R

manipulate, and delete the information in tables.


(C
FO

Lesson 1: Executing a Simple Query | Topic A


SQL Querying: Fundamentals (Second Edition) | 3

Default and Customized


Databases

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 1-2: Default and customized databases.


IC
Some databases are created by default when you install a database application such as Microsoft®
lO
UA

SQL Server® 2017, and you can create and customize other databases to suit your business needs.
ica

Tables
One type of object found in a database is a table. A table is a collection of related information
AL
og

arranged in rows and columns. Information about each item in the collection is displayed as a row.
Columns contain the same category of information for every item in the table. A table has a header
T

Tables
row that identifies the category of information stored in each column.
7L
NO

You use tables to store the information contained in the database. For example, in a database for a
EV

publishing company, you might find a table that contains information about the books the company
01

has published. Each of the rows in the table represents a title that the company publishes. The
DO

columns in the table contain the information the company wants to track for each book: the book's
part number, title, development cost, author, and so on.
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic A


4 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
Figure 1-3: A table displaying information about books.

,I
AT ns
Client/Server Architecture for SQL Databases
ON
SQL database systems are often deployed in a client/server architecture. This means that the

io
services for storing, managing, and presenting data are distributed among two or more computers.

E
As the name implies, there are two tiers in the client/server architecture:
Client/Server
Architecture for SQL
PL rat
• The client tier typically presents data and commands in a user-friendly format that is meant for
Databases humans—through a desktop computer application or a mobile app, for example. End users
DU pe
TI

interact with the client tier.


IC
• The server tier works directly with the database, managing data on behalf of the many clients
lO

that share access to the database. The server tier is managed by system operators/administrators.
UA

End users do not interact directly with it.


The following diagram and table describe various components involved in a client/server
ica

architecture.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic A


SQL Querying: Fundamentals (Second Edition) | 5

LY
ON
E
.
nc
US
,I
AT ns
Figure 1-4: A database server connected to three clients.
ON
io
Item Description

E
Database server
PL rat
Databases are typically hosted on a server. A server is a computer that
provides one or more services to other computers on a network. Servers
DU pe
TI

are high-performance computers designed to provide services to multiple


IC
users simultaneously. This server may be located at your company or in
lO

the cloud.
UA

Database application A database application such as Microsoft SQL Server 2017 runs on the
database server to manage communication between the server and clients.
ica

Network The server and clients communicate data and commands across a
network connection. The client may be located on the same network as
AL
og

the server, or it may connect to the server from a remote location, such as
across the Internet.
T
7L
NO

Client End users get their database work done indirectly through a client, which
is typically a computer or mobile device (such as a smartphone or tablet)
EV

running an operating system such as Microsoft® Windows®, Android,


01

iOS, MacOS, or Linux.


DO

Client application A software application running on the client provides a user interface
)2

through which users can enter, view, and modify data, typically through a
user-friendly interface that presents data in tables or entry forms, with
R
(C

buttons, text boxes, and other controls. In the background, the client
application uses a database language (such as SQL) to communicate with
the database server, translating the end user's requests into instructions
FO

that the database server can understand.

Lesson 1: Executing a Simple Query | Topic A


6 | SQL Querying: Fundamentals (Second Edition)

Item Description
User A client application may provide different levels of access to different
types of users. For example, in a bookstore's database, content
administrators may have more control over content (such as book prices
and descriptions) than salespeople do. And salespeople may have access

LY
to book data that end users viewing book information on a website don't
have (such as the cost to produce and print a book).

ON
Other Architectures for SQL Databases
There are other architecture models besides the two-tiered client/server architecture. For example,
an application might use an additional tier that processes the business logic of the application
Web and Database
separate from the database server and the client. Yet another tier of software and hardware may
Servers prepare the presentation of the application (the user interface, essentially).

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C

Figure 1-5: Web and database servers in a three-tier architecture.


FO

Web application servers obtain dynamic data content from the database server and add static web
content, such as HTML code, graphics, and other documents to present the data in an attractive
format, and provide a user interface that users can experience through a web browser.
In some organizations, rather than installing database servers directly on the organization's network,
administrators may choose to deploy database servers that are hosted by third-party providers on

Lesson 1: Executing a Simple Query | Topic A


SQL Querying: Fundamentals (Second Edition) | 7

the Internet. The term "cloud-based computing" refers to the act of connecting to and using servers
that are hosted on the Internet ("in the cloud") instead of on a local network.
One reason network administrators elect to use cloud-based database servers is to minimize the cost
of installing and maintaining the servers themselves. Hosting the servers on the Internet also makes
them accessible to clients located anywhere in the world. Another reason is that services like

LY
Amazon Web Services and Google Cloud Platform can provide you with access to massive amounts
of storage and processing power in their data centers, enabling you to process huge data sets that
might be impractical to process using your local servers.

ON
SQL
Structured Query Language (SQL) is the language that a client application uses to communicate
with an SQL database. SQL consists of commands that create and manage databases and tables, as
well as retrieve, delete, and modify information in those tables. It is a standard language that works SQL
with a wide variety of different database applications, so it has been among the most desirable of IT

E
skills for years, and will continue to be in demand for data analysts, web developers, application
developers, and others.

.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 1-6: A typical SQL exchange between a client and server.


IC
lO
UA

Note: You may hear SQL pronounced as "ess queue ell" or "sequel," depending on whom you
talk to. Both pronunciations are in common use. The original language was named SEQUEL
(Structured English Query Language) but had to be changed to SQL due to a trademark conflict.
ica

When the language was standardized by the American National Standards Institute (ANSI) in
1986, the official pronunciation was identified as "ess queue ell." However, in some development
circles, the original "sequel" pronunciation is preferred. In general, this course assumes the "S-Q-
AL
og

L" pronunciation (as in "an SQL database"), and "sequel" when referring specifically to the
T

Microsoft SQL Server product (as in "a SQL Server implementation").


7L
NO

SQL Command Groups


EV
01

SQL is made up of three major command groups, described in the following table.
DO
)2

Command Group Description of This Command Group Example Commands


SQL Command Groups
Data Manipulation
R

• Views, changes, and manipulates data within SELECT


(C

Language (DML) a table UPDATE


• Includes commands to select, update, and INSERT
FO

insert data in a table, and delete data from a DELETE


table
• Typically used by data analysts, report
authors, and programmers writing client
applications

Lesson 1: Executing a Simple Query | Topic A


8 | SQL Querying: Fundamentals (Second Edition)

Command Group Description of This Command Group Example Commands


Data Definition • Creates and defines the database and objects CREATE TABLE
Language (DDL) within it DROP TABLE
• Includes commands to create and delete CREATE VIEW

LY
tables DROP VIEW
• Typically used by database administrators
and programmers
Data Control Language • Controls access to the data in a database REVOKE

ON
(DCL) • Includes commands to grant and revoke GRANT
database privileges
• Typically used by database administrators
and programmers

E
Ways SQL Is Used

.
nc
US
Depending on your role, there are various ways you might use SQL. For example, many
organizations collect data such as sales or manufacturing data, market research, logistics, and so

,I
Direct Interaction
forth. Data analysts transform this raw data into information that organizations can use to make
informed decisions. This involves sorting, filtering, and formatting database content to produce

AT ns
reports or data sets that are ready for further processing in other software tools.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV

Figure 1-7: Direct interaction with a database server.


01
DO

A data analyst might work with a database using tools such as Microsoft SQL Server Management
)2

Studio, typing SQL statements directly to extract information from a database, or saving a series of
Point out that this is how SQL statements in a script that can be run repeatedly (at the end of every month, for example).
R
(C

students will interact with Some organizations might have a separate database administrator role—a role responsible for setting
SQL in this course, up and managing databases. Like the data analyst, a database administrator might work in a tool
entering interactive SQL
FO

such as Microsoft SQL Server Management Studio, entering SQL statements directly to create and
commands in the SQL
manage databases and tables.
Server Management
Studio.

Lesson 1: Executing a Simple Query | Topic A


SQL Querying: Fundamentals (Second Edition) | 9

Embedded in Application
Code

LY
ON
E
.
nc
US
,I
AT ns
Figure 1-8: SQL statements embedded with application code.
ON
io
End users of client applications don't have to manually enter SQL statements, as the client

E
PL rat
application constructs SQL statements on their behalf. The desktop, mobile, or web application
developers who create client applications may work with SQL a bit differently than data analysts or
administrators, creating applications in a programming language such as Java, C#, VB.NET, C++,
DU pe
TI

PHP, or Python, and using that language to construct SQL statements dynamically. For example, a
IC
client application might use data entered by the user into a search text field in a client application as
lO

the basis for creating an SQL statement that it sends to the database server. When the results are
UA

returned to the application from the database server, the application displays them.
ica

The Query Editor Window


AL
og

One of the tools you can use to access a Microsoft SQL Server database is Microsoft SQL Server
Management Studio (SSMS). Within SSMS, you'll primarily use the Query Editor window to
T

execute queries. The Query Editor window consists of two panes. The top pane is the editor pane, The Query Editor
7L
NO

where you enter SQL statements. The bottom section contains the Results pane, which displays the Window
results of queries, and the Messages tab, which displays information about the query that you
EV

execute.
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic A


10 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
AT ns
Figure 1-9: The Query Editor window consisting of a statement and results.
ON
io
Access the Checklist tile on your CHOICE Course screen for reference information and

E
PL rat
job aids on How to Connect to a Database.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic A


SQL Querying: Fundamentals (Second Edition) | 11

ACTIVITY 1-1
Connecting to a Database

LY
Before You Begin
As part of course setup, Microsoft SQL Server 2017 and SQL Server Management Studio have been

ON
installed, and the Pub1 database (located in C:\094018Data\Pub1.mdf) has been connected to the
server.

Scenario
Fuller & Ackerman is a publishing company. They store organizational data in a SQL Server 2017 Activity: Connecting to a

E
database called Pub1. This database contains information about customers, books published by the Database
company, obsolete titles, sales transactions, and details of sales representatives working for the

.
nc
US
company.
In this activity, you'll prepare to start working with the database in SQL by doing the following:

,I
• Connecting to the server
• Making sure the Pub1 database is attached to the server

AT ns
• Entering the USE command to identify which database your SQL commands apply to
ON
For information on tables and column names in the Pub1 database, refer to the table structure in

io
Appendix A.

E
PL rat
Note: Activities may vary slightly if the software vendor has issued digital updates. Your
instructor will notify you of any changes.
DU pe
TI

IC
lO

1. Launch SQL Server Management Studio and connect to the server.


UA

Notify students of any


a) On the Start screen, select Microsoft SQL Server Management Studio. changes to activities
based on digital software
ica

updates issued by the


software vendor.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic A


12 | SQL Querying: Fundamentals (Second Edition)

b) In the Connect to Server dialog box, select Connect to connect to the server.

LY
ON
E
.
nc
US
,I
AT ns
The database server has already been set up for you as part of the course setup.
ON
io
2. Verify that the Pub1 database is attached to the server.

E
PL rat
a) In Object Explorer, before the Databases folder icon, select +.
b) Before the System Databases folder icon, select +.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Various sample databases were included in the SQL Server installation. The database you'll be
using for the course, Pub1, has also been attached to the server as part of the course setup.
R

Point out that SQL is not


(C

case sensitive.
3. Establish the context for SQL commands.
FO

a) On the Standard toolbar, select New Query to open the Query Editor window.
Use the control in the b) In the editor pane, type:
lower-left corner of the USE Pub1
code editor to change
the zoom level so
students can see your
screen better.

Lesson 1: Executing a Simple Query | Topic A


SQL Querying: Fundamentals (Second Edition) | 13

c) On the SQL Editor toolbar, select Execute.

Since multiple
databases are available,

LY
the system needs to
know which database
your SQL statements
d) Notice that Pub1 is now selected in the Available Databases drop-down list. apply to. The USE
command identifies the

ON
target of your SQL
statements.

Point out that students


should not be concerned

E
if the titles in their tabs
and windows differ from

.
nc
those shown in the

US
screen images.

,I
You have successfully logged in to SQL Server and selected the Pub1 database as the context for
subsequent SQL statements that you will add to the script.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic A


14 | SQL Querying: Fundamentals (Second Edition)

TOPIC B
Query a Database

LY
When you are connected to a database, you can access the information stored in its tables. One way
you access table information is by viewing it. The command you use to view information is the
SELECT command. In this topic, you will retrieve information from a database by using SELECT
statements.

ON
Queries
A query is an SQL statement that requests information from tables present in a database. When the
database server receives a query, it determines which table or tables contain the requested data, and

E
A Query
which columns and rows should be returned, based on the data requested in the query.

.
nc
US
The SELECT Command

,I
You construct a query in SQL by using the SELECT command. The order of column names you
include in the SELECT statement determines which columns are shown in the output, and the

AT ns
A Query Formed from
order in which they will appear. If you specify more than one column name, you must use commas
the SELECT Command to separate the column names.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

How a Query Is
Processed
Figure 1-10: A query statement formed from the SQL SELECT command.
R
(C

It helps for students to Query Processing


FO

start thinking early on


about the order of query SQL was designed so that it would read somewhat like a sentence in English. As with English, there
processing. This will is a certain order in which you must type the various parts of an SQL statement.
prepare them to
understand complex
queries they encounter
later.

Lesson 1: Executing a Simple Query | Topic B


SQL Querying: Fundamentals (Second Edition) | 15

However, it is helpful to understand that the order in which you type the parts of an SQL statement
is not necessarily the order in which a database server processes them. For example, consider how
the simple SELECT statement shown in this figure is processed.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
Figure 1-11: How a query is processed by the database server.

E
PL rat
If you think about it, this order of operations is logical. The server begins with the full set of data in
DU pe
the table specified in the FROM part of the statement. It then reduces that dataset to only those items
TI

matching the WHERE part of the statement. Finally, it returns only the columns that were requested in
IC
the SELECT part of the statement.
lO
UA

Syntax
ica

The rules for how you are expected to put together an SQL statement are called the syntax. Syntax
is the expected form of a command, including its various parts (called clauses) and placeholders for
AL
og

actual elements that you use with the command. Syntax


T
7L
NO
EV
01
DO
)2
R
(C
FO

Figure 1-12: Syntax illustration.

Clauses used in a statement should all appear in the precise order specified in the syntax. For
example, the syntax of the SELECT command requires that you specify the columns you want to
retrieve first, and then the table from which you want to retrieve the information next. Some clauses
are required (such as SELECT and FROM), but other clauses (such as WHERE, GROUP BY, HAVING, and

Lesson 1: Executing a Simple Query | Topic B


16 | SQL Querying: Fundamentals (Second Edition)

ORDER BY) are optional. Choose which optional clauses to include based on the task you want the
statement to accomplish.

Guidelines for Constructing SQL Statements

LY
Note: All of the Guidelines for this lesson are available as checklists from the Checklist tile on
the CHOICE Course screen.
Guidelines for
Constructing SQL Following are guidelines for constructing SQL statements. Note that there are minor differences

ON
Statements among different implementations of SQL, some of which are configurable within the database. To
construct a standard SQL statement:
• Separate words in the statement as follows:
• Provide at least one space or line break between any two words.
• Enter extra spaces or line breaks if you like, and the statement will still execute correctly.

E
• Type SQL keywords in upper- or lowercase (although all caps is typical). For example, SELECT,
Select, and select are interpreted as the same command.

.
nc
US
• Type table, column, and index names that:
• Begin with a letter.

,I
• Limit length to 30 characters (up to 128 in SQL Server).
• Include no spaces. (Spaces are permitted in SQL Server.)

AT ns
• The capitalization of table and column names does not have to exactly match the capitalization
of those names in the database.
ON
io
• Enclose literal strings, text, and literal dates with single quotes (').

E
PL rat
Note: Depending on the SQL implementation you use and the configuration of the server
and database, the data values you provide in conditions may have to match case exactly to be
considered a match.
DU pe
TI

IC
Select All Columns
lO
UA

When you want to display all of the columns of a table in the output, you can provide an asterisk (*)
ica

instead of column names.


Select All Columns
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic B


SQL Querying: Fundamentals (Second Edition) | 17

LY
ON
E
.
nc
US
,I
AT ns
Figure 1-13: A SELECT clause to display all columns and records from the Titles table.
ON
io
Note: Do not use SELECT * indiscriminately, particularly if you are using SQL in production
code (in an application you are developing). SELECT * may return more data than you actually

E
PL rat
need, which could lead to unnecessary performance bottlenecks. If the column order changes in
the database itself, it will change the order in which results are returned by a SELECT * query.
DU pe
TI

Optional Clauses of the SELECT Statement


IC
lO
UA

SQL includes a number of optional clauses that you can use with the SELECT statement to further
identify the data you want to retrieve from a table. SQL requires that you include these optional
clauses in a specific order. The following table describes some of the optional clauses for the
ica

Optional Clauses of the


SELECT statement and their usage. SELECT Statement

Optional Clause Purpose


AL
og

WHERE A clause that enables you to request only certain rows from a table. For
T

example, you might use a WHERE clause when querying a customer table to
7L
NO

retrieve a list of only the customers who have a particular sales


representative.
EV
01

GROUP BY A clause that uses a column identifier to organize the data in the result set
DO

into groups.
)2

HAVING A clause that you use in conjunction with the GROUP BY clause in order to
specify which groups to include in the results.
R
(C

ORDER BY A clause that enables you to sort query results by one or more columns
and in ascending or descending order.
FO

Syntax Notation for the SQL SELECT Command


When you refer to SQL help and documentation, syntax notation will be represented as follows.

Syntax Notation

Lesson 1: Executing a Simple Query | Topic B


18 | SQL Querying: Fundamentals (Second Edition)

SELECT colname1[, colname2, colname3 ...]


FROM tablename
The syntax notation models the pattern for constructing a complete statement from a particular
command, such as SELECT. Parameters enclosed within square brackets are optional. You must
specify at least one column name in the SELECT statement or use the asterisk to request all columns

LY
in the table. Additional column names are optional.
Note: As a reminder, the commands and keywords in SQL are not case sensitive. As a
convention in this course, you'll find the keywords capitalized in syntax and examples to
differentiate them from object names.

ON
Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Query a Database.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic B


SQL Querying: Fundamentals (Second Edition) | 19

ACTIVITY 1-2
Querying a Database

LY
Before You Begin
You have launched SQL Server Management Studio and connected to the server. You have attached

ON
the Pub1 database to the server. You have started entering a query, beginning with the USE Pub1
statement to specify the database your SQL statements will apply to.

Scenario
The sales manager at Fuller & Ackerman Publishing would like to be able to give a list of all book Activity: Querying a

E
titles and prices to a newly hired sales representative. You have been asked to prepare this list. You Database
know that the information is contained in the Pub1 database but aren't familiar with the tables it

.
nc
US
contains. You will create a query to return the requested data.

,I
1. Identify the table that contains information about book titles published by

AT ns
Fuller & Ackerman Publishing.
a) In Microsoft SQL Server Management Studio, in the Object Explorer pane, make sure the
ON
io
Databases folder is expanded.
You can select the + button to the left of the Databases object to expand the outline at that point.

E
b) In the Databases folder, expand Pub1 and Tables. PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO

Tables in the Pub1 database are listed. Each table contains a set of information related to book
)2

customers, out-of-print (obsolete) book titles, sales, salespersons, current book titles, and so forth.
R
(C
FO

Lesson 1: Executing a Simple Query | Topic B


20 | SQL Querying: Fundamentals (Second Edition)

c) In the Databases folder, expand dbo.Titles and Columns to view the columns contained in the Titles
table.

LY
ON
d) Verify that the Columns folder contains the column bktitle (nvarchar(40), null).
Fuller & Ackerman stores the titles of its current books in this column.

2. Enter a query to display book titles, and run the query.

E
a) In the Query Editor pane, type a SELECT statement on two lines, as shown.

.
nc
US
,I
If students want to save
a little typing effort, point

AT ns
out that they can type
SQL commands and
names in lowercase, and
ON
io
SQL Server will still
recognize them.

E
b) Observe the color coding. PL rat
Keywords are displayed in blue. This can help you to spot typos as you enter commands. Keywords
you spell incorrectly will not be blue.
DU pe
TI

SQL code snippets for


the course activities are c) On the SQL Editor toolbar, select Execute or press F5 to execute the query.
IC
stored as snippets.sql in
d) In the Results pane, observe that the part number, book title, development cost, sale price, and
lO

the Solutions folder for


UA

publishing date are displayed for each book in the Titles table.
each lesson's course
data. You can use these
ica

to save yourself some


typing as you lead
students through the
AL

activities. Or you may


og

want to direct students


T

to these files if they are


7L

having trouble keeping


NO

up with the typing in


class.
EV
01
DO

Point out to students that


)2

using the asterisk in the


SELECT statement Since you specified *, all of the columns in the table are returned by the server.
R
(C

displays all columns in


the table. Providing no 3. Scroll down to view all of the returned rows.
WHERE clause displays
FO

all rows.

Lesson 1: Executing a Simple Query | Topic B


SQL Querying: Fundamentals (Second Edition) | 21

LY
ON
All rows in the table (92 in all) are shown.

4. Revise the SELECT statement to return just two columns.


a) In the Query Editor pane, select the asterisk in the SELECT statement and press Delete.
After you delete the asterisk, the insertion point is located where the asterisk had been, as shown.

E
.
nc
US
,I
AT ns
b) Type title
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og

• As you start typing, the editor's autocomplete feature provides a list of objects that are available
T

in this context.
7L
NO

• Since the Titles table is provided in the FROM clause, columns from the Titles table (and other
objects that would be appropriate in this context) are listed.
EV

• You can select items from this list to avoid typing and to ensure you spell object names correctly.
01

• The Titles table is highlighted in the list.


DO

c) Press Tab.
)2

• The highlighted object (Titles) is inserted into the query.


• Alternatively, you can double-click an item in the list to select it.
R
(C
FO

Lesson 1: Executing a Simple Query | Topic B


22 | SQL Querying: Fundamentals (Second Edition)

d) Type .

LY
ON
E
• When you type the dot, fields within the Titles table are listed.

.
nc
• The bktitle column is highlighted in the list.

US
Note: If you close the autocomplete list, you can reopen it by retyping the

,I
characters that trigger it to appear. If you have already completed an SQL
clause, you may have to delete a few characters and retype them to get it to

AT ns
reappear. ON
e) Press Tab or double-click bktitle.

io
The bktitle column name is added into the editor pane.

E
PL rat
f) Type directly or use the autocomplete feature to finish typing the SELECT statement as shown.
DU pe
TI

IC
lO
UA
ica

Execute the revised query.


AL

5.
og

a) Execute the query.


T
7L

Note: Press F5 or select the Execute button to execute the query. Note that if
NO

you have a portion of the query highlighted, SQL Server Management Studio
EV

will only execute the highlighted portion.


01

b) In the Results pane, observe that only the book title and sale price are displayed for each book in
DO

the Titles table.


)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic B


SQL Querying: Fundamentals (Second Edition) | 23

TOPIC C
Save a Query

LY
Sometimes SQL queries might be long, and even complex. After you have created and executed
them, you might want to reuse these SQL queries for other purposes. For this reason, Microsoft
SQL Server Management Studio enables you to save your queries in SQL script files. By saving your
queries, you can cut down on the amount of time required for inputting the query when you need to

ON
re-run a similar query.

SQL Script Files


SQL Server Management Studio offers you the ability to save the queries that you create. When you

E
save a query, SSMS saves the query in a script file with the extension .sql. The advantage to saving
queries is that doing so enables you to re-run queries simply by opening the saved script and

.
nc
selecting the Execute button.

US
SSMS provides a default name for queries when you save them. The default name is

,I
SQLQuery#.sql, where # is a unique number assigned by SSMS. You can replace this name with a
name of your choosing. Saving a query with a more meaningful name than the default name makes

AT ns
it easier for you to find the script file later. ON
io
Access the Checklist tile on your CHOICE Course screen for reference information and

E
job aids on How to Save a Query.
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic C


24 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 1-3
Saving a Query

LY
Before You Begin
You have launched SQL Server Management Studio and connected to the server. You have attached

ON
the Pub1 database to the server, and have entered a query to select the book title and sales price
columns of data from the Titles table.

Scenario
Activity: Saving a Query You have created a query to retrieve information about books from the Titles table. You then realize

E
that most of the people in the organization frequently request information that this query retrieves.
Instead of retyping this query each time someone requests a list of titles, it will be helpful if you save

.
nc
US
this query as an SQL file.

,I
1. Save the query and close the Query Editor window.

AT ns
a) On the Standard toolbar, select the Save button.
ON
io
E
PL rat
DU pe
TI

IC
lO

b) In the Save File As dialog box, navigate to the C:\094018Data\Executing a Simple Query folder.
UA

c) In the File name text box, change the file name to My Titles Query
d) In the Save as type drop-down list, verify that the SQL Files (*.sql) option is selected.
ica

e) Select the Save button to save the query.


f) Select File→Close to close the saved query.
AL
og

2. True or False? A saved query is automatically named after the database table
T

name being queried.


7L
NO

☐  True
☑  False
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic C


SQL Querying: Fundamentals (Second Edition) | 25

TOPIC D
Modify and Execute a Saved Query

LY
After you have saved a query, you may need to revise it. Modifying an existing query, especially if it
is long and complex, is faster than retyping the query. Thus, the ability to modify a saved query and
then execute it saves you time.

ON
Data Types

Data Types

E
.
nc
US
This is meant to be a
brief introduction to data

,I
types. Reassure
students they'll work with

AT ns
data types later in the
course.
ON
io
E
PL rat The Spotlight on SQL
Data Types presentation
is available from the
DU pe
TI

Spotlight tile on the


CHOICE Course screen.
IC
You may choose to
lO

include it in your
UA

instructional plans, or
you can remind students
ica

about the tile and the


supplemental
information it contains.
AL
og
T
7L
NO
EV

Figure 1-14: A table structure displaying various column types.


01
DO

When you create a table, you must specify the data type of each column. The data type is the
)2

classification of data into groups based on their characteristics, such as how many characters the
value can contain, and what type of value it contains (integer, decimal, text characters, and so forth).
The data type determines what calculations you can perform with that data.
R
(C

All values entered into an SQL database can be classified into one of the data types available in
Microsoft SQL Server 2017. The data type of the value entered into a column must match the data
FO

type the database administrator assigned to that column.


Note: To further explore data types, check out the Spotlight on SQL Data Types presentation
from the Spotlight tile on the CHOICE Course screen.

Lesson 1: Executing a Simple Query | Topic D


26 | SQL Querying: Fundamentals (Second Edition)

Data Types Available in SQL Server


Various data types supported on SQL Server are listed in the following table. Note that data types
differ among various SQL implementations, so refer to the documentation for the specific server
Data Types Available in
you are using to determine the supported data types.

LY
SQL Server
Data Type Used to Store

bigint The integer (whole numbers) data range from –2^63 (–


9,223,372,036,854,775,808) through 2^63 – 1 (9,223,372,036,854,775,807) with a

ON
storage size of 8 bytes.
int The integer (whole numbers) data range from –2^31 (–2,147,483,648) through
2^31 – 1 (2,147,483,647) with a storage size of 4 bytes.
smallint The integer data range from –2^15 (–32,768) through 2^15 – 1 (32,767) with a
storage size of 2 bytes.

E
tinyint The integer data range from 0 through 255 with a storage size of 1 byte.

.
nc
bit The integer data type that can take a value of 1, 0, or NULL.

US
decimal Fixed precision and scale numeric data from –10^38 + 1 through 10^38 – 1.

,I
numeric Functionally equivalent to a decimal.

AT ns
money The monetary data value range from –2^63 (–922,337,203,685,477.5808)
through 2^63 – 1 (+922,337,203,685,477.5807), with accuracy to a ten-
ON
thousandth of a monetary unit with a storage size of 8 bytes.

io
smallmoney The monetary data value range from –214,748.3648 through +214,748.3647,

E
PL rat
with accuracy to a ten-thousandth of a monetary unit with a storage size of 4
bytes.
DU pe
TI

float Floating precision number data with the following valid values: –1.79E + 308
through –2.23E – 308, 0 and 2.23E + 308 through 1.79E + 308.
IC
lO

real Floating precision number data with the following valid values: –3.40E + 38
UA

through –1.18E – 38, 0 and 1.18E – 38 through 3.40E + 38.


datetime Date and time data from January 1, 1753, through December 31, 9999, with an
ica

accuracy of three-hundredths of a second, or 3.33 milliseconds.


smalldatetime Date and time data from January 1, 1900, through June 6, 2079, with an accuracy
AL
og

of one minute.
T

char Fixed-length non-Unicode character data with a maximum storage size of 8,000
7L
NO

bytes.
varchar Variable-length non-Unicode data with a maximum storage size of 8,000 bytes.
EV
01

varchar(max) Variable-length non-Unicode data with a maximum storage size of 2^31 – 1


DO

bytes.
)2

nchar Fixed-length Unicode data with a maximum length of 4,000 characters.


nvarchar Variable-length Unicode data with a maximum length of 4,000 characters.
R
(C

sysname is a system-supplied user-defined data type that is functionally


equivalent to nvarchar (128) and is used to reference database object names.
FO

nvarchar(max) Variable-length Unicode data with a maximum length of 2^31 – 1 bytes.


binary Fixed-length binary data with a maximum length of 8,000 bytes.
varbinary Variable-length binary data with a maximum length of 8,000 bytes.
varbinary(max) Variable-length binary data with a maximum length of 2^31 – 1 bytes.

Lesson 1: Executing a Simple Query | Topic D


SQL Querying: Fundamentals (Second Edition) | 27

Data Type Used to Store


cursor A reference to a cursor.
sql_variant A data type that stores values of various SQL Server–supported data types,
except for text, ntext, timestamp, and sql_variant.

LY
table A special data type used to store a result set for later processing.
timestamp A database-wide unique number that gets updated every time a row gets
updated.

ON
uniqueidentifier A globally unique identifier (GUID).
xml A built-in data type that stores the XML documents and fragments in a SQL
Server database. The stored representation of the xml data type cannot exceed 2
GB.

E
Note: The text, ntext, and image data types were replaced by varchar(max), nvarchar(max), and

.
varbinary(max) in the SQL Server 2008 version.

nc
US
Stored Procedures

,I
A stored procedure is essentially an SQL script file that you save as a database object. The

AT ns
advantage to saving a query as a stored procedure is that SQL Server compiles stored procedures in
ON
advance. Compiling the stored procedure saves an execution plan as part of the stored procedure,

io
which makes the stored procedure run faster when you execute it.

E
PL rat
SQL Server 2017 includes many system-created stored procedures. These stored procedures are
installed by default when you install SQL Server. The system stored procedures have names that
begin with sp_ followed by a descriptive name. For example, the stored procedure sp_help followed If your students include
DU pe
TI

by a table name such as Titles enables you to view the structure of that table. Here's the syntax: web developers, point
IC
sp_help Titles out that using stored
procedures can help
lO
UA

prevent a significant type


Note: To further explore stored procedures, check out the Spotlight on System Stored
of web security
Procedures presentation from the Spotlight tile on the CHOICE Course screen. vulnerability called SQL
ica

injection.

Comments
AL
og

A comment is a word or statement, entered in the Query Editor window, that is not meant for The Spotlight on System
T

SQL Server to execute when it runs the query. You use comments to provide explanations about a Stored Procedures
7L

presentation is available
NO

query or to temporarily disable parts of an SQL statement. You indicate a single line comment by
from the Spotlight tile on
preceding it with two hyphens. Everything following the two hyphens is ignored in the remainder of
EV

the CHOICE Course


that line. You can specify multiple line comments by enclosing the lines within the /* and */ screen. You may choose
01

characters. to include it in your


DO

instructional plans, or
)2

you can remind students


about the tile and the
supplemental
R
(C

information it contains.
FO

Comments

Lesson 1: Executing a Simple Query | Topic D


28 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
AT ns
ON
io
Figure 1-15: Various types of comments in SQL.

E
PL rat
Access the Checklist tile on your CHOICE Course screen for reference information and
DU pe
TI

job aids on How to Work with Saved Queries.


IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic D


SQL Querying: Fundamentals (Second Edition) | 29

ACTIVITY 1-4
Modifying a Saved Query

LY
Before You Begin
You have entered a query to select all columns of data from the Titles table, and you have saved it as

ON
C:\094018Data\Executing a Simple Query\My Titles Query.sql.

Scenario
You created a query to produce a list of book titles and prices for the new sales representative. After Activity: Modifying a
retrieving the information, you realize that it might be helpful to provide a product ID or part Saved Query

E
number of some sort, as some books may have similar names.

.
nc
US
1. Display the structure of the Titles table.

,I
a) On the Standard toolbar, select the New Query button to open the editor pane.
b) From the Available Databases drop-down list, select Pub1.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

• Instead of typing the USE command, you can use this feature directly to specify the database
your SQL statements will apply to.
ica

• This is useful when you want to perform some quick tasks in a database and do not intend to
save the script.
AL

c) In the editor pane, type sp_help titles


og

d) Execute the query.


T
7L
NO

Briefly explain the


results of the query so
EV

that students understand


01

the structure of the Titles


DO

table.
)2
R
(C
FO

Structural information regarding the Titles table is shown.

Lesson 1: Executing a Simple Query | Topic D


30 | SQL Querying: Fundamentals (Second Edition)

2. Based on the scenario, which column should you add to your SELECT
statement?
A: The partnum field will provide the information you're looking for.

3. Close the editor pane without saving the sp_help query.

LY
a) Select File→Close.
b) When you're prompted to save the query, select No.

4. Open the My Titles Query.sql file.

ON
a) Select File→Open→File.
b) In the Open File dialog box, navigate to the C:\094018Data\Executing a Simple Query folder.
c) Select the My Titles Query.sql file and select Open to open the query file.

5. Modify the SELECT statement to display only the necessary columns and

E
verify the query works.

.
a) Position the insertion point immediately after the SELECT keyword, as shown.

nc
US
,I
AT ns
ON
io
b) Press Space, and type Titles.partnum,

E
The completed query is: PL rat
DU pe
TI

Remind students they


IC
can press Tab to select
the name from the
lO
UA

autocomplete list.
c) Execute the query.
d) Observe the results.
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C

92 rows are returned. The query results include the part number.
FO

6. Add a comment to the query.


a) Position the insertion point at the end of the USE Pub1 statement, and press Enter twice to add two
new lines.

Lesson 1: Executing a Simple Query | Topic D


SQL Querying: Fundamentals (Second Edition) | 31

b) Type two dashes to start a comment line, and finish typing the comment as shown.

LY
ON
c) Observe that the comment is shown in green in SQL Server Management Studio.

7. Save the modified query.


a) Select File→Save My Titles Query.sql As.

E
b) In the File name text box, change the file name to My Titles and Partnum Query and then select
Save to save the modified query as My Titles and Partnum Query.sql.

.
nc
US
If you omit the .sql file name extension, it is added automatically when you save the file.
c) Close the Query Editor window, but leave SQL Server Management Studio running.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic D


32 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 1-5
Executing a Saved Query

LY
Before You Begin
You have saved your modified query statement in C:\094018Data\Executing a Simple Query\My

ON
Titles and Partnum Query.sql.

Scenario
Activity: Executing a The sales manager wants an updated list of published book titles. You remember that you have
Saved Query saved the query to retrieve book titles along with their sale price and part number.

E
.
nc
Open the saved SQL file.

US
1.
a) Select File→Open→File.

,I
b) If necessary, in the Open File dialog box, navigate to the C:\094018Data\Executing a Simple Query
folder.

AT ns
c) Select the My Titles and Partnum Query.sql file and select Open to open the query file.
d) On the SQL Editor toolbar, from the Available Databases drop-down list, select Pub1.
ON
io
2. Execute the query.

E
a) Execute the query. PL rat
b) In the Results pane, observe that the part number along with the book title and sale price are
displayed.
DU pe
TI

c) Close the Query Editor window.


IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query | Topic D


SQL Querying: Fundamentals (Second Edition) | 33

Summary
In this lesson, you began working with SQL Server by connecting to a database and executing some
simple queries. By using the SELECT statement to retrieve information from tables, you can gather

LY
exactly the information that you need from practically any SQL database.

As an employee, how often might you connect to the database while working?
A: Answers will vary, but may include: there might be instances where you will retrieve information
Encourage students to

ON
regarding your day-to-day business tasks from the server and implement the same in your course of use the social
work. Therefore, it becomes important for you to access information from the database. To do so, you networking tools
should initially connect to the database. Therefore, every time you require information from the server, provided on the CHOICE
you will connect to the database. Course screen to follow
up with their peers after
Which SQL Server command group would you use the most in your current job? the course is completed
Why? for further discussion

E
and resources to support
A: Answers will vary, but may include: Data Manipulation Language (DML) is the SQL command group

.
continued learning.

nc
you'll use most often because it's the language for retrieving information from the database. In a

US
database, you might update data quite often according to the requirements. DML enables you to
insert, update, or delete information from the database.

,I
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,

AT ns
peers, and the larger CHOICE online community about the topics covered in this course or
other topics you are interested in. From the Course screen you can also access available
ON
io
resources for a more continuous learning experience.

E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 1: Executing a Simple Query |


FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
2 Performing a Conditional

LY
Search

ON
Lesson Time: 1 hour, 45 minutes

E
.
nc
US
Lesson Introduction

,I
AT ns
At this point, you have connected to a server, written a simple query and executed it, and
saved that query to a file. With simple queries, you typically retrieve all the information in a
ON
table. In a production environment, however, you rarely need to view all the information in

io
a table. Instead, you want to retrieve only the rows in a table that meet certain criteria. In
this lesson, you will add criteria to your SELECT statements so that you can perform more

E
sophisticated queries. PL rat
DU pe
TI

Lesson Objectives
IC
lO

In this lesson, you will:


UA

• Use one or more simple search conditions to retrieve the desired output.
ica

• Retrieve records based on a range of values and NULL values.


• Search for patterns in a table.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
36 | SQL Querying: Fundamentals (Second Edition)

TOPIC A
Search Using One or More Conditions

LY
The most basic of conditional searches use one or more criteria to query a table. In this topic, you
will use one or more search conditions to retrieve rows from tables.
Conditional searches enable you to limit the number of rows returned by a SELECT statement. The

ON
benefit to limiting the number of rows in a query's output is that you reduce the amount of work the
SQL Server must perform to return a query's results. Reducing the amount of work for the server
helps to improve its performance.

Conditions

E
Most production tables consist of hundreds or even thousands of records or more. Executing a

.
query that retrieves all columns and all rows from such large tables can severely affect the

nc
US
Single Search Condition
performance of a server. In an environment with large tables, you can improve the performance of
your queries and avoid negatively affecting a server's performance by including conditional search

,I
criteria in your SELECT queries.
A condition is a search criterion you use in a SELECT statement to retrieve or manipulate specific

AT ns
information. You can include more than one search criterion in a SELECT statement so that you can
retrieve the exact information you need. You use search criteria to compare information in a column
ON
io
to a specific value. You can also perform calculations on numeric columns before comparing
information.

E
PL rat
In the figure, you see a SELECT statement that queries the Sales table in the Pub1 database. The
SELECT statement retrieves the ordnum (order number), sldate (sales date), qty (quantity), partnum
(part number), and repid (sales representative ID) for all orders in which the repid column contains
DU pe
TI

the value NO2. Thus, this SELECT statement enables you to see all the orders generated by sales
IC
representative NO2.
lO
UA
ica
AL
og
T
7L
NO
EV

Figure 2-1: A SELECT statement displaying a single search condition.


01
DO

The Conditional Search Process


)2

SQL Server uses a conditional search to retrieve only selected records (or rows) from a table. To
R
(C

process a conditional search:


The Conditional Search 1. You enter the SELECT statement along with a condition in the Query Editor window. To
FO

Process perform a conditional search, you must include a WHERE clause as part of the SELECT statement.
2. SQL Server searches the table using the condition present in the WHERE clause.
3. SQL Server returns the rows that match the condition in the WHERE clause.
4. The server displays the retrieved rows in the Results pane of the Query Editor window.

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 37

LY
Figure 2-2: Steps involved in a conditional search.

The WHERE Clause

ON
The WHERE clause is a clause you use to specify a search condition in an SQL statement. The
WHERE clause contains an expression or column name followed by an operator, and then an
expression or value that SQL Server needs to compare with one or more columns in the table. You The WHERE Clause:
can include more than one condition in the WHERE clause. Example 1
The syntax of the WHERE clause used in the SELECT statement is:

E
SELECT colname1[, colname2, colname3 ...]

.
FROM tablename

nc
US
WHERE condition
In the figure, the WHERE clause includes a single condition. The condition specifies that SQL Server

,I
should return only those rows in the Titles table in which the slprice column has a value greater than
100.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

Figure 2-3: A SELECT statement containing a single condition.


ica

This next figure shows a SELECT statement in which the WHERE clause has two conditions. Because
these two conditions are separated by the AND operator, both conditions must be true in order for
AL
og

SQL Server to display a row in the output. In other words, SQL Server includes a row in the output Point out to students that
only when the column repid contains the value N02 and the column qty is greater than or equal to they might use a query
T

400. like the one shown in


7L
NO

this figure to find all big


sales (sales with a
EV

quantity ordered of
01

greater than or equal to


400) sold by the sales
DO

representative assigned
)2

the ID of N02.
R
(C

The WHERE Clause:


FO

Example 2

Figure 2-4: A SELECT statement displaying multiple conditions.

Lesson 2: Performing a Conditional Search | Topic A


38 | SQL Querying: Fundamentals (Second Edition)

Operators
Operators are symbols or words used in expressions that manipulate values or make comparisons.
They are mostly used between a word and a value in a search condition for a WHERE clause. You can
Multiple Conditional
use operators to perform calculations, compare values, and match patterns. In the following figure,

LY
Operators the WHERE clause contains two conditions: slprice > 40 and partnum > 1000. This query returns all
books where the sale price is greater than $40 and the part number is greater than 1000.

ON
E
Figure 2-5: A SELECT statement displaying multiple conditional operators.

.
nc
US
As another example, the following figure displays a SELECT statement in which the WHERE clause
searches for all books with a sale price greater than or equal to 30. SQL Server thus searches

,I
Single Conditional
through the Titles table and returns only those rows in which the sale price is greater than or equal
to 30.

AT ns
Operator ON
io
E
PL rat
DU pe
TI

IC
lO
UA

Figure 2-6: A SELECT statement displaying operators used in a WHERE clause.

Operators Used in SQL


ica

There are eight key categories of operators used in Microsoft® SQL Server® 2017.
AL
og

Operator Description
T

Arithmetic operators Perform mathematical operations on two expressions of numeric


7L

data.
NO

Assignment operators Establish the relationship between a column heading and the
EV

expression that defines values for the column.


01
DO

Compound operators Perform mathematical operations on two numeric expressions by


combining one operator with another.
)2

Bitwise operators Perform bit manipulations between two expressions of the integer
R

data type.
(C

Comparison operators Test whether two expressions are the same, greater than, or less
FO

than.
Logical operators Test for the truth of a condition. Return a Boolean data type with a
value of TRUE or FALSE.
String concatenation Allow string concatenation.
operators

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 39

Operator Description
Unary operators Perform an operation on only one expression of any of the data
types of the numeric data type category.

LY
Comparison Operators
Comparison operators are symbols you use in a WHERE clause to compare two expressions or
values.

ON
In SQL Server, you use comparison operators in conditions as part of a WHERE clause. You cannot Comparison Operators
use comparison operators with columns that use the text, ntext, or image data types.
The output of a comparison operator is one of three values: TRUE, FALSE, or UNKNOWN.
• If the output of a comparison operator is TRUE, SQL Server displays the row in the results of a
query.

E
• If the output is FALSE, SQL Server does not display the row in the query results. How NULL and

.
• If the output is UNKNOWN, the results may vary. This may occur, for example, in some WHERE UNKNOWN are dealt

nc
US
with in comparisons is
conditions involving NULL values. covered later in this
topic.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 2-7: A SELECT statement displaying the comparison operator.


IC
lO

Comparison Operators and Their Descriptions


UA

There are nine comparison operators used in SQL Server 2017.


ica

Comparison Operator Description

= Equal to
AL
og

> Greater than


T
7L

< Less than


NO

>= Greater than or equal to


EV
01

<= Less than or equal to


DO

<> Not equal to


)2

!= Not equal to (not SQL-92 standard)


R
(C

!< Not less than (not SQL-92 standard)


!> Not greater than (not SQL-92 standard)
FO

Arithmetic Operators
Arithmetic operators are symbols used to perform mathematical operations on numeric
expressions. You can also use the plus (+) and minus (-) operators to perform arithmetic operations
Arithmetic Operators

Lesson 2: Performing a Conditional Search | Topic A


40 | SQL Querying: Fundamentals (Second Edition)

on datetime and smalldatetime values. In the following figure, you see a SELECT statement that uses
the plus operator to add 20 dollars to the sale price of books; you might use such a statement if your
organization planned to increase the cost of books by a certain dollar amount. The WHERE clause
then restricts the output to only those books where the sale price plus 20 dollars is greater than 50
dollars.

LY
ON
E
.
nc
US
,I
Figure 2-8: A SELECT statement displaying an arithmetic operator.

AT ns
Arithmetic Operators Used in SQL
ON
There are five arithmetic operators used in SQL.

io
E
Arithmetic Operator Description

+ Addition
PL rat
DU pe
TI

- Subtraction
IC
* Multiplication
lO
UA

/ Division
% Returns the integer remainder of a division
ica

Column Aliasing
AL
og
T

A column alias is a name you assign for SQL Server to use as a column heading in the output. You
7L

can assign a column alias to any column in a table and SQL Server will display the alias in place of
NO

Column Aliasing
the default column heading in the result set. Using an alias enables you to provide more descriptive
EV

headings for the columns in a table. The alias can contain any alphanumeric characters along with a
01

few special characters, such as $ or #. If you want the alias to contain a space, period, or
exclamation point, you must enclose it in single or double quotes.
DO
)2

By default, SQL Server displays the column name in the heading of the result set for a SELECT
statement. If the column does not have a column name because it is the result of a calculation, SQL
Server displays the heading "No column name." You make the output of a query more meaningful
R
(C

when you provide a column alias for any calculations in the SELECT statement.
FO

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 41

LY
ON
E
.
Figure 2-9: A table displaying the column alias.

nc
US
Alternative Ways to Define an Alias

,I
The syntax for defining an alias provides for some variations, as shown in the following figure.

AT ns
ON Alternative Ways to

io
Define an Alias

E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Figure 2-10: Alternative syntax for defining an alias.


R
(C

Logical Operators
FO

Logical operators are operators that test the truth of a condition. Logical operators, like
comparison operators, return a value of either TRUE or FALSE. You may use multiple logical
operators in a WHERE clause to test for more than one condition. For each row, the condition or Logical Operators
combination of conditions in the clause is evaluated. If the result returns TRUE, then that row is
returned by the database when the query is evaluated.

Lesson 2: Performing a Conditional Search | Topic A


42 | SQL Querying: Fundamentals (Second Edition)

Logical Operator Description

ALL TRUE if all of a set of comparisons are TRUE.


AND TRUE if both Boolean expressions are TRUE.

LY
ANY TRUE if any one of a set of comparisons is TRUE.
BETWEEN TRUE if the operand is within a range.
EXISTS TRUE if a subquery contains any rows.

ON
IN TRUE if the operand is equal to one of a list of expressions.
LIKE TRUE if the operand matches a pattern.
OR TRUE if either Boolean expression is TRUE.
SOME TRUE if some of a set of comparisons are TRUE.

E
NOT Inverts the logical value returned by the other operators.

.
nc
US
This list of SQL Server logical operators is typical. Refer to your database's documentation for a
specific list of supported logical operators.

,I
Note: Boolean is a type of expression with two possible values, "true" and "false."

AT ns
ON
io
The AND, OR, and NOT Operators

E
PL rat
The AND, OR, and NOT operators are the most commonly used logical operators. The AND and
OR operators are used to combine the result of two or more Boolean expressions. The AND operator
DU pe
TI

returns TRUE when both expressions are TRUE, while the OR operator returns TRUE when either
of the expressions is TRUE. The NOT operator is used to negate a Boolean expression.
IC
lO

Note: Spaces are necessary between words, but optional where there is a symbol, such as a
UA

comparison or arithmetic operator.


ica

Syntax of Commonly Used Logical Operators


boolean_expression1 AND boolean_expression2
AL
og

boolean_expression1 OR boolean_expression2
T

[ NOT ] boolean_expression
7L
NO

OR Example
EV
01

This figure shows a WHERE clause with two search conditions separated by the OR operator. For this
DO

example, SQL Server will return all rows in the Customers table in which the value in the state
)2

The OR Operator
column is either Massachusetts or California.
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 43

LY
ON
Figure 2-11: Using the OR operator in SQL querying.

E
AND Example

.
nc
US
In the following figure, the WHERE clause consists of multiple search conditions. The AND logical
operator connects the two search conditions, and both the conditions must be true in order for SQL

,I
Server to include a row in the output of a query. In this example, for SQL Server to include a row in The AND Operator
the output, the customer must live in the state of Texas and the city of Houston.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica

Figure 2-12: Using the AND operator in SQL querying.


AL
og

NOT Example
T
7L
NO

This figure shows you an example of the NOT logical operator. In this example, SQL Server will
EV

return all rows in the Customers table in which the city column does not contain the value
01

Ryebrook. In other words, this query gives you a list of all customers who don't live in the city of The NOT Operator
DO

Ryebrook.
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


44 | SQL Querying: Fundamentals (Second Edition)

LY
ON
Figure 2-13: Using NOT operators in SQL.

AND and NOT Combined Example


In this example, the WHERE clause consists of two conditions separated by the AND NOT operators.

E
This syntax enables SQL Server to retrieve all rows in the Customers table where the customers live

.
in New York but not the city of Ryebrook.

nc
The AND and NOT

US
Operators in
Combination

,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 2-14: Using AND and NOT operators in SQL.


IC
lO

Operator Precedence
UA

When you provide multiple conditions in a complex WHERE clause, you might assume that they are
ica

performed from left to right, in the order in which there were typed. However, the operators you
Operator Precedence
use to chain these various conditions together may have different precedence levels, which
determine the order in which SQL Server executes them. You can use parentheses to override the
AL
og

order in which SQL Server executes operators.


T

If two operators in an expression have the same operator precedence level, they are evaluated left to
7L

right based on their position in the expression.


NO

Operators are listed here in their order of precedence. Items at the top are performed first.
EV
01

Operator Level Operator Precedence in Each Level


Point out that students
DO

have not used all of 1 + (Positive), - (Negative), ~ (Bitwise NOT)


)2

these operators yet, but


they are included in this 2 * (Multiply), / (Division), % (Modulo)
R

list for completeness.


(C

3 + (Add), + (Concatenate), - (Subtract)


4 =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
FO

5 ^ (Bitwise Exclusive OR), & (Bitwise AND), | (Bitwise OR)


6 NOT
7 AND

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 45

Operator Level Operator Precedence in Each Level

8 ALL, ANY, BETWEEN, IN, LIKE, OR, SOME


9 = (Assignment)

LY
Parentheses
You can provide parentheses to override the normal operator precedence, as shown in these
examples.

ON
In the top example, since AND has precedence over OR, the AND operation is performed first—even Parentheses
though it appears after the OR within the statement.
In the bottom example, the normal order is overridden by parentheses. The OR operation within the
parentheses is performed before the AND operation.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV

Figure 2-15: Parentheses override the normal order of operations.


01
DO

Comparisons Involving NULL


)2

NULL means that a value is unknown. NULL provides a way for the user to represent that the data
R

value is unknown, not applicable, or intended to be added later. NULL can be useful for
(C

representing unknown values, but it can make comparisons a bit awkward because NULL values are Comparisons Involving
unknown and therefore can't really be compared. NULL
FO

In the default configuration for SQL Server, when a value in a comparison operation is NULL, it is
treated differently from an empty or zero value. It is important to understand how NULL values are
dealt with in comparison operations so your queries produce the results you intend to produce.

Lesson 2: Performing a Conditional Search | Topic A


46 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
AT ns
ON
Figure 2-16: A comparison involving a NULL value.

io
E
Consider the query shown in the previous figure as an example of how comparison operators
PL rat
function when a NULL value is involved. In this example, suppose the Titles table contains a row
with an slprice value of 40 and a devcost value of NULL. Because of the NULL value in devcost,
DU pe
TI

this row will not be returned in the query result, even though the value of slprice is more than 35.
IC
The first expression in the WHERE clause (slprice > 35) returns TRUE. The second expression
lO

(devcost > 15000) returns NULL.


UA

The following table shows the results for various combinations of expressions and operations.
ica

Expression 1 Expression 2 Result of AND Result of OR Operation


Operation
AL
og

TRUE NULL FALSE TRUE


T

NULL NULL FALSE UNKNOWN


7L
NO

FALSE NULL FALSE UNKNOWN


EV

In the table, you can see that an AND operation performed on TRUE and NULL returns FALSE.
01

Only rows in which the WHERE clause evaluates as TRUE are included in the result.
DO
)2

Access the Checklist tile on your CHOICE Course screen for reference information and
R

job aids on How to Search Using One or More Conditions.


(C
FO

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 47

ACTIVITY 2-1
Searching Using a Simple Condition

LY
Scenario
The sales department has asked you to provide the sales representatives with a list of all books with

ON
a price of $50 or more. They have also noticed an increase in demand for books on sailing. For this
reason, the sales department has also asked you to confirm that a book named "Sailing" is available.

1. Launch SQL Server Management Studio, open a new query editor, and select Activity: Searching Using

E
the Pub1 database. a Simple Condition

.
a) If SQL Server Management Studio is not running, launch it and connect to the server.

nc
US
b) On the Standard toolbar, select New Query to open the Query Editor window.
c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub1 SQL code snippets for

,I
database is selected. the course activities are
stored as snippets.sql in

AT ns
the Solutions folder for
2. List books for which the sale price is greater than or equal to $50. each lesson's course
a) In the editor pane, press Enter to skip a line and enter the FROM clause as shown.
ON data. You can use these

io
to save yourself some
typing as you lead

E
PL rat students through the
activities. Or you may
want to direct students
DU pe
TI

to these files if they are


having trouble keeping
IC
up with the typing in
lO

• By typing the FROM clause first, you provide a clue to inform SQL Server Management Studio class.
UA

which table you're querying.


• This enables the autocomplete feature to display suggested column names that you type in
ica

clauses such as SELECT.


b) Move the insertion point to the first line. Type SELECT pa
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

The partnum column is selected.

Lesson 2: Performing a Conditional Search | Topic A


48 | SQL Querying: Fundamentals (Second Edition)

c) Press Tab.
The partnum column name is inserted.
d) Finish the SELECT clause, and enter the WHERE clause as shown.

LY
Point out that spaces
around the >= operator
are optional.

ON
e) Observe the column names you entered in the SELECT and WHERE clauses.
• It is not necessary to specify the table with each field (fully qualified names such as
Titles.partnum, Titles.bktitle, and so forth) because the query refers only to the Titles table.
• When you create more complex queries that use multiple tables, you'll need to use fully qualified
names.

E
f) Press F5 or select the Execute button to execute the query.

.
g) In the Results pane, observe the book titles for which the sale price is greater than or equal to $50.

nc
US
,I
AT ns
ON
io
E
Three books are returned. PL rat
DU pe
TI

3. List the details of the book that has "Sailing" as the book title.
IC
a) Revise the last line of your query as shown.
lO
UA

Mention to students that


ica

they will learn how to


return multiple rows with
pattern matching later in
AL
og

this lesson.
T

b) Execute the query.


7L
NO

c) In the Results pane, observe that a book with the title "Sailing" is displayed.
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 49

ACTIVITY 2-2
Comparing Calculated Column Values

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Your boss has come up with an idea to promote the sales of the company by offering discounts for Activity: Comparing
certain books. The plan is to provide 7% off on all books for which the sale price is greater than $45 Calculated Column

E
after the discount. You need to identify the book titles that will be included in the discount sale. Values

.
nc
US
1. Display the normal prices of all books.

,I
a) In the editor pane, delete the WHERE clause.

AT ns
ON
io
E
PL rat
b) Execute the query.
DU pe
TI

c) In the Results pane, observe that books are shown with their normal prices.
IC
lO
UA
ica
AL
og
T
7L
NO
EV
01

2. Display all books with a discounted price.


DO

a) In the editor pane, add the text as shown.


)2
R
(C
FO

This revises the third column to show a calculated value.


b) Execute the query.

Lesson 2: Performing a Conditional Search | Topic A


50 | SQL Querying: Fundamentals (Second Edition)

c) In the Results pane, observe that books are now shown with discounted prices.

LY
ON
The third column no longer shows the normal sale price, but rather a calculated value, so no label is
shown for the column.

E
3. Provide the calculated column with an alias.

.
nc
a) In the editor pane, add the text as shown.

US
,I
AT ns
ON
io
This gives the calculated column an alias.

E
b) Execute the query. PL rat
c) In the Results pane, observe that the discounted prices now have a column name.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L

Show only books whose discounted price is at least $45.


NO

4.
a) In the editor pane, add the WHERE clause as shown.
EV
01
DO
)2
R
(C
FO

This limits the results to books with a sale price more than $45 after the discount.
b) Execute the query.

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 51

c) In the Results pane, observe the books with discounted prices greater than $45.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


52 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 2-3
Searching for Rows Using Multiple Conditions

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Activity: Searching for The sales manager has information about a book exhibition that is to be held in Ryebrook, New
Rows Using Multiple York. He wants a list of customers in New York and the customers in the city of Ryebrook so that

E
Conditions he can notify them of Fuller & Ackerman Publishing's participation in the book exhibition. The
sales manager wants to run a promotional sale in New York and Massachusetts. He wants the sales

.
nc
US
representative with ID S01 to be in charge of the sale, and to contact the customers in those states.

,I
1. List all customers who are from the state of New York.

AT ns
a) Open a new Query Editor window, but do not close the existing window.
b) In the new Query Editor window, enter the statement in the editor pane as shown.
ON
io
You will return to the

E
Titles query later. PL rat
DU pe
TI

Point out that 'NY' can


IC
be typed in upper- or
lO

lowercase since the


UA

database is not c) Execute the query.


configured for case- d) In the Results pane, observe that SQL Server displays a list containing six customers from New
ica

sensitive searches. York State.


AL
og
T
7L
NO
EV
01
DO
)2
R
(C

2. List all customers who live in either the state of Massachusetts or New York.
FO

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 53

a) Revise the WHERE clause as shown.

LY
b) Execute the query.

ON
c) In the Results pane, observe that SQL Server lists a total of seven customers from the states of New
York and Massachusetts.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
Adding an OR condition increased the number of matches from 6 to 7.

3. Attempt to list customers whose sales representative ID is S01 and who are
DU pe
TI

either from Massachusetts or from New York.


IC
a) Edit your query to read:
lO
UA
ica

Point out to students that


the representative ID
S01 is "ess zero one."
AL
og
T
7L

b) Execute the query.


NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


54 | SQL Querying: Fundamentals (Second Edition)

c) In the Results pane, observe that a list of seven customers from Massachusetts or New York are
displayed.

LY
ON
E
d) Consider how the query produced these results.

.
nc
US
,I
AT ns
ON
io
E
PL rat
• AND operations take precedence over OR operations.
DU pe
TI

• As written, the WHERE clause produces two groups of results. The first group is those where
IC
state = 'NY'. The second group is those where state = 'MA' AND repid = 'S01'.
lO

• To apply the repid = 'S01' condition to both states, you need to enclose the OR operation
UA

within parentheses so it is performed before AND.


ica

4. Revise the query so the OR operation is performed before AND.


a) Add parentheses in the WHERE clause as shown.
AL
og
T
7L
NO
EV
01
DO
)2

First the list of all customers will be reduced to those in NY or MA. Then the list will be further
reduced to those where the repid is S01.
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


SQL Querying: Fundamentals (Second Edition) | 55

b) Execute the query, and observe the results.

LY
ON
A list of four customers who are either from the state of Massachusetts or New York is displayed. All
have a repid of S01.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic A


56 | SQL Querying: Fundamentals (Second Edition)

TOPIC B
Search for a Range of Values and NULL Values

LY
You have retrieved records from a table based on conditions. There are times when you may need
to retrieve information from a database based on a specified range of values. In this topic, you will
search for records based on a range of values.

ON
The BETWEEN...AND Operator
The output of a query depends on the condition you use to retrieve information. If there is a table
that contains a list of book titles and their prices, and you need only the list of books whose price
The BETWEEN...AND
range is between $40 and $50, then instead of using two conditions, you can use an operator to

E
Operator retrieve the records that fall in that range.

.
The BETWEEN...AND operator is a logical operator that searches for rows where one or more

nc
US
columns contain a value within a range of values. You specify the start value of the range after the
BETWEEN keyword and the end value after the AND keyword in the WHERE clause of an SQL

,I
statement. You can use the logical operator NOT to retrieve records that fall outside a specified range.
In the following figure, the WHERE clause specifies that SQL Server should retrieve all rows in the

AT ns
Titles table where the slprice column is less than $50 or greater than $55.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R

Figure 2-17: Using the BETWEEN.. AND operator in SQL.


(C

The BETWEEN...AND operator is the equivalent of using >= and <= operators to frame a condition.
FO

Using the BETWEEN...AND operator rather than the mathematical symbols makes it easier to read
and understand the SQL statement.

Syntax of the BETWEEN...AND Operator


The syntax of the BETWEEN...AND operator is:

Lesson 2: Performing a Conditional Search | Topic B


SQL Querying: Fundamentals (Second Edition) | 57

expression1 [ NOT ] BETWEEN expression2 AND expression3

The IN Operator
The IN operator is a logical operator that checks whether a column value or expression matches a

LY
list of values. You use the IN operator in a WHERE clause between the column name and the list of
values to be matched. You specify the list of values within parentheses, separated by commas. If you The IN Operator
use text in the list of values, you must enclose it within single quotes. The data type of values in the
list must match the data type of the column or expression.

ON
In the following figure, the WHERE clause uses the IN operator followed by a list of values in
parentheses. In this example, SQL Server retrieves all rows in which the state value is California,
New York, or Massachusetts.

E
.
nc
US
,I
AT ns
ON
io
E
Figure 2-18: Use of the IN operator in SQL.
PL rat
DU pe
TI

Syntax of the IN Operator


IC
The syntax of the IN operator is:
lO
UA

expression [ NOT ] IN
( expression [ value1, value2, ...] )
ica

The NULL Value


AL
og

NULL is a value that SQL Server stores in a column when the value of the column is either
unknown or undefined. When you view table information, SQL Server displays the word "NULL"
T

in the columns that contain the NULL value. NULL is not the same as zero, blank, or a zero-length
7L

The NULL Value


NO

character string. If you attempt to compare NULL values, they will not be equal because the value
of each NULL is unknown.
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic B


58 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
Figure 2-19: Using a NULL value in a table.

,I
The IS NULL Clause

AT ns
The IS NULL clause is a clause that tests for the NULL value in a column. You can use the IS
NULL
ON
clause in a WHERE clause after the expression or column name you want to check for NULL

io
The IS NULL Clause
values. You can use the NOT operator between the IS and NULL keywords to check for values in a
column that are not NULL.

E
PL rat
In the following figure, you see an example of using the IS NULL clause as part of a WHERE clause in
a query. In this example, SQL Server returns those books that have a sale price between $35 and $45
DU pe
TI

and a development cost that is unknown.


IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R

Figure 2-20: Use of the IS NULL clause.


(C

The following figure provides you with an example of how to use the IS NOT NULL clause. In this
FO

example, SQL Server returns all books that have a sales price between $35 and $45 and have a
The IS NOT NULL
defined development cost.
Clause

Lesson 2: Performing a Conditional Search | Topic B


SQL Querying: Fundamentals (Second Edition) | 59

LY
ON
E
Figure 2-21: Use of the IS NOT NULL clause.

.
nc
US
Syntax for the IS NULL Clause
The syntax for the IS NULL clause is:

,I
expression

AT ns
expression IS [NOT] NULL ON
io
Access the Checklist tile on your CHOICE Course screen for reference information and

E
PL rat
job aids on How to Search for a Range of Values and NULL Values.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic B


60 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 2-4
Searching for a Range of Values and NULL

LY
Values

ON
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database
is selected.

Scenario

E
Activity: Searching for a The manager of the sales department plans to provide discounts to customers for books that are
Range of Values and priced between $35 and $70. He has asked you to generate a list of these books. In addition, he

.
nc
NULL Values would like you to provide him with a list of all books that do not have a defined development cost.

US
Finally, the sales manager has asked you to provide a list of books that have a defined development
cost so that he can analyze the profitability of each book.

,I
AT ns
1. Generate a list of all titles with a sale price between $35 and $70.
ON
a) Switch to the query tab with the Titles query and modify the SELECT and WHERE clauses as shown

io
here:

E
PL rat
DU pe
TI

IC
lO
UA
ica

Note: If you closed the editor containing the Titles query, enter this query on a
new query tab, making sure you select the Pub1 database.
AL
og

b) Execute the query.


c) In the Results pane, observe that a list of 38 book titles with a sale price between $35 and $70 is
T

displayed.
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic B


SQL Querying: Fundamentals (Second Edition) | 61

d) Scroll down to view all rows, and observe that the BETWEEN...AND operator includes the values at
the start and end of the range.
For example, books selling for exactly $35 are included in the list.

LY
ON
E
.
nc
US
,I
2. List the titles that do not have the development cost recorded.
a) Edit the query so that it reads as follows:

AT ns
ON
io
E
PL rat
DU pe
TI

IC
• Add the devcost column to the output.
lO

• Change the WHERE clause to show those books for which no devcost value has been entered.
UA

b) Execute the query.


c) In the Results pane, observe that the list includes five book titles whose development cost is not
ica

defined.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C

3. Modify the query to list titles that have a numerical development cost.
FO

Lesson 2: Performing a Conditional Search | Topic B


62 | SQL Querying: Fundamentals (Second Edition)

a) Edit the query to retrieve all rows that have a value in the devcost column:

LY
b) Execute the query.

ON
c) In the Results pane, observe that a list of 87 titles that have a numerical development cost is
displayed.
The list contains no books with a NULL devcost value.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic B


SQL Querying: Fundamentals (Second Edition) | 63

TOPIC C
Search Data Based on String Patterns

LY
Other types of search conditions you might use when querying a table include pattern matching and
wildcard characters. Search conditions using pattern matching and wildcard characters enable you to
perform searches, such as all titles that contain the word "sailing" in them or all customers whose
last names begin with "C." In this topic, you will use pattern matching and wildcard characters in

ON
search conditions.

Wildcard Characters
Sometimes you won't want to search tables using exact matches. Perhaps you want to see a list of

E
customers whose ZIP Codes begin with "151" and end in any two numbers. Or you might want to
retrieve all books that begin with the letter "T." Pattern matching by using a combination of letters

.
Wildcards

nc
or numbers and wildcard characters provides you with greater flexibility when querying a table.

US
A wildcard character is a special character you can use in a search condition to represent certain

,I
characters. You can insert it anywhere within a search pattern to locate column values in records
that contain a known sequence of characters without having to enter the entire string of characters,

AT ns
or when the entire set of characters is not known. There are four wildcard characters in SQL. Some
of them substitute for a single character, while others substitute for an unlimited number of
ON
characters. You can use more than one wildcard character in an expression.

io
The following figure provides you with an example of a search condition in which a wildcard is

E
PL rat
used. In this example, the percent (%) wildcard is used to represent any number of characters. This
query therefore returns all books with titles that begin with the letter "C."
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO

Figure 2-22: Wildcard in SQL querying.


EV
01

SQL Server supports four wildcard characters for matching patterns as part of a WHERE clause in an
DO

SQL statement.
)2

Wildcard Meaning
R

% Any string of zero or more characters.


(C

_ Any single character.


FO

[] Any single character within the specified range.


[^] Any single character not within the specified range.

Lesson 2: Performing a Conditional Search | Topic C


64 | SQL Querying: Fundamentals (Second Edition)

Pattern Matching
Pattern matching is a method of searching for column values in a table with the help of patterns
known to contain a specific combination of text or numeric characters. You can use a pattern to
Pattern Matching
search for a single character or a combination of characters, and can include one or more wildcard

LY
characters. Pattern matching tests whether the specified pattern exists anywhere within the value in
the specified column. Pattern matching uses the LIKE operator followed by the pattern enclosed
within single quotes. Characters used in the pattern are not case sensitive.

ON
E
.
nc
Figure 2-23: Pattern matching in SQL.

US
In this example, the WHERE clause uses a search condition in which several characters are enclosed

,I
within the percent signs ('%art%'). This query returns all books with titles that contain the letters
"art" anywhere in the title. In other words, this query would return a book with the title Art Classics

AT ns
and also a book with the title of Smart Cooking.
ON
You may need to combine different wildcards to obtain the results you need. In the following figure,

io
you see a SELECT statement that searches for all customers who have an "o" as the second character
in the their name. The underscore character (_) is the wildcard for a single character, and the percent

E
Multiple Wildcards
PL rat
character (%) is the wildcard for any number of characters. With this example, a match would be
found whether the customer name is "Colleen's Craft Supplies" or the more unusual "Kolleen's
DU pe
Kraft Supplies."
TI

IC
lO
UA
ica
AL
og
T
7L
NO

Figure 2-24: Wildcard used in the Titles table.


EV
01

Syntax of the LIKE Operator


DO

The syntax of the LIKE operator is:


)2

expression [ NOT ] LIKE 'pattern'


The pattern should be enclosed within single quotes.
R
(C
FO

Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Retrieve Data Based on String Patterns.

Lesson 2: Performing a Conditional Search | Topic C


SQL Querying: Fundamentals (Second Edition) | 65

ACTIVITY 2-5
Retrieving Data Based on String Patterns

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
A customer has told a salesperson that he wants a list of all books that have information about art. Activity: Retrieving Data
After selecting the first book from the list of book titles, the customer wants to select a second book Based on String

E
that he's seen before. He thinks the title of the book started with the character A, M, or C. After Patterns
seeing the list of books, he realizes that the search has to be extended for book titles whose

.
nc
US
characters range from A to G. Another customer wants to know if his name and customer ID are
still available in the database. He was a customer of this company a long time ago and does not
remember his customer ID; however, he remembers that it was a four-digit number, with the last

,I
digit being either 1 or 9.

AT ns
1.
ON
Display the books that have the characters "art" in the title.

io
a) Revise the SELECT and WHERE clauses as shown.

E
PL rat
DU pe
TI

IC
lO
UA
ica

b) Execute the query.


c) In the Results pane, observe the titles that have been returned.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C

• SQL Server displays a list of five books with the characters "art" in their titles.
FO

• Some titles contain the word "Art."


• Other titles contain "art" as part of another word, such as Starting a Small Garden and Starting a
Greenhouse.
Ask students if they can
think of other ways to
2. Display the details of books for which the titles begin with A, M, or C. successfully query book
titles about art.

Lesson 2: Performing a Conditional Search | Topic C


66 | SQL Querying: Fundamentals (Second Edition)

a) Edit the pattern in the WHERE clause as shown.

LY
b) Execute the query.

ON
c) In the Results pane, observe that SQL Server displays 16 books with titles that begin with A, M, or
C.

E
.
nc
US
,I
AT ns
ON
io
E
3.
PL rat
Modify the query to display the details of books for which the titles begin with
the characters from A to G.
DU pe
TI

a) Edit the pattern in the WHERE clause as shown.


IC
lO
UA
ica
AL
og
T

b) Execute the query.


7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic C


SQL Querying: Fundamentals (Second Edition) | 67

c) In the Results pane, observe that books in the Results all have titles beginning with the characters
from A to G.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica

4. List the customer details from the Customers table for those who have a four-
AL
og

digit customer number.


T

a) Switch to the query tab with the Customers query and revise it as shown. (Alternatively, you can
7L
NO

type this query in a new query window.)


EV
01
DO
)2
R
(C
FO

Note: The single quotes in the WHERE clause contain four underscores. On
most keyboards, the underscore character is located on the right end of the
top row of keys (approximately above the letter P). Hold Shift while pressing
this key to get the underscore.
b) Execute the query.

Lesson 2: Performing a Conditional Search | Topic C


68 | SQL Querying: Fundamentals (Second Edition)

c) In the Results pane, observe that SQL Server displays five customers who have four-digit customer
numbers.

LY
ON
E
5. Modify the query to list customers with a four-digit customer number with the

.
last digit being either 1 or 9.

nc
US
a) Revise the last line of the query as shown.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

Note: The pattern in the WHERE clause consists of three underscore characters
IC
followed by [19] to search for 1 or 9 at the end of the customer number.
lO
UA

b) Execute the query.


c) In the Results pane, observe that SQL Server displays the two customers who have four-digit
customer numbers with the last digit being either 1 or 9.
ica
AL
og
T
7L
NO
EV
01
DO
)2

6. What WHERE clause would match cities that do not begin with "H", but do have
a second letter of "o"?
R
(C

A: WHERE city like '[^H]o%'


FO

7. What WHERE clause would match cities that do not contain the letters A, B, C,
or D?
A: This can be accomplished in various ways, such as WHERE city NOT like '%[a-d]%' and
WHERE city NOT like '%[abcd]%'

8. Clean up the workspace.

Lesson 2: Performing a Conditional Search | Topic C


SQL Querying: Fundamentals (Second Edition) | 69

a) Close all Query Editor windows without saving the queries.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search | Topic C


70 | SQL Querying: Fundamentals (Second Edition)

Summary
In this lesson, you narrowed the scope of your queries by performing conditional searches.
Depending on the size of an organization, its production databases can consist of hundreds or

LY
thousands of rows. Executing SELECT statements without any search conditions retrieves all of this
data and can significantly degrade the performance of the database servers. Using search conditions
enables you to narrow down the scope of your queries to select only those rows you need for
further business analysis.

ON
Why do you use a condition in a query?
A: Answers will vary, but may include: conditions are used to retrieve specific information from the
Encourage students to
use the social database. They make information retrieval easier and faster. Conditions become an important
networking tools criterion in querying when the user requires only a specific part of the information.
provided on the CHOICE
What are the operators that you will use when you have more than one condition

E
Course screen to follow
up with their peers after to be included in a query?

.
nc
the course is completed A: Answers will vary, but may include: you will use logical operators as well as arithmetic operators very

US
for further discussion often when more than one condition is included in a query. Depending upon the requirement, various
and resources to support
operators like compound assignment and comparison operators can also be used.

,I
continued learning.
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,

AT ns
peers, and the larger CHOICE online community about the topics covered in this course or
other topics you are interested in. From the Course screen you can also access available
ON
io
resources for a more continuous learning experience.

E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 2: Performing a Conditional Search |


3 Working with Functions

LY
ON
Lesson Time: 1 hour

E
Lesson Introduction

.
nc
US
You have retrieved specific data from a table by using a WHERE clause. But you can do more

,I
than just display data that is in a table. You can perform calculations and other operations
on data and present it in a desired format. In this lesson, you will use various functions to

AT ns
perform calculations on data to obtain meaningful output from the database.
ON
io
Lesson Objectives

E
In this lesson, you will: PL rat
• Perform date calculations.
DU pe
TI

• Calculate data using aggregate functions.


IC
lO

• Manipulate string values in a query.


UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
72 | SQL Querying: Fundamentals (Second Edition)

TOPIC A
Perform Date Calculations

LY
The data present in a table can be of any number of data types, including dates and times. But dates
and times may not be stored exactly the way you want to present them. Fortunately, SQL provides
tools you can use to format and perform calculations on dates and times.

ON
Date Storage
Microsoft® SQL Server® 2017 stores date information in a table using the data types datetime and
smalldatetime. Dates and times are actually stored as numbers, with each day as a whole number and
the time as a decimal. This makes it feasible to sort dates and use date arithmetic, such as calculating

E
the number of days, years, or minutes between two date values. When SQL Server retrieves this
information, you might want to view it in a specific date and time format other than its default

.
nc
format.

US
,I
Functions

AT ns
A function is a SQL Server object with a specified name and optional parameters that operates as a
single logical unit. The parameters the function accepts can be column names or values. If the
ON
function requires multiple input parameters, you must separate the parameters with commas. The

io
Functions
function performs a designated action and returns a result.

E
PL rat
The following figure shows a SELECT statement that contains two functions: DATEADD() and
GETDATE(). The first function, DATEADD(), enables you to add days, months, or years to an existing
date. In this example, the function DATEADD(month, 3, pubdate) adds three months to the
DU pe
TI

current value in the pubdate column for each row. (You might run into this scenario if you had to
IC
push back the publication date of all books published by the company.) The second function,
lO

GETDATE(), simply displays today's date and time.


UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Figure 3-1: A SELECT statement displaying functions.


R
(C

Types of Functions
FO

Functions can be classified as built-in functions, which cannot be modified by users, and user-
defined functions, which can be created and modified by users. There are three types of functions:
Types of Functions
rowset functions, which are used to reference tables in an SQL statement; aggregate functions,
which operate on a collection of values but return a single value; and scalar functions, which operate

Lesson 3: Working with Functions | Topic A


SQL Querying: Fundamentals (Second Edition) | 73

on a single value and then return a single value. Scalar functions can be used in any valid
expressions. The following table describes the categories of functions SQL Server includes.

Category Description

Configuration functions Return information about configuration settings.

LY
Cursor functions Return information about the status of a cursor.
Date and time functions Manipulate datetime and smalldatetime values.
Mathematical functions Perform trigonometric, geometric, and other numeric operations.

ON
Metadata functions Return information on the attributes of databases and database
objects.
Security functions Return information about users and roles.
String functions Manipulate char, varchar, nchar, nvarchar, binary, and varbinary

E
values.

.
nc
System functions Operate or report on various system-level options and objects.

US
System statistical functions Return information regarding the performance of the database

,I
server.

AT ns
Text and image functions Manipulate text and image values.
ON
io
Date Functions

E
PL rat
You use date functions to perform calculations on date columns that contain a date and time input
value. These functions return a string, numeric, or date and time value. In date functions, if datetime
or smalldatetime values are used, they are enclosed within single quotes.
DU pe
TI

Date Functions
In the following figure, you see a SELECT statement that uses the DATEADD() and DATEDIFF()
IC
functions. As mentioned earlier, the DATEADD(month, 3, pubdate) function adds three months to
lO

the value in the pubdate column. The DATEDIFF (year, pubdate, '12-31-2017') function
UA

displays the difference in years between the book's publication date (pubdate) and the date
12-31-2017.
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic A


74 | SQL Querying: Fundamentals (Second Edition)

To demonstrate SQL
Server's "day zero,"
today's date/time, and

LY
the number value behind
today's date/time,
execute this command:
SELECT CAST(0 AS

ON
datetime),
GETDATE(),
CAST(GETDATE() AS
float)
Also point out that this is
an example of a query
that does not use a

E
FROM clause.

.
nc
US
,I
AT ns
ON
io
Figure 3-2: A SELECT statement displaying date functions.

E
PL rat
Note: The SET DATEFORMAT statement can be used to set the order of the dateparts
(month/day/year) for entering datetime and smalldatetime values.
DU pe
TI

Date functions are scalar functions that perform operations on date and time values. The following
IC
table describes several of the date functions included with SQL Server's Transact-SQL. Other SQL
lO

databases may provide different functions.


UA

Function Description
ica

DATEADD(datepart, Returns a new datetime value based on adding an interval to the


number, date) specified date.
AL
og

DATEDIFF(datepart, Returns the number of date and time boundaries crossed


T

startdate, enddate) between two specified dates.


7L
NO

DATENAME(datepart, date) Returns a character string representing the datepart of the


specified date. The datepart can be month, date, or year.
EV
01

DATEPART(datepart, date) Returns an integer representing the specified datepart of the


DO

specified date.
)2

DAY(date) Returns an integer representing the day datepart of the specified


date.
R
(C

GETDATE( ) Returns the current system date and time of the SQL Server
computer in the format specified for datetime values.
FO

GETUTCDATE( ) Returns the datetime value representing the current UTC


(Universal Time Coordinate or Greenwich Mean Time) time. The
current UTC time is derived from the current local time and the
time zone setting in the operating system of the computer on
which SQL Server is running.

Lesson 3: Working with Functions | Topic A


SQL Querying: Fundamentals (Second Edition) | 75

Function Description
MONTH(date) Returns an integer that represents the month part of a specified
date.
YEAR(date) Returns an integer that represents the year part of a specified

LY
date.

Date and Time Data Types

ON
SQL Server supports several different date and time data types. The database administrator chooses
from these data types when designing and creating a table. The date and time data types vary based
on the precision of the date and time values they store in the table. There are six data types for Date and Time Data
storing date and time information: date, datetime, datetime2, datetimeoffset, smalldatetime, and Types
time.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica

Figure 3-3: Data types representing date and time.


AL

Data Type Description


og

This data type enables you to store dates in the format 'YYYY-MM-DD.'
T

DATE
Columns that use the DATE data type use three storage bytes. Supported
7L
NO

values are 0001-01-01 through 9999-12-31. The accuracy of this data type
EV

is exactly one day.


01

TIME The TIME data type enables you to store values in the
DO

'hh:mm:ss.nnnnnnn' format. TIME supports the data range of


)2

00:00:00.0000000 through 23:59:59.9999999. The accuracy of this data


type is 100 nanoseconds.
R
(C

DATETIME The DATETIME data type enables you to store dates in the format
'YYYY-MM-DD hh:mm:ss.nnnnnnn.' DATETIME uses eight bytes to
store its information. Supported year values are from 1753 through 9999.
FO

The DATETIME data type has the accuracy of one thousandth of a


second.

Lesson 3: Working with Functions | Topic A


76 | SQL Querying: Fundamentals (Second Edition)

Data Type Description


DATETIME2 The DATETIME2 data type also represents the date value 'YYYY-MM-
DD hh:mm:ss.nnnnnnn.' Values stored in the DATETIME2 data type
consume six to eight bytes of storage space. DATETIME2 supports
dates of January 1, 001 through December 31, 9999. The accuracy of this

LY
data type is 100 nanoseconds. Thus, the data stored in columns that use
the DATETIME2 format is more accurate than that of the DATETIME
format.

ON
DATETIMEOFFSET DATETIMEOFFSET represents a date value in the format 'YYY-MM-
DD hh:mm:ss.nnnnnnn [+| - ] hh:mm.' It takes 8 to 10 bytes to store
this information and supports the data range of January 1, 001 through
December 31, 9999. The accuracy of this data type is 100 nanoseconds.
SMALLDATETIME The SMALLDATETIME data type enables you to configure a column to
store dates from 01-01-1900 to 12-31-2079 and times from 00:00:00 to

E
23:59:59. SQL Server uses four bytes to store the contents of a
SMALLDATETIME column. The accuracy of the SMALLDATETIME

.
nc
US
data type is one minute.

,I
Conversion Between Date Types

AT ns
Dates may not always be stored in the format you need to present in your output. The CONVERT()
and CAST() functions are useful for converting between data types.
ON
io
The CONVERT() function enables you to provide a numeric style value that identifies the formatting
that will be applied to the value. CAST() is a bit more straightforward, converting between two data

E
PL rat
types, but not providing style options. The CONVERT() function is the more powerful of the two
functions, but it is also specific to SQL Server. In general, it is best to use the more standard CAST()
DU pe
TI

function whenever it can meet your needs, and use CONVERT() only when CAST() doesn't provide
the formatting you require.
IC
lO

Following are some examples showing the CAST() function being used to convert dates to other
UA

data types.
Students may wish to try -- Show date as a floating point number
ica

some of these examples SELECT CAST(pubdate AS float) FROM Titles


in the Pub1 database. -- Example from output: 42599
AL
og

-- Show date as a datetime


T

SELECT CAST(pubdate AS datetime) FROM Titles


7L

-- Example from output: 2016-08-19 00:00:00.000


NO
EV

-- Show date as a date


01

SELECT CAST(pubdate AS date) FROM Titles


-- Example from output: 2016-08-19
DO

Following are examples showing the CONVERT() function being used to convert date values into a
)2

varchar containing various date formats, which are specified by a particular style value.
R

-- Show date as a varchar containing date and time format


(C

SELECT CONVERT(varchar, pubdate, 100) FROM Titles


-- Example from output: Aug 19 2016 12:00AM
FO

-- Show date as a varchar containing short date-only format


SELECT CONVERT(varchar, pubdate, 6) FROM Titles
-- Example from output: 19 Aug 16

-- Show date as a varchar containing date in slash format with year first

Lesson 3: Working with Functions | Topic A


SQL Querying: Fundamentals (Second Edition) | 77

SELECT CONVERT(varchar, pubdate, 111) FROM Titles


-- Example from output: 2016/08/19

-- Show date as a varchar containing date in slash format with year last
SELECT CONVERT(varchar, pubdate, 100) FROM Titles

LY
-- Example from output: 08/19/2016

-- Show date as a varchar containing date in dash format with year last
SELECT CONVERT(varchar, pubdate, 110) FROM Titles
-- Example from output: 08-19-2016

ON
Syntax of CAST()
The syntax of the CAST() function is:
CAST ( expression AS data_type [ ( length ) ] )

E
Syntax of CONVERT()

.
nc
US
The syntax of the CONVERT() function is:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

,I
A list of style codes for CONVERT() is provided at https://docs.microsoft.com/en-us/sql/t-sql/
functions/cast-and-convert-transact-sql.

AT ns
ON
The DATEPART() Function

io
E
PL rat
The DATEPART() function is a date function that specifies the part of the date you want SQL
Server to return, such as the year, month, day, and hour. You'll find that you will use DATEPART() as
an input parameter for many of the date functions. You can use an abbreviation in date functions
DU pe
TI

instead of entering the full name of the datepart.


IC
Following is the list of abbreviations of DATEPART().
lO
UA

Datepart Abbreviations

year yy, yyyy


ica

quarter qq, q
AL
og

month mm, m
T

dayofyear dy, y
7L
NO

day dd, d
EV

week wk, ww
01

weekday dw
DO
)2

hour hh
minute mi, n
R
(C

second ss, s
FO

millisecond ms

Using SMALLDATETIME in Date Functions


The SMALLDATETIME data type is accurate only to the minute. So, when you use a date function
on a column that uses the SMALLDATETIME data type, SQL Server always returns zeros for the
seconds and milliseconds.

Lesson 3: Working with Functions | Topic A


78 | SQL Querying: Fundamentals (Second Edition)

Nested Functions
When you nest a function within another function, the innermost function is evaluated first. Its
output becomes an input argument for the outer function. Be sure your inner function is providing
Nested Functions
the correct data type to the outer function. For example, the query shown in the following figure

LY
returns the number of years that have transpired since the book was published.

ON
E
.
nc
US
,I
AT ns
ON
Figure 3-4: The GETDATE() function nested within the DATEDIFF() function.

io
E
PL rat
Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Perform Date Calculations.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic A


SQL Querying: Fundamentals (Second Edition) | 79

ACTIVITY 3-1
Performing Date Calculations

LY
Scenario
Fuller & Ackerman Publishing is celebrating its 25th year in the marketplace. Management has

ON
decided to release a "golden oldies" collection of books published in the company's early years. The
details of the old books are available in the "Obsolete_Titles" table. The information required is a
list of books that were released between 1994 and 2003, the exact year they were released, and the
age of each book.

E
1. Launch SQL Server Management Studio, open a new query editor, and select

.
Activity: Performing Date

nc
the Pub1 database. Calculations

US
a) If SQL Server Management Studio is not running, launch it and connect to the server.

,I
b) On the Standard toolbar, select New Query to open the Query Editor window.
c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub1 SQL code snippets for

AT ns
database is selected. the course activities are
stored as snippets.sql in
2.
ON
Identify the column name that contains the date information in the the Solutions folder for

io
each lesson's course
Obsolete_Titles table. data. You can use these

E
a) In the editor pane, type:
sp_help obsolete_titles
PL rat to save yourself some
typing as you lead
students through the
DU pe
TI

b) Execute the query. activities. Or you may


want to direct students
IC
to these files if they are
lO
UA

having trouble keeping


up with the typing in
class.
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

c) In the Results pane, observe that the pubdate column has smalldatetime as its data type.
d) In the editor pane, delete the query sp_help obsolete_titles.

Lesson 3: Working with Functions | Topic A


80 | SQL Querying: Fundamentals (Second Edition)

3. True or False? You can use the DATEPART function to extract the year from the
published date of the book.
☑  True
☐  False

LY
4. Enter a query to list the details of obsolete book titles, along with the year in
which they were published, and the age of the book.
a) In the editor pane, enter the following query.

ON
Note: Press Tab at the beginning of lines you need to indent.

Review with students the

E
purpose of the

.
DATEPART and

nc
US
DATEDIFF functions in
this SELECT statement.

,I
AT ns
ON
io
• The SELECT clause can be broken into multiple lines.

E

PL rat
It is common (but not universal) practice to break the lines as shown, indenting and starting each
new line with the comma used to separate each column.
• This approach enables you to delete various lines of the SELECT statement without having to
DU pe
TI

delete the comma from the previous line.


• It is also common practice to place the commas at the end of the line.
IC
• The query functions the same way, regardless of which way you position the commas.
lO
UA

Note: The column alias "year" and argument "YEAR" are pink because YEAR is
also the name of a SQL Server function.
ica

b) Execute the query.


c) In the Results pane, observe that only books published in the specified date range are displayed.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Note: Depending on the current year (when you work through this activity),
your results for age will differ from those shown here.

5. Modify the query to use just the year.

Lesson 3: Working with Functions | Topic A


SQL Querying: Fundamentals (Second Edition) | 81

a) In the editor pane, comment out the WHERE clause as shown.

LY
ON
b) In the editor pane, add a new WHERE clause as shown.

E
.
nc
US
,I
AT ns
ON
io
This version of the WHERE clause examines just the year part of the date.

E
c) Execute the query. PL rat
d) In the Results pane, observe that you get the same result as before.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01

When you need to deal with whole years, you can use this approach.
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic A


82 | SQL Querying: Fundamentals (Second Edition)

TOPIC B
Calculate Data Using Aggregate Functions

LY
SQL Server includes a number of functions that enable you to perform summary calculations on the
numerical data present in a table. For example, you might use the SUM aggregate function to calculate
the total of a column. In this topic, you will use aggregate functions to perform calculations on
numeric columns.

ON
Aggregate Functions
An aggregate function is a function that performs calculations on a set of values and returns a
single value. The function is composed of two parts: a name that gives an indication of the

E
Aggregate Functions
calculation SQL Server performs, followed by values or references to the values, enclosed in
parentheses. When SQL Server executes the query with the aggregate function, the result contains a

.
nc
single row with the summary information. Aggregate functions usually ignore NULL values.

US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL

Figure 3-5: A SELECT statement using aggregate functions.


og
T

This figure shows a SELECT statement that uses the COUNT() and AVG() aggregate functions. The
7L

function enables SQL Server to count the values in a column. The AVG() function
NO

COUNT()
calculates the average of all the values in the column.
EV

All aggregate functions operate on a collection of values but return a single, summarizing value.
01
DO

Aggregate Function Description


)2

AVG(expression) Returns the average of values in a column. The column can


contain only numeric data. Ignores NULL values (adds the non-
R
(C

NULL values and divides by the count of non-NULL values).


COUNT(expression), Returns a count of values in a column (if you specify a column
FO

COUNT(*) name as an expression) or of all rows in a table or group (if you


specify *). COUNT(expression) ignores NULL values, but
COUNT(*) includes them in the count.
MAX(expression) Returns the highest value in a column (last value alphabetically
for text data types). Ignores NULL values.

Lesson 3: Working with Functions | Topic B


SQL Querying: Fundamentals (Second Edition) | 83

Aggregate Function Description


MIN(expression) Returns the lowest value in a column (first value alphabetically
for text data types). Ignores NULL values.
SUM(expression) Returns the total of values in a column. The column can contain

LY
only numeric data. Ignores NULL values.

Keywords

ON
In the following figure, both SELECT and FROM are SQL keywords you use when writing a SELECT
statement.
Keywords

E
Point out to students
from the slide or the

.
nc
interface that SQL

US
Server displays the
keywords in blue.

,I
AT ns
ON
io
E
Figure 3-6: A SELECT statement displaying keywords. PL rat
A keyword in SQL Server is a word that is reserved for defining, manipulating, and accessing data.
DU pe
TI

When you enter keywords in the Query Editor window, Microsoft® SQL Server® Management
IC
Studio (SSMS) displays them in color.
lO
UA
ica

Using a Keyword
Outside Its Context
AL
og
T
7L
NO
EV

Figure 3-7: A SELECT statement displaying keywords outside the context.


01
DO

Because a keyword has a predefined meaning in SQL, if used outside the predetermined context,
)2

you must enclose it within double quotes. For example, if the SELECT statement uses the SQL
keyword "from" as an alias for the custnum column in the output, you must enclose it in double
R
(C

quotes so it won't be confused with the FROM keyword.


Note: Keywords can also be used as identifiers or names of databases or database objects, such
FO

as tables, columns, and views.

The DISTINCT Keyword


You use the DISTINCT keyword to eliminate duplicate values in a list of values.
The DISTINCT Keyword

Lesson 3: Working with Functions | Topic B


84 | SQL Querying: Fundamentals (Second Edition)

DISTINCT is an optional keyword you can use in two contexts: after the SELECT keyword, or inside
SUM(), AVG(), and COUNT() functions. SELECT DISTINCT will return unique rows of output.
In the SUM, AVG, and COUNT functions, you can use the DISTINCT keyword to eliminate duplicate
values before performing calculations. The DISTINCT keyword is always used with column names
and not with arithmetic expressions.

LY
The SELECT statement in the following figure provides you with a list of all the unique cities in
which Fuller & Ackerman Publishing's customers live.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
Figure 3-8: A SELECT clause with the DISTINCT keyword.
lO
UA

Within the following query, the DISTINCT keyword removes any duplicate values before they are
processed by the COUNT function.
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic B


SQL Querying: Fundamentals (Second Edition) | 85

DISTINCT in a COUNT
Function

LY
ON
E
.
nc
US
,I
Figure 3-9: DISTINCT removes duplicate values returned by a COUNT function.

AT ns
Access the Checklist tile on your CHOICE Course screen for reference information and
ON
io
job aids on How to Calculate Data Using Aggregate Functions.

E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic B


86 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 3-2
Calculating Data Using Aggregate Functions

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Activity: Calculating Data Management wants to expand Fuller & Ackerman Publishing. They have decided that as part of
Using Aggregate their planning, they need to determine the amount invested in the titles published in the past and

E
Functions then estimate the investments they need to make for the growth of the company. They have decided
to use the sales figures from the year 2017 for this analysis.

.
nc
US
In order to perform their analysis, management would like you to retrieve the following information:
• The titles released in 2017.

,I
• A count of the titles released, the total development cost for all books, and the average
development cost for a title.

AT ns
ON
io
Have students cover up 1. List all titles that were developed in 2017.

E
the activity steps and try
to write the SELECT
PL rat
a) Revise all lines of the query as shown.

statement for retrieving a


DU pe
TI

list of all titles released


in 2017. Then lead a
IC
discussion on how
lO

students' statements
UA

compare with what's in


step 1.
ica

b) Execute the query.


AL

c) In the Results pane, observe that SQL Server displays all books that were developed in 2017.
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

2. Display the total number of titles released, the total cost of development for all
titles, and the average development cost for a title in the year 2017.

Lesson 3: Working with Functions | Topic B


SQL Querying: Fundamentals (Second Edition) | 87

a) Revise the SELECT clause as shown. (You do not have to revise the FROM and WHERE clauses.)

LY
ON
Three output columns are specified, each produced by an aggregate function, and named by an
alias.
b) Execute the query.
c) In the Results pane, observe that the count of titles, the sum of the development cost, and the
average cost of development for a title are displayed.

E
.
nc
US
,I
AT ns
ON
Find the number of unique prices.

io
3.
a) Modify the SELECT clause as shown to observe COUNT(*) and COUNT(DISTINCT).

E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO

b) Execute the query.


EV

c) In the Results pane, compare the price_count to the distinct_price_count.


01
DO
)2
R
(C

While there are 56 different prices, there are only 31 distinct prices.
FO

Note: NULL devcost values are ignored (not counted) by the aggregate
functions. Duplicate values are ignored (counted only once) when using
COUNT(DISTINCT column).

Lesson 3: Working with Functions | Topic B


88 | SQL Querying: Fundamentals (Second Edition)

TOPIC C
Manipulate String Values

LY
You have used functions to manipulate dates and process numeric values. SQL also includes string
functions, which enable you to manipulate text.

ON
Strings
A string is a collection of characters that you cannot use in an arithmetic calculation. SQL Server
uses char, varchar, text, nchar, nvarchar, and ntext to store strings. The text and ntext data types
Strings
were removed in SQL Server 2008. You can use varchar(max) and nvarchar(max) instead for very
long string data.

E
The characters you store in these data types can be uppercase or lowercase letters, numerals, and

.
special characters such as the "at" sign (@), ampersand (&), and exclamation point (!) in any

nc
US
combination. When you use string values in an expression, you must enclose them within single
quotes. When SQL Server compares strings, it ignores the case of the strings.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

Figure 3-10: A SELECT statement in which the WHERE clause uses a string.
ica

String Functions
AL
og

String functions are functions that perform an operation on a string input value and return a string
or a numeric value. The following table describes key string functions in SQL Server.
T
7L
NO

String Function Description


EV

ASCII Returns the ASCII code value of the leftmost character of a


01

(character_expression) character expression.


DO

CHAR (integer_expression) Converts an integer ASCII code to a character.


)2

LEFT Returns the part of a character string starting at a specified


R

(character_expression, number of characters from the left.


(C

integer_expression)
FO

RIGHT Returns the part of a character string starting at a specified


(character_expression, number of characters from the right.
integer_expression)

LEN (string_expression) Returns the number of characters, rather than the number of
bytes, of the given string expression, excluding any trailing
blanks.

Lesson 3: Working with Functions | Topic C


SQL Querying: Fundamentals (Second Edition) | 89

String Function Description


STR (float_expression [, Returns character data converted from numeric data.
length [, decimal ] ] )

LOWER Returns a character expression after converting uppercase

LY
(character_expression) character data to lowercase.
UPPER Returns a character expression with lowercase character data
(character_expression) converted to uppercase.

ON
LTRIM Returns a character expression after removing leading blanks.
(character_expression)

RTRIM Returns a character string after truncating all trailing blanks.


(character_expression)

REPLACE Replaces all occurrences of the second given string expression in

E
('string_expression1', the first string expression with a third expression.

.
'string_expression2',

nc
US
'string_expression3')

REVERSE Returns the reverse of a character expression.

,I
(character_expression)

AT ns
REPLICATE Repeats a character expression for a specified number of times.
(character_expression,
integer_expression)
ON
io
SPACE Returns a string of repeated spaces.

E
(integer_expression) PL rat
STUFF Deletes a specified length of characters and inserts another set of
DU pe
TI

(character_expression, characters at a specified starting point.


IC
start, length,
lO

character_expression)
UA

SUBSTRING (expression, Returns part of a character, binary, text, or image expression.


start, length)
ica

UNICODE Returns the integer value, as defined by the Unicode standard,


('ncharacter_expression') for the first character of the input expression.
AL
og

NCHAR Returns the Unicode character associated with the given integer
T

(integer_expression) code, as defined by the Unicode standard.


7L
NO

SOUNDEX Returns a four-character (SOUNDEX) code to evaluate the


EV

(character_expression) similarity of two strings.


01

DIFFERENCE Returns the difference between the SOUNDEX values of two


DO

(character_expression, character expressions as an integer.


)2

character_expression)

QUOTENAME Returns a Unicode string with the delimiters added to make the
R
(C

('character_string' [, input string a valid Microsoft SQL Server delimited identifier.


'quote_character' ])
FO

PATINDEX ('%pattern%', Returns the starting position of the first occurrence of a pattern
expression) in a specified expression, or zeros if the pattern is not found, on
all valid text and character data types.

Lesson 3: Working with Functions | Topic C


90 | SQL Querying: Fundamentals (Second Edition)

String Function Description


CHARINDEX (expression1, Returns the starting position of the specified expression in a
expression2 [, character string.
start_location ])

LY
In the following figure, the SELECT statement uses the LEN() function to determine the number of
characters in each customer's name. You might use this information to help you decide whether to
String Functions
use a customer's name as their login name for your website or to make sure the string is long enough
before using SUBSTRING() or CHARINDEX() functions.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
Figure 3-11: A SELECT statement displaying a string function.
lO
UA

Case Conversion Functions


ica

Case conversion functions are functions that convert the case of a string. The LOWER function
accepts uppercase characters as the input and converts them to lowercase. The UPPER function
AL
og

Case Conversion
accepts lowercase characters as the input and converts them to uppercase. The input parameter you
provide for the case conversion function can be a value or a column name.
T

Functions
7L

The following figure shows you the usage of the UPPER() and LOWER() case functions and their
NO

output. The UPPER(custname) function converts the value in the custname column to all uppercase
EV

letters. Likewise, the LOWER(custname) function converts the value in the custname column to all
01

lowercase letters.
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic C


SQL Querying: Fundamentals (Second Edition) | 91

LY
ON
E
.
nc
US
Figure 3-12: A SELECT statement consisting of case conversion functions.

,I
AT ns
Note: In the editor pane, you can select a literal text string and convert it by pressing Ctrl+Shift
+U to convert to uppercase and Ctrl+Shift+L to convert to lowercase.
ON
io
Column Leading and Trailing Spaces

E
PL rat
Leading and trailing spaces are spaces that are present when the data stored in a char or nchar
(fixed length) column is less than the maximum number of characters that the column can contain.
DU pe
TI

Spaces inserted before the value are called leading spaces, whereas those inserted at the end of the Leading and Trailing
IC
value are called trailing spaces. Spaces
lO
UA

Even when data is stored in variable length columns such as varchar, which doesn't allow leading or
trailing spaces, the query output sent to the Microsoft SQL Server Management Studio Results
pane usually includes trailing spaces. You'll sometimes want to trim those spaces to make your
ica

output look better.


AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Figure 3-13: Leading and trailing spaces.

Lesson 3: Working with Functions | Topic C


92 | SQL Querying: Fundamentals (Second Edition)

The Trim Functions


The trim functions enable you to remove the leading and trailing blank spaces that are part of a
string of characters. You can use the LTRIM function to remove blank spaces before the value in a
The Trim Functions
column and the RTRIM function to remove blank spaces after the value in a column. The TRIM

LY
function trims both ends of the value. The trim functions work only on string values.
In the following example, LTRIM(lname) removes any leading spaces from the contents of the
lname field. The RTRIM(fname) function removes any trailing spaces from the fname field.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 3-14: A SELECT statement displaying trim functions.


IC
lO

Character Extraction
UA

Character extraction is the process of extracting specific characters from a string value. The
ica

extracted string is called a substring. You can extract characters from the beginning, end, or
anywhere in the string.
AL
og

The SUBSTRING Function


T
7L

SUBSTRING is the function you use to extract characters from any part of a given string. The
NO

SUBSTRING function accepts three input parameters. The first parameter can be a character string,
EV

The SUBSTRING
binary string, text, an image, a column, or an expression that includes a column. You cannot use
01

Function aggregate functions as expressions. The second parameter is an integer that specifies where you want
DO

the substring to begin. The third parameter is a positive integer that specifies the number of
characters or bytes you want SQL Server to return.
)2

In the following figure, you see an example of the use of the SUBSTRING() function. In the
R

SUBSTRING(custname, 5, 10) function, SQL Server will return the string of characters that
(C

begins with the fifth character of the customer name and continues for up to 10 characters. For
example, if the value in the custname field is "Chloe Community Gallery and Workshop," the
FO

SUBSTRING(custname, 5, 10) function returns the string "e Communit".


The LEFT() and RIGHT() functions return characters from the beginning or end of a string. For
example, to extract three characters from the beginning of the customer name, you can use
SUBSTRING(custname, 1, 3) or LEFT(custname, 3). To extract six characters from the end of
the customer name, you can use SUBSTRING(custname, LEN(custname)-5, 6) or
RIGHT(custname,6).

Lesson 3: Working with Functions | Topic C


SQL Querying: Fundamentals (Second Edition) | 93

LY
ON
E
.
nc
US
,I
Figure 3-15: A SELECT statement displaying the SUBSTRING function.

AT ns
Data Types Supported by SUBSTRING
ON
io
The output of the SUBSTRING function can be character data if the expression is one of the
supported character data types, binary data if the expression is one of the supported binary data

E
PL rat
types, or a string if the expression is the same type as the given expression.

Concatenation
DU pe
TI

IC
Concatenation is the process of combining two string expressions into one string expression. Use
lO

the + (string concatenation) operator to concatenate two expressions. Both expressions must be of
UA

the same data type, or you must be able to convert one expression to the data type of the other Concatenation
expression.
ica

In the following figure, the SELECT statement concatenates the sales representatives' last names with
their first names (lname+fname). In the output, however, the values in the lname and fname
AL
og

columns include trailing spaces, which are included in the result, producing a gap between the last
name and the first name.
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic C


94 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
Figure 3-16: A SELECT statement displaying the concatenation operation.

AT ns
You can resolve the problem of the extra spaces between the last and first names by applying the
TRIM() function to the source values.
ON
io
You might also want to use string concatenation to insert separating characters between two
expressions, such as a comma and a space. The following figure shows a version of the query with

E
the formatting improved in this way. PL rat
DU pe
TI

Concatenating Column
IC
Values and Static
lO

Values
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Figure 3-17: Concatenating column values and static values.


R
(C

Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Manipulate String Values.
FO

Lesson 3: Working with Functions | Topic C


SQL Querying: Fundamentals (Second Edition) | 95

ACTIVITY 3-3
Manipulating String Values

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Your manager has asked for a list of customers in a format that can be easily used for addressing Activity: Manipulating
envelopes. You will prepare a list with three columns: String Values

E
• Customer name

.
• Customer's street address

nc
US
• City, state, and ZIP Code on a single line, with city and state separated by commas

,I
1. List the names of customers and their addresses from the Customers table.

AT ns
Be sure to remove any trailing spaces from the output.
ON
a) In the editor pane, select the entire query and press Delete.

io
b) Type a new query as shown.

E
PL rat
DU pe
TI

IC
lO
UA
ica

c) Execute the query.


AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic C


96 | SQL Querying: Fundamentals (Second Edition)

d) In the Results pane, observe the list of customer names and addresses.

LY
ON
E
.
nc
US
• The city, state, and ZIP Code are displayed in a single column, instead of each component in its

,I
own column.
• Unfortunately, the city data is output with trailing spaces, which have been incorporated into the

AT ns
citystatezip column.
• You'll need to trim the city values before they are concatenated into citystatezip.
ON
io
2. Revise the query to trim the city values.

E
PL rat
a) Revise the query as shown, applying the TRIM function to city.
DU pe
TI

IC
Demonstrate the
command sp_help
lO
UA

customers to show
that the state column is
data type nvarchar(4),
ica

limiting it to two
characters at most, and
thus does not need to be
AL
og

trimmed. b) Execute the query, and observe the results.


T
7L
NO
EV
01
DO
)2
R
(C
FO

The gaps following the city names have been eliminated.

3. Clean up the workspace.

Lesson 3: Working with Functions | Topic C


SQL Querying: Fundamentals (Second Edition) | 97

a) Close all Query Editor windows without saving the queries.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions | Topic C


98 | SQL Querying: Fundamentals (Second Edition)

Summary
In this lesson, you used functions to perform calculations on data. Functions enable you to perform
tasks without having to write in-depth programs yourself. For example, aggregate functions enable

LY
you to count the number of rows that satisfy a search condition, which is something you might use
if you wanted to know how many customers purchased a particular item.

Mention some instances where you would use string functions. Why would you
use them?

ON
Encourage students to
use the social A: Answers will vary, but may include: string functions can be used in a wide variety of instances. One
networking tools example might occur when you want to remove leading or trailing spaces from the contents of a
provided on the CHOICE column. In this scenario, you could use the RTRIM() and LTRIM() functions.
Course screen to follow
up with their peers after Which function would you use most often? Why?
the course is completed

E
A: Answers will vary, but one of them might include the AVG() function. This function enables you to
for further discussion
calculate the average of the values in a particular column.

.
and resources to support

nc
US
continued learning. Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
peers, and the larger CHOICE online community about the topics covered in this course or

,I
other topics you are interested in. From the Course screen you can also access available
resources for a more continuous learning experience.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 3: Working with Functions |


4 Organizing Data

LY
ON
Lesson Time: 1 hour, 30 minutes

E
Lesson Introduction

.
nc
US
Retrieving data is the main purpose of most SQL queries. Organizing the data that appears

,I
in the result set helps you identify the information that you need instead of searching for it
among the retrieved data. In this lesson, you will sort and group data so that the required

AT ns
output is displayed. ON
io
Lesson Objectives

E
In this lesson, you will: PL rat
• Sort the query output to display the result in a specific order.
DU pe
TI

• Rank data.
IC
lO

• Group the data displayed in the output.


UA

• Filter grouped data.


ica

• Summarize grouped data.


• Use PIVOT and UNPIVOT operators.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
100 | SQL Querying: Fundamentals (Second Edition)

TOPIC A
Sort Data

LY
One of the simplest and most straightforward organizational techniques you can employ is a basic
sort. In this topic, you will sort the output of a query based on one or more columns.

ON
Data Sorting
Sorting is a method of arranging the rows displayed in the output of a query in either ascending or
descending order based on one or more column values. You can perform multiple levels of sorting
Sorting: Ascending
with a given set of rows.
Order

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
Figure 4-1: A table displaying the sort in ascending order by sale price.
DU pe
TI

IC
lO

Sorting: Descending
UA

Order
ica
AL
og
T
7L
NO
EV
01

Figure 4-2: A table displaying the sort in descending order by sale price.
DO
)2

The ORDER BY Clause


R
(C

You use the ORDER BY clause to sort the rows in a query's result set in a specific sort order. To
use this clause, enter ORDER BY followed by the column name on which you want to sort the output,
FO

The ORDER BY Clause


and then the optional keyword ASC for ascending order or DESC for descending order. (By default,
SQL Server sorts the output in ascending order if you don't specify an order.)
SQL Server treats the NULL values present in the columns as the lowest values. The ORDER BY
clause, when used, is entered at the end of the SQL SELECT statement.
[ ORDER BY [colname1, colname2,...] [ ASC | DESC ] ]

Lesson 4: Organizing Data | Topic A


SQL Querying: Fundamentals (Second Edition) | 101

Note: SQL Server cannot sort columns that contain ntext, text, or image data types.

You can perform multiple levels of sorting by specifying column names, one after the other, and
separating them with commas.

LY
In the following figure, you see a SELECT statement that includes an ORDER BY clause. The ORDER
BY clause specifies that SQL Server should first sort the output in ascending order by the slprice
column. Then, when there are two or more books that have the same price, SQL Server should sort
the output by the partnum column in descending order.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
Figure 4-3: A SELECT statement displaying the ORDER BY clause along with the resultant table.
lO
UA

Note: There is no limit to the number of columns in the ORDER BY clause, but when all these
ica

column sizes are added, the maximum capacity is 8,060 bytes.


AL
og

Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Sort Data.
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic A


102 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 4-1
Sorting Data

LY
Scenario
The management of Fuller & Ackerman Publishing has set up a team to analyze their profit and

ON
loss. They require information about book titles and their prices, listing books in descending order
of price. They also want the number of books that need to be sold to break even.

Activity: Sorting Data 1. Launch SQL Server Management Studio, open a new query editor, and select

E
the Pub1 database.

.
a) If SQL Server Management Studio is not running, launch it and connect to the server.

nc
US
SQL code snippets for b) On the Standard toolbar, select New Query to open the Query Editor window.
the course activities are c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub1

,I
stored as snippets.sql in database is selected.
the Solutions folder for

AT ns
each lesson's course
data. You can use these
2. List the book titles along with their sale price for all book titles in the Titles
table. Sort this list in descending order of sale price and in ascending order of
to save yourself some
ON
io
typing as you lead book title.
students through the
a) Enter the query as shown.

E
activities. Or you may
want to direct students
PL rat
to these files if they are
DU pe
TI

having trouble keeping


up with the typing in
IC
class.
lO
UA
ica

b) Execute the query.


c) In the Results pane, observe that 92 book titles are displayed with their sale price displayed in
descending order, and that books with the same price are sorted in ascending alphabetical order.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

3. Write a query to show the break-even quantity for sales of each book.

Lesson 4: Organizing Data | Topic A


SQL Querying: Fundamentals (Second Edition) | 103

a) Revise the SELECT and ORDER BY clauses, and add a WHERE clause as shown.

Sorting by calculated
value is the important

LY
idea to learn here.

ON
• The break-even point is the number of books that must be sold to recoup the development cost
for a book.
• Divide the development cost by sale price to determine how many books must be sold to match
the development cost.
• The results are sorted by the break-even calculated value.
b) Execute the query.

E
c) In the Results pane, observe the results.

.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

Each book title is shown along with its sale price, development cost, and the number of copies that
must be sold to recoup the development cost.
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic A


104 | SQL Querying: Fundamentals (Second Edition)

TOPIC B
Rank Data

LY
You have sorted data, which helps to reveal relationships between the values in different rows. You
can provide additional insights through SQL's various ranking functions.

ON
The Ranking Functions
Ranking functions are functions that sequentially number the rows in a result set based on the
partitioning and ordering of the rows. Depending on the ranking function you use in the query,
The Ranking Functions
some of the rows might get the same rank value as other rows. A ranking function is always
followed by the OVER clause, which determines the partitioning and ordering of the rows before

E
SQL Server applies a ranking function. The OVER clause is supported by the PARTITION BY clause,
which determines how rows are grouped for ranking, and the ORDER BY clause, which determines

.
nc
the order of rows within each partition.

US
The following query uses the ranking functions to accomplish these tasks:

,I
• The RANK() function ranks the rows by the values in the qty column.
• The DENSE_RANK() function ranks the rows by the values in the qty column but without gaps in

AT ns
the ranking values. ON
• The NTILE() function distributes the rows in the output into the specified number of groups

io
(five in the example).
• The ROW_NUMBER() function assigns a unique row number to each row in the output.

E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Figure 4-4: A SELECT statement displaying ranking functions.


R
(C

Syntax of a Ranking Function


FO

The syntax of a ranking function is:


Ranking Function () OVER ([PARTITION BY value_expression,...[n]] ORDER BY
<column> [ASC | DESC][,...[n]])

Lesson 4: Organizing Data | Topic B


SQL Querying: Fundamentals (Second Edition) | 105

The RANK Function


The RANK function is a ranking function that returns a ranking value for each row in a result set.
The rank values returned by the RANK function are not continuous. If two or more rows of a table
have the same value, SQL Server assigns them the same rank value. In such a case, the ranking value The RANK Function

LY
increases as specified by the ORDER BY clause.
In the following figure, you see a SELECT statement that displays the repid, qty, and custnum
columns in the output. In addition, SQL Server assigns a ranking to the rows based on the quantity
(qty) column. Notice that SQL Server assigns a tie to rows in which the quantity is the same.

ON
E
.
nc
US
,I
AT ns
ON
io
E
Figure 4-5: A SELECT statement displaying the RANK function.
PL rat
DU pe
TI

Syntax of the RANK Function


IC
The syntax of the RANK function is:
lO
UA

RANK () OVER ( [< partition_by_clause>] <order_by_clause>)


ica

The DENSE_RANK Function


The DENSE_RANK function is a ranking function that performs a task similar to that of the RANK
AL
og

function, but it does not produce gaps in the rank values. Instead, this function consecutively ranks
each unique ORDER BY value.
T

The DENSE_RANK
7L

Function
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic B


106 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
Figure 4-6: A SELECT query displaying the DENSE_RANK function.

AT ns
Syntax of the DENSE_RANK Function
ON
The syntax of the DENSE_RANK function is:

io
DENSE_RANK () OVER ( [< partition_by_clause>] <order_by_clause>)

E
PL rat
The ROW_NUMBER Function
DU pe
TI

The ROW_NUMBER function is a ranking function that uses an ORDER BY clause and a unique
IC
partition value to return a result set, which consists of sequential numbers for each row set. The row
lO
UA

The ROW_NUMBER
number is subject to change according to the rows in the output.
Function
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Figure 4-7: A SELECT statement displaying the ROW_NUMBER function.

Lesson 4: Organizing Data | Topic B


SQL Querying: Fundamentals (Second Edition) | 107

Syntax of the ROW_NUMBER Function


The syntax of the ROW_NUMBER function is:
ROW_NUMBER () OVER ( [< partition_by_clause>] <order_by_clause>)

LY
The NTILE Function
The NTILE function is a ranking function that divides the rows in each partition of a result set into
a specified number of groups based on a given value and ranks them according to the partition. The
NTILE function contains an integer expression as its main argument, which specifies the number of

ON
The NTILE Function
groups into which each partition will be divided. The rows in the result set will be divided evenly
among the partitions, but when the number of rows in the result set does not divide exactly into the
number of partitions, the rows are distributed in such a way that the larger groups appear first in the
result set.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica

Figure 4-8: A SELECT statement displaying the NTILE function.


AL
og

Syntax of the NTILE Function


T

The syntax of the NTILE function is:


7L
NO

NTILE (integer_expression) OVER ( [< partition_by_clause>] <order_by_clause>)


EV
01

The TOP n Keyword


DO
)2

You can use the TOP n keyword with an ORDER BY clause to select a specific number or percentage
of rows in the output. For example, you might use the TOP n keyword to select the top 10 sales
R

orders (by quantity) in the Sales table. Note that you must include an ORDER BY clause in the
(C

The TOP n Keyword


SELECT statement for the TOP n keyword to work properly.
In the following query, SQL Server lists rows from the Sales table in descending order by quantity.
FO

Because the query specifies TOP 10 in the SELECT statement, SQL Server lists only the first 10 rows
in the sorted output.

Lesson 4: Organizing Data | Topic B


108 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
Figure 4-9: A SELECT statement using the TOP n keyword.

,I
AT ns
Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Rank Data.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic B


SQL Querying: Fundamentals (Second Edition) | 109

ACTIVITY 4-2
Ranking Data

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Management of Fuller & Ackerman Publishing has set up a team to analyze the performance of Activity: Ranking Data
sales representatives based on their sales during 2017. Even though they have a report containing

E
the total sales quantities for 2017, they want to list the representatives based on the sales made by
them during that year. You would like to use ranking functions to list the representatives based on

.
nc
US
the quantity of books they sold in 2017.

,I
1. Show all sales results for 2017.

AT ns
a) Enter a query to show sales results for 2017. ON
io
E
PL rat
DU pe
TI

IC
lO
UA

b) Execute the query and observe the results.


ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C

There are 94 rows in the results.


FO

Next, you will add a column that partitions the sales representatives into five ranking groups, based
on their sales quantities.

2. Add a custom field based on the RANK function.

Lesson 4: Organizing Data | Topic B


110 | SQL Querying: Fundamentals (Second Edition)

a) Revise the query, inserting a new second line as shown.

LY
ON
b) Execute the query.
c) Scroll through the results, and observe how they are partitioned and ordered.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

• Because you partitioned by repid, rows for the same repid are clustered together.
IC
• Because you ordered by qty, rows within each partition are shown in order by the quantity sold.
lO

• The Rank column shows the rank order of each sales quantity. For example, 500 is the top
UA

ranked sales quantity (rank of 1), and 0 is the lowest ranked sales quantity (rank of 22).

Add a custom field based on the DENSE_RANK function.


ica

3.
a) Revise the query, inserting a new third line as shown.
AL
og
T
7L
NO
EV
01
DO
)2

b) Execute the query.


R
(C
FO

Lesson 4: Organizing Data | Topic B


SQL Querying: Fundamentals (Second Edition) | 111

c) Compare the numbering of the Dense Rank column to the Rank column.

LY
ON
E
.
nc
US
Rows are ranked in the same order, but DENSE_RANK does not skip ranking values when there are
multiple rows with the same rank, making it easier to understand the ranking.

,I
4. Divide the rows into five groups and add row numbers.

AT ns
a) Revise the query, inserting a new fourth and fifth line as shown.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

b) Execute the query.


ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic B


112 | SQL Querying: Fundamentals (Second Edition)

c) Examine the values shown in the Row Number column.

LY
ON
E
.
nc
US
• While row numbers seem redundant in the numbered table provided in the Results pane, it can
be useful to have row numbers directly in the SQL output.

,I
• If you plan to present the data in a table (on a website or in a mobile app, for example) that users
can sort (by selecting a column header, for example), it may be useful to have a row number

AT ns
showing the original sort order.

d) On the ribbon, select the Results to Text button to switch to plain text output.
ON
io
Alternatively, you can press Ctrl+T.
e) Execute the query.

E
PL rat
f) In the Results pane, scroll and observe the text-only results.
DU pe
TI

IC
lO
UA
ica
AL
og
T

• This is how a custom application or reporting tool would normally receive the SQL results.
7L

• SQL Server Management Studio adds its own row numbers, but you may have situations where
NO

you need to add them directly to the content.


EV

Examine the Ntile values.


01

5.
DO

a) On the ribbon, select the Results to Grid button to switch back to grid output.
)2

Alternatively, you can press Ctrl+G.


R

The next time you run a query, it will be shown in grid format.
(C

b) Execute the query.


c) Scroll and observe the Ntile column data.
FO

The values produced by Ntile break the ranked values up into the number of groups you specify
(five, in this query). So rows with an Ntile value of 1 are in the top fifth of rankings. Those with an
Ntile value of 2 are in the second fifth, and so on.

Lesson 4: Organizing Data | Topic B


SQL Querying: Fundamentals (Second Edition) | 113

TOPIC C
Group Data

LY
There are times when you need to summarize or "roll up" groups of data, rather than show the
detail of every row. For example, you might want to show a summary of total sales for each sales
rep, rather than list each sale separately. SQL provides various ways to accomplish this.

ON
Groups
A group is a collection of two or more records combined into one unit based on the values in one
or more columns. Summarized records present in each row of the group are listed together as a
single row in the output. SQL Server does not sort the groups in any order, but does sort the Groups

E
records within the group in ascending order.

.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og

Figure 4-10: A table displaying grouped records.


T
7L
NO

The GROUP BY Clause


EV

GROUP BY is a clause you use to group two or more rows displayed in the output based on one or
01

more columns.
DO

The GROUP BY clause is followed by a column or a non-aggregate expression that references a The GROUP BY Clause
)2

column.
Any columns you specify directly in the SELECT statement (that is, those that you do not use in an
R
(C

aggregating function) must also be included in the GROUP BY clause. In most cases, you use the
GROUP BY clause to enable you to perform a calculation on the group.
FO

In the following figure, SQL Server groups the rows in the sales table by sales representative ID. It
then calculates the total quantity of the sales for the group. In other words, this query enables you to
determine the total sales quantities for each sales representative.

Lesson 4: Organizing Data | Topic C


114 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
AT ns
Figure 4-11: A SELECT statement using the GROUP BY clause.
ON
io
If you do not include an ORDER BY clause in the query, SQL Server returns the groups for the

E
PL rat
GROUP BY clause in no particular order. To retrieve a sorted output, include the ORDER BY clause in
the query.
DU pe
TI

Syntax of the GROUP BY Clause


IC
The syntax of the GROUP BY clause is:
lO

[ GROUP BY [group_by_expression1, group_by_expression2,.] ]


UA
ica

Specifications for Using the GROUP BY Clause


A GROUP BY clause must comply with certain specifications when written as part of a SELECT
AL
og

statement.
T

Specification Description
7L
NO

Multilevel groups You can form multilevel groups by entering columns separated by
EV

commas. The number of levels is limited by the size of the data stored in
01

the column, aggregate columns, and aggregate values involved in the


DO

query.
)2

Aggregate functions If you use aggregate functions in the SELECT clause, SQL Server
calculates the summary values after the groups are formed.
R
(C

Non-aggregate lists When a non-aggregate list of values is entered in the SELECT clause, each
of the non-aggregate values must be included in the GROUP BY list.
FO

NULL values If the column on which the group is formed contains NULL values, they
are all placed in a single group.
Column aliases The column alias used in the SELECT clause cannot be used to specify a
grouping column.

Lesson 4: Organizing Data | Topic C


SQL Querying: Fundamentals (Second Edition) | 115

Query Grouping Sets


Grouping sets allow you to define multiple groupings within a single query. These grouping sets are
introduced as extensions to the GROUP BY clause. These extensions can include the CUBE and
ROLLUP subclauses and the GROUPING_ID function. However, these grouping sets define their own
Grouping Sets

LY
purpose, without which a single query defines only one grouping set in the GROUP BY clause. The
grouping set statement generates a result that is equivalent to the result set generated by using the
GROUP BY, ROLLUP, or CUBE operation. These grouping sets show better performance because they
execute a single query for multiple groupings.

ON
E
.
nc
US
,I
AT ns
Figure 4-12: A SELECT statement displaying grouping sets. ON
io
Note: Sometimes, when a GROUP BY clause is used along with the GROUPING SETS feature, it
will generate a result that is equivalent to multiple simple Transact-SQL GROUP BY statements.

E
PL rat
However, writing Transact-SQL statements is easier than using the GROUPING SETS subclause,
as it avoids the need to write multiple queries. The GROUPING SETS subclause enables you to
list all grouping sets that you require. Another added advantage with these grouping set
DU pe
TI

subclauses is that SQL Server optimizes data access and the calculation of aggregates.
IC
lO

The GROUPING_ID function helps you identify those grouping sets that each result row belongs to.
UA

In order to execute this function, you must provide all attributes that are involved in the grouping
set as the input. The result of the GROUPING_ID function is an integer result represented as a bitmap,
ica

in which each bit represents a different attribute. Therefore, this function produces a unique integer
for each of the grouping sets.
SELECT GROUPING_ID(ordnum,custnum)
AL
og

FROM sales
T

GROUP BY CUBE(ordnum, custnum);


7L

SELECT GROUPING_ID(ordnum,custnum)
NO

FROM sales
EV

GROUP BY ROLLUP(ordnum, custnum);


01

Example of the GROUPING SETS Subclause


DO

The following code illustrates the use of the GROUPING SETS subclause.
)2

SELECT partnum,bktitle
R

FROM titles
(C

GROUP BY GROUPING SETS ((partnum,bktitle));


FO

CUBE and ROLLUP Subclauses


The CUBE and ROLLUP subclauses are shortcuts to the predefined GROUPING SETS specifications.
More precisely, they are abbreviations to the GROUPING SETS subclause. Each of these subclauses The CUBE and
has unique operations associated with it. The CUBE subclause generates all possible grouping sets GROUPING SETS
obtained from the elements listed in parentheses. This also includes the empty grouping set. Subclauses

Lesson 4: Organizing Data | Topic C


116 | SQL Querying: Fundamentals (Second Edition)

However, the result obtained from the CUBE subclause is large because the results are exponential in
number. The CUBE subclause is beneficial for complex data analysis.

LY
ON
E
Figure 4-13: The CUBE and GROUPING SETS subclauses.

.
nc
US
The ROLLUP subclause, on the other hand, produces a hierarchical series of grouping sets. The
ROLLUP subclause is used with the ROLLUP keyword to specify the hierarchy of grouping attributes.

,I
This subclause returns 'n+1' grouping sets for 'n' elements in a hierarchical manner.

AT ns
ON
io
The ROLLUP and
GROUPING SETS

E
Subclauses
PL rat
DU pe
TI

IC
lO
UA
ica

Figure 4-14: The ROLLUP and GROUPING SETS subclauses.


AL
og

Example of the CUBE Subclause


The given example code illustrates the CUBE subclause. Consider the columns from the Pub1
T

database. CUBE(custid,repid,tsales); is equivalent to the following:


7L
NO

GROUPING SETS((custid,repid,tsales),(custid,tsales),(repid,tsales),
EV

(custid,repid),(custid),(repid),(tsales),())
01

Example of the ROLLUP Subclause


DO
)2

The given example code illustrates the ROLLUP subclause. Consider the columns from the Pub1
database. ROLLUP(custid,repid,tsales) is equivalent to the following:
R
(C

GROUPING SETS((custid,repid,tsales)),(custid,repid),(custid),())
FO

Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Group Data.

Lesson 4: Organizing Data | Topic C


SQL Querying: Fundamentals (Second Edition) | 117

ACTIVITY 4-3
Grouping Data

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
You must summarize the total sales made by each representative over a period of one year. Activity: Grouping Data

E
Show all 2017 sales results.

.
1.

nc
US
a) Delete the four rows of calculated columns so the query appears as shown.

,I
AT ns
ON
io
E
PL rat
b) Add an ORDER BY clause as shown.
DU pe
TI

IC
lO
UA
ica
AL
og
T

This will keep the rows for each rep sorted together.
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic C


118 | SQL Querying: Fundamentals (Second Edition)

c) Execute the query and scroll as you examine the result.

LY
ON
E
.
nc
US
,I
• There are multiple rows for each sales representative.

AT ns
• Now you need to modify the query so a single summary row is shown for each sales
representative.
ON
io
Note: The image in step 1c shows part of the results you'll see. You'll need to
scroll to see all rows in the results.

E
PL rat
2. Attempt to group the results into a single row for each sales representative.
DU pe
TI

a) Change ORDER BY to GROUP BY as shown.


IC
lO
UA
ica
AL
og
T
7L
NO

b) Execute the query and examine the result.


An error message is shown.
EV
01

Msg 8120, Level 16, State 1, Line 1


DO

Column 'Sales.qty' is invalid in the select list because it is not


contained in either an aggregate
)2

function or the GROUP BY clause.


• This message may not make the problem clear to you.
R
(C

• In this case, you're trying to group the results for each sales rep into a single row, and qty
contains different values for each row.
FO

• You need to summarize qty somehow—using one of the aggregate functions (like SUM), for
example.
• No problem was reported for repid because you're grouping by that column, so every row in that
group contains the same repid.
• An error message wasn't shown for the custnum column (which has the same problem) because
the error produced by the qty column was serious enough to stop the query before the custnum
column could be evaluated.

Lesson 4: Organizing Data | Topic C


SQL Querying: Fundamentals (Second Edition) | 119

3. Add an aggregate function.


a) Revise the first line of the query as shown.

LY
ON
• Enclosing custnum in a COUNT function returns the number of unique customers sold to by each
sales rep.
• COUNT(ordnum) and COUNT(custnum) would each return the same result: the number of
sales rows per sales rep.

E
b) Execute the query and observe the results.

.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

• Results for eight reps are shown.


• Results are grouped for each sales rep, showing the number of unique customers they sold to
during the year.
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic C


120 | SQL Querying: Fundamentals (Second Edition)

TOPIC D
Filter Grouped Data

LY
When you group data, all rows that form part of that group are listed together. You can further filter
grouped data by adding conditions. In this topic, you will filter grouped data using aggregate
functions.

ON
The HAVING Clause
HAVING is a clause you can use to specify a search condition based on an aggregate value. (Use a
WHERE clause if you want to search based on one of the columns in the SELECT statement.) You use
The HAVING Clause
the HAVING clause with the GROUP BY clause. After SQL Server groups and aggregates the data, it

E
applies the conditions in the HAVING clause.

.
In the following figure, the GROUP BY repid clause specifies that SQL Server should group the

nc
US
output rows based on the sales representative IDs. SQL Server then calculates the total sales for
each sales representative based on the aggregate function SUM(qty) in the SELECT statement.

,I
Finally, the HAVING clause restricts the output to only the sales representatives who have sold a total
quantity of 2000 or more.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

Figure 4-15: A SELECT statement displaying the HAVING clause with the GROUP BY clause.

Both the HAVING clause and the WHERE clause enable you to filter the results SQL Server displays in
ica

the output of a query. But these clauses differ in what they can filter. The WHERE clause enables you
to filter data coming in to the query based on any of the columns in the SELECT statement. In
contrast, the HAVING clause can filter based only on the output of an aggregate function.
AL
og
T
7L

Access the Checklist tile on your CHOICE Course screen for reference information and
NO

job aids on How to Filter Grouped Data.


EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic D


SQL Querying: Fundamentals (Second Edition) | 121

ACTIVITY 4-4
Filtering Grouped Data

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Fuller & Ackerman Publishing wants to increase by 10 percent the production of books that have Activity: Filtering
sold 2000 copies or more. The publishing department requires the part numbers of these books so Grouped Data

E
that they can increase the production of the specified books. As an incentive, management decided
to provide a bonus to representatives who have sold 2000 copies. The financial department requires

.
nc
US
the IDs of these representatives to credit the bonus into their salary account.

,I
1. Add a HAVING clause to show only representatives who sold at least 2000

AT ns
books.
a) Revise the query, adding a HAVING clause as the last line of the query, as shown.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica

• The database server will process the HAVING clause after FROM, WHERE, GROUP BY, and any
aggregating functions such as the SUM function in the SELECT clause.
AL
og

• Only rows with a total sales quantity greater than 2000 will be shown.
T

2. Execute the query and examine the results.


7L
NO

a) Execute the query.


EV
01
DO
)2
R
(C
FO

You may want to refer


students back to the last
step of the previous
activity in their student
b) Examine the results.
manual to see a screen
• Only five reps had annual sales totals greater than 2000. image of the previous
results.

Lesson 4: Organizing Data | Topic D


122 | SQL Querying: Fundamentals (Second Edition)

• Before you added the HAVING clause, eight reps were shown.
• If you wanted to sort the results by the number of customers sold to, you could add ORDER BY
#_Cust as the final clause of the SELECT statement.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic D


SQL Querying: Fundamentals (Second Edition) | 123

TOPIC E
Summarize Grouped Data

LY
After you have grouped data, you may find that creating additional subgroups in the grouped data
will be helpful. In this topic, you will summarize grouped data.

ON
The CUBE and ROLLUP Operators
CUBE and ROLLUP are operators that are used to display summary rows along with the rows displayed
by the GROUP BY clause. You enter the CUBE or ROLLUP operator after the GROUP BY clause. In the
result, the left column value of the summary row is displayed as NULL and the right column value The CUBE Operator
contains the summary value.

E
When you use the CUBE operator, the number of columns listed in the GROUP BY clause

.
determines the number of summary rows displayed in the output. A summary row is returned for

nc
US
every group and subgroup in the output. So, the number of rows in the output is the same,
regardless of the order in which grouping columns are specified.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01

Figure 4-16: A SELECT statement displaying the CUBE operator.


DO
)2

When you use the ROLLUP operator, groups are summarized in hierarchical order, from the
lowest level in the group to the highest. The group hierarchy is determined by the order in which
R
(C

grouping columns are specified. Changing the order of grouping columns can affect the number of
rows displayed in the output.
FO

Lesson 4: Organizing Data | Topic E


124 | SQL Querying: Fundamentals (Second Edition)

The ROLLUP Operator

LY
ON
E
.
nc
US
Figure 4-17: A SELECT statement displaying the ROLLUP operator.

,I
AT ns
Access the Checklist tile on your CHOICE Course screen for reference information and
ON
job aids on How to Summarize Grouped Data.

io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic E


SQL Querying: Fundamentals (Second Edition) | 125

ACTIVITY 4-5
Summarizing Grouped Data

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
To break down how each sales representative is making their sales quotas for the year, you'll Activity: Summarizing
summarize each sales representative's sales to each customer. Grouped Data

E
.
nc
Display the representative IDs and total sales made by each representative.

US
1.
a) Delete the HAVING clause, and revise the SELECT and GROUP BY clauses as shown.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
These changes will:
lO

• Display the custnum column, as well as a sum of sales quantities in the annual_total column.
UA

• Add a subgroup by custnum to the GROUP BY clause.


ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic E


126 | SQL Querying: Fundamentals (Second Edition)

b) Execute the query, and observe 17 rows with subtotals for each repid and custnum.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
2. Roll up the results. PL rat
a) Add WITH ROLLUP to the GROUP BY clause as shown.
DU pe
TI

IC
lO
UA
ica
AL
og
T

The query had already been grouped by repid and subgrouped by custnum. With these revisions,
7L
NO

the query will also display a rollup to show the grand total of sales made by all representatives.
b) Execute the query.
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic E


SQL Querying: Fundamentals (Second Edition) | 127

c) Examine the query results, scrolling down to view all of the rows.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
• The results show the IDs of representatives and the customers to whom they have sold books,

E

along with the total sales to each customer. PL rat
A summary row (with a custnum of NULL) totals the sales for each representative ID.
• The last row (repid and custnum of NULL) shows the grand total of sales made by all
DU pe
TI

representatives.
IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic E


128 | SQL Querying: Fundamentals (Second Edition)

TOPIC F
Use PIVOT and UNPIVOT Operators

LY
You have summarized data using the CUBE and ROLLUP operators. After you have summarized
data, you may wish to rotate column values into multiple columns so you can use aggregate
functions on any columns in the output. You might also want to rotate those columns into column
values again. In this topic, you will use PIVOT and UNPIVOT relational operators to accomplish such

ON
tasks. Pivoted output is sometimes called cross-tabulation or spreadsheet-style output.

The PIVOT and UNPIVOT Operators


PIVOT is a relational operator that is used to rearrange the related columns and values of a table in

E
the output of a query.

.
The PIVOT Operator The PIVOT relational operator rotates unique values from one column of a table into multiple

nc
US
columns in the output. This rotation enables SQL Server to perform aggregate functions on the
columns and display the resultant data in a pivoted table.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV

Figure 4-18: A SELECT statement using the PIVOT operator.


01
DO

Syntax of the PIVOT Operator


)2

The syntax of the PIVOT operator is:


SELECT [non-pivoted column] AS <column name>, ...[last pivoted column] AS
R
(C

<column name>
FROM (SELECT query that produces data) AS <alias for the source query>
FO

PIVOT (
<aggregate function> (column being aggregated)
FOR [column that contains the values that will become column headers] IN
([first pivoted column],....[last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>

Lesson 4: Organizing Data | Topic F


SQL Querying: Fundamentals (Second Edition) | 129

The UNPIVOT operator does the opposite of the PIVOT operator by rotating multiple columns
into the values of a single column. The UNPIVOT operator does not perform the exact reverse of the
PIVOT operator, because the UNPIVOT operator rearranges pivoted column values into columns
having new headings and new data.

LY
Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Use the PIVOT and UNPIVOT Operators.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic F


130 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 4-6
Using PIVOT

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Activity: Using PIVOT You are looking for patterns of monthly sales by sales representatives over the period of January
through June. You will write a query to summarize the quantities sold by each sales representative

E
each month. You will pivot the data to display each month in a separate column.

.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

Figure 4-19: Table showing six months of total sales for each representative.
ica

Create a simple query to produce the columns of data you'll need.


AL

1.
og

a) Revise the query as shown.


T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic F


SQL Querying: Fundamentals (Second Edition) | 131

b) Execute the query, and observe the results.

LY
ON
E
.
nc
US
Each sale is shown with:
• The month in which the sale occurred (shown as just the first three characters of the month)

,I
• The quantity of items sold
• The representative who sold them

AT ns
You would like to show the total sales quantity for each representative each month, rather than
ON
showing each individual sale. You can accomplish this using a PIVOT relational operator. But first

io
you have to prepare the results of this query to be used as the source for another query, which you
will use to actually perform the pivot operation.

E
2. Prepare the query to serve as the input source for another query.
PL rat
DU pe
TI

a) Highlight both lines of the query, and press Tab once to indent them.
b) Insert lines before and after the original query, to wrap it in a new outer query, as shown.
IC
lO
UA
ica
AL
og
T
7L
NO

• The new outer query uses your previous query as its FROM source.
• The outer query selects all columns from the source table, and doesn't apply a WHERE filter, so at
EV

this point, it should simply return the same results as the inner query.
01

• You've used an alias to name the results of this query as source.


DO

• The inner query is a subquery and must be enclosed by parentheses.


)2

c) Execute the query.


The results are the same as the previous results. At this point, the outer query doesn't add much,
R
(C

but you will now apply a pivot operation to change the way the sales data is presented in the query
results.
FO

3. Pivot the query results.

Lesson 4: Organizing Data | Topic F


132 | SQL Querying: Fundamentals (Second Edition)

a) Apply a pivot operation to the outer query as shown.

LY
ON
The pivot:
• Uses the SUM aggregation function to total the qty values for each month.
• Specifies mo (the month) as the column that contains values to be used as column headers.
• Specifies the first six months as the columns to be pivoted.

E
• Is given the alias pivoted to name the resulting (pivoted) table.

.
b) Execute the query, and examine the results.

nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO

The data has been pivoted. Months are now used as column headers.
UA

4. Exit SQL Server Management Studio without saving the query.


ica

Note: If you want to review the query later, you can save it to a file.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data | Topic F


SQL Querying: Fundamentals (Second Edition) | 133

Summary
In this lesson, you organized the data obtained from a query. By using the ability to organize data,
you can easily find the information you need in your queries' result sets.

LY
When and why might you enable sorting options?
A: Answers will vary, but may include: sorting can be enabled to get a listing of data in ascending or
Encourage students to
descending order to facilitate data analysis or to view the results alphabetically. use the social

ON
networking tools
When might you group the data in a table? provided on the CHOICE
A: Answers will vary, but may include: grouping data will facilitate better analysis, such as viewing the Course screen to follow
total sales of a company grouped region-wise or city-wise. up with their peers after
the course is completed
Note: Check your CHOICE Course screen for opportunities to interact with your classmates, for further discussion
peers, and the larger CHOICE online community about the topics covered in this course or and resources to support

E
other topics you are interested in. From the Course screen you can also access available continued learning.

.
nc
resources for a more continuous learning experience.

US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 4: Organizing Data |


FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
5 Retrieving Data from

LY
Multiple Tables

ON
Lesson Time: 1 hour, 30 minutes

E
.
nc
US
Lesson Introduction

,I
AT ns
Up to now, you have been retrieving and organizing data from a single table using various
clauses and functions in SQL. In this lesson, you will retrieve data from multiple tables.
ON
io
Lesson Objectives

E
In this lesson, you will:
PL rat
DU pe
TI

• Use the UNION operator to combine results from two queries into a single output.
IC
• Compare results of two queries to get distinct values.
lO
UA

• Retrieve data by joining tables.


ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
136 | SQL Querying: Fundamentals (Second Edition)

TOPIC A
Combine the Results of Two Queries

LY
Sometimes, you might need to pull information from multiple different tables and combine the
results in a single, unified result set. One way to accomplish this is using the UNION operator.

ON
Note: To further explore database design, check out the Spotlight on Database Normalization
presentation from the Spotlight tile on the CHOICE Course screen.
The Spotlight on
Database Normalization
presentation is available
from the Spotlight tile on The UNION Operator
the CHOICE Course
screen. You may choose The UNION operator enables you to combine the results of two or more queries into a single

E
to include it in your output. You enter the UNION operator between two SELECT SQL statements. The number of

.
instructional plans, or columns in each SELECT query must be identical. In each query, the data type of the respective

nc
US
you can remind students columns must be compatible. By default, when you use the UNION operator, SQL Server removes
about the tile and the duplicate rows from the result set. To display these duplicate rows, use the ALL keyword after the
supplemental

,I
UNION operator.
information it contains.
In the following figure, you see a query that combines the results of two SELECT statements to

AT ns
generate a single output. This query provides you with a list of all books from both the Titles and
Obsolete_Titles tables in a single result set. Note that the syntax meets the following requirements:
ON
io
The UNION Operator
• Both SELECT statements specify the same number of columns, and the columns have the same
data types.

E
PL rat
• The ALL keyword after the UNION operator specifies that SQL Server should list all rows in both
tables, including duplicates.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Figure 5-1: Two SELECT statements using the UNION ALL operator.
R
(C

Syntax of the UNION Operator


FO

The syntax of the UNION operator is:

Lesson 5: Retrieving Data from Multiple Tables | Topic A


SQL Querying: Fundamentals (Second Edition) | 137

SELECT column_name(s)
FROM table1 UNION [ALL]
SELECT column_name(s) FROM table2;

LY
Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Combine the Results of Two Queries.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic A


138 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 5-1
Combining the Results of Two Queries

LY
Scenario
To clinch a business deal, management wants an alphabetical list of all books that have been

ON
published from the day the company came into existence. Some of the books that were published
are currently out of print, and this information is found in the Obsolete_Titles table. The other
books published are in the Titles table.

Launch SQL Server Management Studio, open a new query editor, and select

E
Activity: Combining the 1.
Results of Two Queries the Pub1 database.

.
nc
US
a) If SQL Server Management Studio is not running, launch it and connect to the server.
b) On the Standard toolbar, select New Query to open the Query Editor window.

,I
SQL code snippets for c) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub1
the course activities are database is selected.

AT ns
stored as snippets.sql in
the Solutions folder for
2. List the part number, book title, and publishing date of all books in the Titles
each lesson's course
ON
io
data. You can use these table.
to save yourself some a) Enter the query as shown.

E
typing as you lead
students through the
PL rat
activities. Or you may
DU pe
TI

want to direct students


to these files if they are
IC
having trouble keeping
lO

up with the typing in


UA

class.
b) Execute the query, and examine the results.
ica
AL
og
T
7L
NO
EV
01
DO
)2

92 books are listed in three columns.


R
(C

3. List the part number, book title, and publishing date of all books in the
Obsolete_Titles table.
FO

a) Press Enter twice to insert a blank line after the previous query.

Lesson 5: Retrieving Data from Multiple Tables | Topic A


SQL Querying: Fundamentals (Second Edition) | 139

b) Type a second query as shown.

LY
ON
c) Execute the queries.
Both queries run, and their results are shown in two separate output tables.
d) Observe that there is a duplicate entry.
Have students make

E
sure no text is selected
before they select

.
nc
Execute.

US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T

• There are 99 rows in total between the two tables.


7L
NO

• The Clear Cupboards book appears in the current Titles table and the Obsolete_Titles table.
• The partnum and bktitle for the duplicate entries are the same, but the pubdate values are
EV

different.
01

e) Click within the top results table.


DO
)2
R
(C

The top table (Titles) contains 92 rows.


FO

Lesson 5: Retrieving Data from Multiple Tables | Topic A


140 | SQL Querying: Fundamentals (Second Edition)

f) Click within the bottom results table.

LY
The bottom table (Obsolete_Titles) contains 7 rows.

4. Create a combined book list.


a) In the editor pane, select the blank line between the two SELECT statements and type UNION to

ON
combine the results of the two tables.

E
.
nc
US
,I
b) Execute the query.

AT ns
c) Examine the results.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og

• SQL Server displays the combined output of both tables (99 rows).
T
7L

• The Clear Cupboards book appears in the list twice.


NO

• Although the UNION operator should only show one copy of any duplicate rows, it is showing two
EV

copies of Clear Cupboards because the rows are not identical. They have different pubdates. If
you didn't show pubdate, the two rows would be identical.
01
DO

5. Eliminate the pubdate column, and run the query again.


)2

a) In the editor pane, remove the pubdate column from both SELECT clauses.
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic A


SQL Querying: Fundamentals (Second Edition) | 141

b) Execute the query.


c) Scroll and examine the results to determine whether Clear Cupboards still appears twice.
The Clear Cupboards book now appears only once. Without the different dates in the pubdate
column, the data for both copies is now exactly the same. The UNION operator automatically
removes duplicates.

LY
6. Use the UNION ALL operator to show all combined rows, including
duplicates.
a) In the editor pane, change UNION to UNION ALL.

ON
E
.
nc
US
b) Execute the query.

,I
c) Scroll and examine the results to determine whether both copies of Clear Cupboards are shown.

AT ns
Once again, there are two copies of the Clear Cupboards book (rows 1 and 98).
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic A


142 | SQL Querying: Fundamentals (Second Edition)

TOPIC B
Compare the Results of Two Queries

LY
You have used the UNION operator to combine the results of two queries. But what if you want to
retrieve distinct values from the result set of either of the queries or from both queries? In this topic,
you will compare results to get distinct values in the output.

ON
The EXCEPT and INTERSECT Operators
The EXCEPT and INTERSECT operators enable SQL Server to compare the rows identified by each
SELECT statement and use this comparison to generate the query's result set. With the EXCEPT
The EXCEPT Operator
operator, SQL Server selects all rows in the first table except those that have matching rows in the

E
second table. In contrast, with the INTERSECT operator, SQL Server selects only those rows in the
first table that it finds in the second table.

.
nc
US
,I
AT ns
ON
io
E
PL rat
Figure 5-2: Two SELECT statements using the EXCEPT operator.

The EXCEPT operator enables you to combine two SELECT statements so that SQL Server retrieves
DU pe
TI

all rows from the first table that are not found in the second table. You might use this type of query
IC
to retrieve all books in the Titles table except those that are listed in the Obsolete_Titles table. Use
lO

this syntax for the EXCEPT operator:


UA

SELECT column1[, column2, ...]


FROM table1
ica

EXCEPT
SELECT column1[, column2, ...]
AL

FROM table2
og
T
7L
NO

The INTERSECT
Operator
EV
01
DO
)2

Figure 5-3: Two SELECT statements with the INTERSECT operator.


R
(C

You use the INTERSECT operator to return the rows that two queries have in common. For example,
FO

if you want to find out whether any of the books in the Titles table are also in the Obsolete_Titles
table, you can use two SELECT statements separated by the INTERSECT operator to retrieve this list.
Here is the syntax for the INTERSECT operator:
SELECT column1[, column2, ...]
FROM table1
INTERSECT

Lesson 5: Retrieving Data from Multiple Tables | Topic B


SQL Querying: Fundamentals (Second Edition) | 143

SELECT column1[, column2, ...]


FROM table2
As with the UNION operator, both EXCEPT and INTERSECT require that your SELECT statements
specify the same number of columns. In addition, the data types of those columns must be
compatible.

LY
Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Compare the Results of Two Queries.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic B


144 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 5-2
Comparing Results of Two Queries

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Activity: Comparing You are planning to place an order for books that are listed in the Titles table. However, you've
Results of Two Queries been told by the salesperson that this order also contains some obsolete titles, which are listed in the

E
Obsolete_Titles table. You want to ensure that you do not sell obsolete titles. So, you decide to first
check for obsolete titles listed in the Titles table and then list the titles that are not obsolete.

.
nc
US
Retrieve any records in the Titles table that are also in the Obsolete_Titles

,I
1.
table.

AT ns
a) In the editor pane, change UNION ALL to INTERSECT.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

b) Execute the query.


ica

c) In the Results pane, verify that the book title Clear Cupboards is displayed. There is one obsolete
title still in the Titles table.
AL
og

2. Retrieve a list of books from the Titles table that are not included in the
T

Obsolete_Titles table.
7L
NO

a) In the editor pane, change INTERSECT to EXCEPT.


EV
01
DO
)2
R
(C
FO

b) Execute the query.


c) In the Results pane, observe that SQL Server displays all records from the Titles table that are not in
the Obsolete_Titles table. There are a total of 91 rows.

Lesson 5: Retrieving Data from Multiple Tables | Topic B


SQL Querying: Fundamentals (Second Edition) | 145

TOPIC C
Retrieve Data by Joining Tables

LY
In most databases, you'll find that the information you need is distributed across multiple tables, not
contained in a single table. You can obtain this distributed information by combining the output
from multiple tables. In this topic, you will use SQL Server's ability to join tables to retrieve data
from more than one table.

ON
Joins
A join is a method of combining data from two or more tables into one result set based on a
condition or a column that is common to both tables. There are four types of joins:

E
• Cross joins Joins

.
• Inner joins

nc
US
• Outer joins
• Self joins

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

Figure 5-4: An output table generated by joining Table 1 and Table 2.


R
(C

Cross Joins
FO

The cross join is a join in which SQL Server combines each row in one table with each row from
the second table. In the SQL statement, you enter the CROSS JOIN keyword between the two table
names you are joining together. The output of a cross join is sometimes called a Cartesian product Cross Joins
because SQL Server joins every row in the first table with every row of the second table. The total

Lesson 5: Retrieving Data from Multiple Tables | Topic C


146 | SQL Querying: Fundamentals (Second Edition)

number of records displayed in the output is the number of rows in the first table multiplied by the
number of rows in the second table.
Note: If you add a WHERE clause to a cross join, SQL Server treats it as an inner join.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 5-5: A cross join combining the values in the Colors and Sizes tables.
IC
lO

Note: You'll find that cross joins are rarely used in a production environment because of their
UA

limited usefulness.
ica

Syntax of a Cross Join


The syntax of a cross join is:
AL
og

SELECT colname1, [colname2, ...]


T

FROM tablename1 CROSS JOIN tablename2


7L
NO

Inner Joins
EV
01

An inner join is a join that displays records from two tables that have equivalent values in one or
DO

more columns. SQL Server compares the values of the joined columns based on the equivalent
)2

Inner Joins
comparison operator. The output of an inner join query consists of only the rows that have
matching values in both tables.
R
(C

Note: The most commonly used joins in SQL Server are inner joins.
FO

In the following example, the SELECT statement displays the custnum column from the Sales table
and the fname and lname columns from the sales representative (Slspers) table. The query then uses
the FROM and the INNER JOIN clauses to join the two tables together (FROM sales INNER JOIN
slspers). Finally, the ON clause specifies the column that the two tables have in common: repid.
Notice that because the repid column exists in both tables, SQL Server requires you to identify the

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 147

table for each repid column by preceding the column name with the table name followed by a
period.

LY
ON
E
.
nc
US
,I
AT ns
Figure 5-6: The Sales table with an inner join to the Slspers table on the repid column.
ON
io
When you create queries that retrieve rows from multiple tables, you will encounter situations where

E
PL rat
the tables have columns with the same name. For example, the column partnum exists in both the
Titles and Sales tables in the Pub1 database. If you reference the column partnum in a query that Qualified Column
joins these two tables, you must identify the table from which you want SQL Server to pull the Names
DU pe
TI

column's information. You identify the table by preceding the column with the name of the table
IC
followed by a period.
lO
UA
ica
AL
og
T
7L
NO

Figure 5-7: Qualified column names.


EV
01

Syntax of an Inner Join


DO

The syntax of an inner join is:


)2

SELECT colname1, [colname2, ...]


FROM tablename1 INNER JOIN tablename2
R
(C

ON tablename1.column = tablename2.column
FO

Note: An inner join is also known as an equi-join.

Lesson 5: Retrieving Data from Multiple Tables | Topic C


148 | SQL Querying: Fundamentals (Second Edition)

Outer Joins
Another type of join supported in SQL Server is an outer join. Unlike an inner join in which SQL
Server displays the matching rows between two tables, with an outer join, SQL Server displays all
Outer Joins
rows in one table regardless of whether there's a matching row in the other table. For example, you

LY
might want a list of all books in the Titles table and their associated sales from the Sales table
regardless of whether each book has any sales. In other words, it's possible that you have a book in
Titles for which there are no sales. An outer join enables you to identify those books. SQL Server
supports three types of outer joins: left, right, or full.

ON
E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

Figure 5-8: The results of a left outer join.


IC
lO

You use a left outer join to display all rows from the table on the left of the FROM clause regardless
UA

of whether it has matching rows in the table on the right. Here is the syntax for a left outer join:
ica

SELECT column1, colummn2, ...


FROM table1 LEFT OUTER JOIN table2
ON table1.column = table2.column
AL
og

Note: You can typically rewrite a left outer join as a right outer join, and vice versa.
T
7L
NO

You use a right outer join to accomplish the opposite of a left outer join: display all the rows from
EV

the table on the right side of the FROM clause whether there are any matching rows in the table on
the left side or not. Use this syntax for a right outer join:
01
DO

SELECT column1, colummn2, ...


FROM table1 RIGHT OUTER JOIN table2
)2

ON table1.column = table2.column
R

A full outer join query returns all rows from both tables in the join condition regardless of whether
(C

there are matching values present in either table. This type of query has limited usefulness and you'll
rarely use it. Use this syntax to perform a full outer join:
FO

SELECT column1, colummn2, ...


FROM table1 FULL OUTER JOIN table2
ON table1.column = table2.column

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 149

The Table Alias Name


A table alias name is an alternative name you give to a table so that you can use it to refer to that
table in place of the table name. You typically use a table alias to avoid having to type a long table
name in an SQL statement or when you want to refer to the same table as two different tables in the The Table Alias Name

LY
same query. You specify the table alias after the table name in the FROM clause of a query. To access
a column in a table using the table alias, enter the table alias, followed by a period, and then the
column name.
In the following example, the FROM clause assigns the table alias name of "c" to the
Potential_Customers table. The alias is used in the SELECT clause as shorthand to refer to the table.

ON
E
.
nc
US
,I
AT ns
Figure 5-9: A SELECT statement displaying the table alias names.
ON
io
Note: Optionally, you can omit the AS keyword between the table name and table alias.

E
PL rat
DU pe
TI

Self Joins
IC
lO

A self join is a join that joins a table to itself. In the SQL statement, you use two table aliases in the
UA

join condition to identify the table. You then enter the INNER JOIN keywords in the FROM clause
between the table names and aliases. In a self join, both table names are the same, but the table alias Self Joins
ica

names are different. You specify the join condition in the ON clause.
The following figure shows an example of a self join. The Potential_Customers table contains a list
AL

of all potential customers and their assigned customer numbers. In addition, each potential customer
og

has a customer number in the referredby column that identifies which customer referred them to
T

Fuller & Ackerman Publishing.


7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


150 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
AT ns
Figure 5-10: A code sample using a self join.
ON
io
Multiple Table Joins

E
PL rat
It's possible for you to join more than two tables together in a single query by using multiple join
conditions. You do this when you want to retrieve columns of information from more than two
DU pe
TI

Multiple Table Joins


tables and have those columns appear in a single result set. For example, consider the Pub1
database. Consider the structure of the following tables, as shown in the figure.
IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 151

LY
ON
E
.
nc
US
,I
AT ns
ON
io
Figure 5-11: The structure of tables in the Pub1 database.

E
PL rat
This figure shows the structure of the Sales, Customers, and Titles tables. Notice that the Sales table
and Customers table have the custnum column in common. Likewise, the Sales and Titles tables
have the partnum column in common.
DU pe
TI

The relationships between these three tables make it possible for you to write a query such as the
IC
following, which retrieves a list of sales that contains the order number and quantity from the Sales
lO

table, the book title from the Titles table, and the customer name from the Customers table.
UA

SELECT ordnum, qty, bktitle, custname


FROM Sales INNER JOIN Customers
ica

ON Sales.custnum = customers.custnum
INNER JOIN Titles
AL
og

ON Sales.partnum = Titles.partnum
Be sure to list each table name just once in the FROM clause. It doesn't matter which table you list
T

first. The ON clauses make it clear which table.column to relate to the other table.column.
7L
NO

The following figure shows the output of the multiple table join query. Notice that the result set
EV

contains columns from the Sales, Titles, and Customers tables.


01

Multiple Table Joins:


DO

Query Results
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


152 | SQL Querying: Fundamentals (Second Edition)

LY
ON
E
.
nc
US
,I
Figure 5-12: Results of the multiple table join query.

AT ns
Note: To further explore joins, check out the Spotlight on Join Types presentation from the
ON
io
Spotlight tile on the CHOICE Course screen.
The Spotlight on Join
Types presentation is

E
available from the
Spotlight tile on the
PL rat
Access the Checklist tile on your CHOICE Course screen for reference information and
CHOICE Course screen. job aids on How to Retrieve Data by Joining Tables.
DU pe
TI

You may choose to


IC
include it in your
lO

instructional plans, or
UA

you can remind students


about the tile and the
supplemental
ica

information it contains.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 153

ACTIVITY 5-3
Retrieving Data by Performing an Inner Join

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Management has asked you to provide a list of all sales along with the name of the sales Activity: Retrieving Data
representative responsible for each sale. For each sale, they would like to know the order number, by Performing an Inner

E
the sale date, and the quantity sold, in addition to the name of the sales representative. They have Join
asked that you sort the output in descending order by the quantity sold.

.
nc
US
List all sales orders and sales reps in two queries.

,I
1.
a) In the query editor, delete the current query, and type two new queries as shown.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


154 | SQL Querying: Fundamentals (Second Edition)

b) Execute the queries, and examine the results.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
The repid column appears in both tables. You can use it to join data from the two tables.

E
2.
PL rat
Enter an inner join query to retrieve a list of all sales along with the sales
representatives' names.
DU pe
TI

a) Delete the second query, and add the fname and lname columns to the first query as shown.
IC
lO
UA
ica
AL
og
T

• The fname and lname columns are highlighted by SQL Server Management Studio because they
7L

are not contained in the Sales table.


NO

• These two columns are from the Slspers table.


EV

b) Add an INNER JOIN clause to join data from the Slspers table to the Sales table.
01
DO
)2
R
(C
FO

• Now that two tables are involved, you have to specify the table names for columns that appear in
both tables, to clarify which source you are referring to.
• The repid column is highlighted in the SELECT clause because you need to specify which table it
belongs to.

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 155

c) In the SELECT clause, add the table name for repid as shown.

LY
ON
Qualifying repid with either Sales or Slspers gives the same results.
d) Add the ORDER BY clause to sort the output in alphabetical order by sales representative name.

E
.
nc
US
,I
e) Execute the query.

AT ns
f) In the Results pane, scroll down to examine the records. ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T

• You have joined data from two different tables.


7L
NO

• The results are shown in descending order by the quantity sold.


EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


156 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 5-4
Retrieving Data by Performing an Outer Join

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected.

Scenario
Activity: Retrieving Data You have been asked to provide a list of all books published by Fuller & Ackerman and their total
by Performing an Outer sales (if any). You will use a left outer join query to produce this list.

E
Join

.
nc
Display all columns in the Titles and Sales tables.

US
1.
a) In the query editor, delete the current query, and type two new queries as shown.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

b) Execute the query, and examine the results to determine how you will join the two tables.
IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C

• The partnum column will enable you to join the tables.


• You'll pull the sales from the Sales table, and use partnum to join the book titles from Titles into
FO

the results.

2. Determine if any rows exist in one table, but not the other.

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 157

a) Revise the queries as shown.

LY
ON
These revisions:
• Show only partnum columns in both SELECT clauses.
• Use the EXCEPT operator to show only the values that exist in one table but not the other.
b) Execute the query, and examine the results.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
37 books, including part number 39843, do not exist in both tables.
DU pe
TI

You need to include even books that haven't sold any copies in your output. So you will use an outer
IC
join. Refer students back to
lO

the results in Step 1b.


UA

3. Write an outer join query, joining on partnum. Part number 39843


a) In the query editor, delete the current query, and enter a new query as shown. exists in Titles, but not
ica

Sales. Apparently the


book has never been
sold.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


158 | SQL Querying: Fundamentals (Second Edition)

b) Execute the query, and examine the results.

LY
ON
E
.
• All titles in the left table (Titles) were included, even those not in the Sales table (because no

nc
US
sales were recorded for those titles).
• The qty values for titles not in the Sales table are shown as NULL, since there is no value to

,I
provide.
• Separate rows are shown where there have been separate orders for the same title, such as The

AT ns
Complete Football Reference.
ON
Group the results by book title, and aggregate the quantities sold.

io
4.
a) In the query editor, revise the query as shown.

E
PL rat
DU pe
TI

IC
lO
UA
ica

After these changes, the query will:


AL

• Use the SUM function to aggregate the qty values.


og

• Use a GROUP BY clause to summarize results for each book title.


T

b) Execute the query.


7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 159

c) In the Results pane, scroll down to view the results.

You may wish to


demonstrate HAVING

LY
SUM(qty) IS NOT
NULL to show only those
books that did not sell.

ON
If you have time,
consider showing the
three-table query
example from the
Multiple Table Joins
section.

E
• Books that have had multiple orders, such as The Complete Football Reference, have been

.
nc
aggregated to a single row.

US
• The total sales quantity for all books with multiple orders is shown.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


160 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 5-5
Retrieving Data from a Single Table Using a Self

LY
Join

ON
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database
is selected.

Scenario

E
Activity: Retrieving Data You have been asked to provide a list of all potential customers and the customers that referred
from a Single Table them. Since both types of customers come from the same table, you will use a self join query to

.
nc
Using a Self Join produce the list.

US
,I
1. Enter a self join query to retrieve a list of potential customers and the

AT ns
customers that referred them to Fuller & Ackerman Publishing.
a) In the query editor, delete the current query, and type a new query as shown.
ON
io
E
PL rat
DU pe
TI

IC
lO

b) Execute the query, and observe the results.


UA
ica
AL
og
T
7L
NO
EV
01

• In this list of customers, some customers have been referred by other customers.
DO

• The referredby column shows the customer number of the person who referred each customer.
)2

For example, customer 31001 (Empire Books) was referred by customer 31004 (The Family
Sing Center).
R

• You can join this table to itself to show the name of each customer, with another column showing
(C

the name of the customer who referred them.


FO

2. Revise the query to show the name of the referredby customer.

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 161

a) Add an alias so you can refer to results of the SELECT query.

LY
This will enable you to refer to columns coming from this result when you expand on this query using

ON
a join.
b) Add two more lines to the query as shown.

E
.
nc
US
,I
• With the INNER JOIN operator, you have named the right side of the join as referredlist.

AT ns
• In the last line, you are matching the referredby column of custlist to the custname column of
referredlist.
c) Execute the query and examine the results.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA

All columns from custlist and referredlist are shown in the combined results. Multiple columns with
the same name might be confusing. You could rename some of the columns using aliases in the
ica

SELECT clause. Also, you don't need all of these columns for your report—just the names of the
customer and who referred them.
AL
og

3. Show specific columns from each side of the join.


T

a) Revise the SELECT clause as shown.


7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


162 | SQL Querying: Fundamentals (Second Edition)

b) Execute the query and examine the results.

LY
ON
The completed query produces a list of all potential customers and the customers that referred
them.

Exit SQL Server Management Studio without saving the query.

E
4.

.
Note: If you want to review the query later, you can save it to a file.

nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables | Topic C


SQL Querying: Fundamentals (Second Edition) | 163

Summary
In this lesson, you executed queries that retrieved data from multiple tables. By using the UNION,
EXCEPT, INTERSECT, and JOIN operators in your SELECT statements, you can retrieve the exact

LY
information you need from data split across multiple tables and display it in a single, united result
set.
When might you join one table to another? Why?
A: Answers will vary, but may include: you join one table to another when data in one table is dependent

ON
Encourage students to
upon the data in another table. Sometimes, the primary key in one instance is used to retrieve data use the social
from the other table based on the relationship between the columns in the table. networking tools
provided on the CHOICE
When might you join a table to itself? Why? Course screen to follow
A: Answers will vary, but may include: joining a table to itself is done when you want to retrieve up with their peers after
information from the table based on some condition that is satisfied within that table itself. For the course is completed

E
example, if you want to retrieve information of all employees belonging to the same country within the for further discussion

.
and resources to support
table, then you use a self join.

nc
continued learning.

US
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,

,I
peers, and the larger CHOICE online community about the topics covered in this course or
other topics you are interested in. From the Course screen you can also access available

AT ns
resources for a more continuous learning experience. ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 5: Retrieving Data from Multiple Tables |


FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
6 Exporting Query Results

LY
ON
Lesson Time: 30 minutes

E
Lesson Introduction

.
nc
US
So far in this course, you have queried tables and viewed the results in the Results pane in

,I
Microsoft® SQL Server® Management Studio (SSMS). SQL professionals would have no
problem with viewing and understanding such results. End users, on the other hand,

AT ns
typically don't have SSMS installed on their computers. For this reason, you need to be able
to provide users with data in formats they can use in the applications they do have available
ON
io
to them. In this lesson, you will obtain query results in formats that users can use in other
applications and tools.

E
PL rat
Lesson Objectives
DU pe
TI

In this lesson, you will:


IC
lO

• Generate a text file.


UA

• Generate an XML file.


ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
166 | SQL Querying: Fundamentals (Second Edition)

TOPIC A
Generate a Text File

LY
One of the ways in which you can distribute the results of your queries to other users is by saving
those results in text files. Users can then import those results into an application such as Microsoft®
Excel® for further manipulation. In this topic, you will save the result set of queries into text files.

ON
Text Data Formats
Microsoft® SQL Server® 2017 enables you to save the results of a query into two text formats.
These formats differ based on how SQL Server separates the data that is stored in the columns in
Text Data Formats
the result set. The two formats are:

E
• Tab delimited values. In this format, SQL Server separates the values in the columns of the result

.
set with tabs.

nc
US
• Comma delimited values. SQL Server separates the values in the columns of the result set with
commas. By default, SQL Server saves result sets in the comma delimited value format.

,I
You choose between the two data formats supported by SQL Server based on the application in
which a user plans to use the result set. For example, Microsoft Excel can open and use the data in a

AT ns
comma delimited text file. ON
io
Note: To further explore the use of text data files, check out the Spotlight on Exporting and
Using Text Data Files presentation from the Spotlight tile on the CHOICE Course screen.

E
The Spotlight on
Exporting and Using
PL rat
Text Data Files
DU pe
TI

presentation is available Access the Checklist tile on your CHOICE Course screen for reference information and
from the Spotlight tile on job aids on How to Save the Query Results.
IC
the CHOICE Course
lO

screen. You may choose


UA

to include it in your
instructional plans, or
ica

you can remind students


about the tile and the
supplemental
AL

information it contains.
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 6: Exporting Query Results | Topic A


SQL Querying: Fundamentals (Second Edition) | 167

ACTIVITY 6-1
Saving the Query Results

LY
Data File
C:\094018Data\Exporting Query Results\Commissions.sql

ON
Scenario
You have a query that generates a report on sales commissions for all sales representatives for an Activity: Saving the
entire year. You will export the report to a CSV format, so it can be imported into Excel for further Query Results
analysis.

E
.
nc
Launch SQL Server Management Studio, open a new query editor, and select

US
1.
the Pub1 database.

,I
a) If SQL Server Management Studio is not running, launch it and connect to the server.
b) Select File→Open→File. Navigate to C:\094018Data\Exporting Query Results, and select

AT ns
Commissions.sql.
c) Select Open.
ON
io
The query is loaded into the query editor.
d) On the SQL Editor toolbar, from the Available Databases drop-down list, ensure that the Pub1

E
database is selected.
e) Examine the query.
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV

This query combines numerous techniques that you have used, including joins, aliases, sorting,
01

functions, and concatenation.


DO
)2
R
(C
FO

Lesson 6: Exporting Query Results | Topic A


168 | SQL Querying: Fundamentals (Second Edition)

f) Execute the query.

Consider having a
student volunteer to

LY
explain how the query
works step by step.

ON
The query provides summary information for each sales rep, including commission rate, total sales,

E
and commission for the year.

.
nc
US
2. Save the query results in the comma delimited format.
a) In the Results pane, right-click the blank area and select Save Results As.

,I
b) In the Save Grid Results dialog box, navigate to the C:\094018Data\Exporting Query Results folder.
c) In the File name text box, type Annual Sales Commissions

AT ns
d) Verify that CSV (Comma delimited) (*.csv) is selected in the Save as type drop-down list.
ON
io
E
PL rat
DU pe
TI

e) Select Save to save the results as a comma delimited text file.


IC
f) Minimize the SQL Server Management Studio application window.
lO
UA
ica
AL
og
T
7L
NO
EV

3. Open the Annual Sales Commissions.csv file and view its content.
01

a) In File Explorer, navigate to the C:\094018Data\Exporting Query Results folder.


DO
)2
R
(C
FO

Lesson 6: Exporting Query Results | Topic A


SQL Querying: Fundamentals (Second Edition) | 169

b) Double-click Annual Sales Commissions.csv to open the file.


If Excel is installed on your computer, the CSV file will open in Excel.

LY
ON
E
.
nc
US
,I
AT ns
ON
io
Note: You may need to drag the dividers between column headings to adjust

E
column widths so all the data is visible.
PL rat
c) If you are prompted to select an application with which to open the file, select Notepad.
DU pe
If you open the file in Notepad, you can see that commas are used to separate the columns. String
TI

values are enclosed in double quotes.


IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

d) Exit the application (Excel or Notepad) that you used to examine the CSV file.
e) Close any File Explorer windows that you opened.
R
(C
FO

Lesson 6: Exporting Query Results | Topic A


170 | SQL Querying: Fundamentals (Second Edition)

TOPIC B
Generate an XML File

LY
In addition to saving result sets in text formats, you can also save the output of queries in the XML
format. Files in XML format can be used by a variety of applications, particularly web-based
applications. In this topic, you will save query results in an XML file.

ON
XML
XML stands for eXtensible Markup Language. XML is used to create custom markups, thereby
allowing users to "mark up" or define their own elements of data within a document. Users define
these elements through the use of tags. The main purpose of XML is to facilitate the sharing of

E
structured data among applications and across the Internet. XML is easily readable because it uses
self-descriptive tags. XML is similar to HTML in its coding format, but unlike HTML, which is used

.
nc
to display data, XML is used to define data.

US
,I
The FOR XML Clause

AT ns
The For XML clause is a clause that you can use to return the results of a query in XML format.
The FOR XML clause requires one or all of four modes to return results.
ON
io
The FOR XML Clause
Mode Description

E
RAW PL rat
Generates a single element per row in the rowset with a generic identifier
as the element tag.
DU pe
TI

AUTO Returns query results in a simple XML tree.


IC
EXPLICIT Defines the shape of the resulting XML tree. It requires a specific format
lO

for the resulting rowset that is generated.


UA

PATH Generates an element wrapper for each row in a rowset.


ica

In the following example, the SELECT statement selects all sales representatives whose IDs begin
with the letter "N." The ORDER BY clause sorts the result set by the representative IDs. The FOR
AL
og

XML AUTO, TYPE, ELEMENTS clause specifies that SQL Server should generate the query's result set
in XML with a single element per row for each salesperson.
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 6: Exporting Query Results | Topic B


SQL Querying: Fundamentals (Second Edition) | 171

LY
ON
E
.
nc
US
,I
AT ns
Figure 6-1: A FOR XML clause illustration.
ON
io
Syntax of the FOR XML Clause

E
The syntax of the FOR XML clause is:
SELECT (columnname1,columnname2,....)
PL rat
DU pe
TI

FROM table name


WHERE (condition)
IC
ORDER BY (expression)
lO

FOR XML mode


UA
ica

Access the Checklist tile on your CHOICE Course screen for reference information and
job aids on How to Generate an XML File.
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 6: Exporting Query Results | Topic B


172 | SQL Querying: Fundamentals (Second Edition)

ACTIVITY 6-2
Generating an XML File

LY
Before You Begin
SQL Server Management Studio is running. A query editor window is open, and the Pub1 database

ON
is selected. The Commissions.sql file is open in the query editor.

Scenario
Activity: Generating an Your team uses a cloud-based application to perform analysis on your sales. The application requires
XML File that you upload input data in an XML format. You will export the annual sales commissions report

E
to XML.

.
nc
US
1. Revise the query to produce XML output.

,I
a) Add a new last line to the query as shown.

AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV

The FOR XML AUTO, TYPE, ELEMENTS clause causes SQL Server to return the results of the
01

query in the XML format.


DO

• The AUTO parameter requests that XML be displayed in a nested format in which each sales
)2

representative's information appears indented below the sales representative's ID.


• The TYPE parameter sets the data type of the results to XML.
R

• The ELEMENTS parameter requests that SQL Server return the column information for each
(C

sales representative as XML elements.


FO

2. Produce the XML report.

Lesson 6: Exporting Query Results | Topic B


SQL Querying: Fundamentals (Second Edition) | 173

a) Execute the query.

LY
ON
The results are formatted as XML. A link is provided so you can open the XML output as a file.
b) In the Results pane, select the hyperlink.
The XML that was generated opens in an XML editor.
c) In the XML Editor window, observe that all column values are displayed within their respective
column names as XML elements.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2

d) Select File→Save xmlresult1.xml As to save the XML file.


e) In the Save File As dialog box, navigate to the C:\094018Data\Exporting Query Results folder.
R
(C

f) In the File name text box, type Commission Report


g) In the Save as type drop-down list, make sure that XML Files is selected.
FO

h) Select Save to save the XML file.

3. Exit SQL Server Management Studio without saving your changes to the
query.

Lesson 6: Exporting Query Results | Topic B


174 | SQL Querying: Fundamentals (Second Edition)

Summary
In this lesson, you exported query results in both the text and XML formats. Exporting result sets in
different formats enables you to easily work with your data in other applications.

LY
For what purposes will you save query results?
A: Answers will vary, but may include: query results can be saved to analyze data, and to enable clients
Encourage students to
use the social to view the results in different applications.

ON
networking tools
provided on the CHOICE How is the ability to generate an XML file beneficial?
Course screen to follow A: Answers will vary, but may include: XML format reports can be accessed by many different
up with their peers after applications. XML data is also easily readable because it uses self-descriptive tags.
the course is completed
for further discussion Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
and resources to support peers, and the larger CHOICE online community about the topics covered in this course or

E
continued learning. other topics you are interested in. From the Course screen you can also access available

.
nc
resources for a more continuous learning experience.

US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Lesson 6: Exporting Query Results |


SQL Querying: Fundamentals (Second Edition) | 175

Course Follow-Up
Organizations use databases and the tables within them to store mission-critical information. When
you need to retrieve information from these databases, you must use the Structured Query Language
(SQL). Using SQL enables you to perform business analysis tasks such as identifying sales trends,

LY
targeting customers for marketing purposes, and verifying whether an inventory item is in stock.
In this course, you used SQL as a tool to retrieve information from a database and its tables. You
retrieved all information in tables, and then you developed queries to retrieve specific information
using conditions. You learned to sort, group, and filter the results of queries. You also joined tables

ON
to extract information present in multiple tables. Then, you exported query result sets as text and
XML files.

What's Next?
SQL Querying: Advanced (Second Edition) is the next course in this series. This course covers advanced
querying concepts such as creation of tables and indexes.

E
You are encouraged to explore SQL querying fundamentals further by actively participating in any

.
nc
of the social media forums set up by your instructor or training administrator through the Social

US
Media tile on the CHOICE Course screen.

,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Course Follow up
FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
A The Pub1 Database

LY
ON
The database used in this book, called the Pub1 database, is being used in a hypothetical
book publishing company called Fuller & Ackerman Publishing. The following tables
constitute the Pub1 database.
• The Customers table describes each of Fuller & Ackerman Publishing's customers.
• The Sales table describes each book sale.

E
• The Slspers table describes each sales representative working at Fuller & Ackerman

.
Publishing.

nc
US
• The Titles table describes each book produced by Fuller & Ackerman Publishing.
• The Obsolete_Titles table describes all books that are out of print.

,I
• The Potential_Customers table describes any possible new customers for Fuller &
Ackerman Publishing.

AT ns
The Customers Table
ON
io
Column Name Data Type Length Description

E
custnum nvarchar PL rat 10 The customer number for each client.
Each customer is assigned a unique
DU pe
TI

IC customer number.
referredby nvarchar 10 The customer number of the client
lO

who referred this potential customer to


UA

Fuller & Ackerman Publishing.


custname nvarchar 60 The customer’s name, or business
ica

name.
address nvarchar 50 The customer’s street address.
AL
og

city nvarchar 40 The city in which the customer resides.


T

state nvarchar 4 The state in which the customer


7L
NO

resides.
EV

zipcode nvarchar 24 The state’s ZIP Code.


01

repid nvarchar 6 The customer’s sales representative’s


DO

identification number.
)2

The Sales Table


R
(C

Column Name Data Type Length Description


FO

ordnum nvarchar 10 The order number for each book sale.


Each sales order is assigned a unique
order number.
sldate smalldatetime 4 The date of sale.
178 | SQL Querying: Fundamentals (Second Edition)

Column Name Data Type Length Description


qty int 4 The number of books ordered.
custnum nvarchar 10 The customer number for the
customer purchasing books.

LY
partnum nvarchar 10 The part number of the book being
ordered.
repid nvarchar 6 The sales representative responsible for

ON
the sale.

The Slspers Table

Column Name Data Type Length Description

repid nvarchar 6 The identification number for each

E
salesperson. Each sales representative is

.
assigned a unique identification number.

nc
US
fname nvarchar 20 The first name of the sales representative.

,I
lname nvarchar 40 The last name of the sales representative.
commrate float 8 The sales representative’s commission rate.

AT ns
The Titles Table
ON
io
Column Name Data Type Length Description

E
partnum nvarchar
PL rat
10 The part number for each book published
by Fuller & Ackerman. Each book is
DU pe
TI

assigned a unique part number.


IC
bktitle nvarchar 80 The title of the book.
lO
UA

devcost money 8 The development cost of the book.


slprice money 8 The sale price of the book.
ica

pubdate smalldatetime 4 The date when the book was published.


AL
og

The Obsolete_Titles Table


T
7L

Column Name Data Type Length Description


NO

partnum nvarchar 10 The part number for each book considered


EV

obsolete.
01
DO

bktitle nvarchar 80 The title of the obsolete book.


)2

devcost money 8 The development cost of the obsolete


book.
R
(C

slprice money 8 The price of the book.


pubdate smalldatetime 4 The date when the book was published.
FO

Appendix A : The Pub1 Database |


SQL Querying: Fundamentals (Second Edition) | 179

The Potential_Customers Table

Column Name Data Type Length Description

custnum nvarchar 10 A unique number assigned for the


potential customer.

LY
referredby nvarchar 10 The customer number of the client who
referred this potential customer to Fuller &
Ackerman Publishing.

ON
custname nvarchar 60 The potential customer’s name, or
business name.
address nvarchar 50 The potential customer’s street address.
city nvarchar 40 The city in which the potential customer
resides.

E
state nvarchar 4 The state in which the potential customer

.
resides.

nc
US
zipcode nvarchar 24 The potential customer’s ZIP Code.

,I
repid nvarchar 6 The identification number of the sales
representative in the potential customer’s

AT ns
area.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Appendix A : The Pub1 Database |


FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
Mastery Builders

LY
ON
Mastery Builders are provided for certain lessons as additional learning resources for this

E
course. Mastery Builders are developed for selected lessons within a course in cases when

.
they seem most instructionally useful as well as technically feasible. In general, Mastery

nc
US
Builders are supplemental, optional unguided practice and may or may not be performed as
part of the classroom activities. Your instructor will consider setup requirements, classroom

,I
timing, and instructional needs to determine which Mastery Builders are appropriate for you
to perform, and at what point during the class. If you do not perform the Mastery Builders

AT ns
in class, your instructor can tell you if you can perform them independently as self-study,
and if there are any special setup requirements.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO
182 | SQL Querying: Fundamentals (Second Edition)

Mastery Builder 1-1


Executing a Simple Query

LY
Activity Time: 15 minutes

ON
Scenario
Information about customers, book titles, sales representatives, and sales is stored in
separate tables in the Pub1 database. You must query the database and retrieve
information requested by functional managers and executives in the company for
various business needs. The information the managers have requested includes:
• Lists of all customers, titles, sales representatives, and sales.

E
• A mailing list that consists of the customer name and address information.

.
nc
• A list with the book title, part number, and sale price.

US
• A list of sales representatives' names and ID numbers.
• A list of all orders, the part number ordered, and the sale quantity.

,I
AT ns
1. If SQL Server Management Studio is not running, launch it and
ON
connect to the server. Open a new query editor, and from the

io
Available Databases list, select Pub1.

E
2.
PL rat
In the Object Explorer pane, explore the tables included in the
Pub1 database and their structures.
DU pe
TI

IC
3. Write and execute SELECT statements to view all columns and all
lO
UA

rows in each of the Customers, Titles, Slspers, and Sales tables.


ica

4. Write and execute a query that retrieves these columns from the
Customers table: custname, address, city, state, and zipcode.
AL
og

5. Write and execute a query that retrieves the bktitle, partnum, and
T

slprice columns from the Titles table.


7L
NO

6. Write and execute a query that retrieves the repid, fname, and
EV

lname columns from the Slspers table.


01
DO

7. Write and execute a query to retrieve the ordnum, partnum, and qty
)2

columns from the Sales table.


R
(C

8. Exit Microsoft SQL Server Management Studio without saving your


statements.
FO

Mastery Builders
SQL Querying: Fundamentals (Second Edition) | 183

Mastery Builder 2-1


Performing a Conditional Search

LY
Activity Time: 15 minutes

ON
Scenario
A sales analysis revealed that most of the books Fuller & Ackerman Publishing sells are priced
between $10 and $30. So the sales manager decides to increase the inventory level for books in this
price range. Now, you need to list the book title, part number, and sale price of these books. The
sales manager also wants information about the representatives who were hired in the past six
months. These representatives were assigned IDs that began with either E or N. The sales manager

E
wants their details along with the list of sales made by them. She also wants the information about

.
the sale quantity made by these representatives if the sale quantity is 400 or above in a single sale.

nc
US
Note: The file C:\094018Data\Performing a Conditional Search\Solution\Performing a
Conditional Search.sql contains one possible solution for these tasks. Try to perform these tasks

,I
on your own before you refer to the solution file.

AT ns
1.
ON
If SQL Server Management Studio is not running, launch it and connect to the

io
server. Open a new query editor, and from the Available Databases list, select

E
Pub1. PL rat
2. In the Object Explorer pane, explore the tables included in the Pub1 database
DU pe
TI

and their structures.


IC
lO

List the book title, part number, and sale price of books that are priced
UA

3.
between $10 and $30. Execute the query.
ica

You should see 47 rows in your results, presented like this.


AL
og
T
7L
NO
EV
01
DO
)2

4. Show sales made by representatives whose IDs start with either E or N.


R
(C

Execute the query.


You should see 63 rows in your results, presented like this.
FO

Mastery Builders
184 | SQL Querying: Fundamentals (Second Edition)

LY
ON
5. Add another condition to the WHERE clause in the query you wrote
for Step 4. Include only those sales where the quantity was at least
400. Execute the query.
This should reduce the results to 7 rows.

Close the Query Editor window without saving your changes.

E
6.

.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Mastery Builders
SQL Querying: Fundamentals (Second Edition) | 185

Mastery Builder 3-1


Working with Functions

LY
Activity Time: 15 minutes

ON
Scenario
A customer is considered a big buyer if he or she purchases 400 or more books in a single purchase.
The sales team wants to identify customers who are big buyers and list the sales made to them
during the first six months of 2017. You are also asked to list the total quantity of books sold to
these customers and the total number of such sales. There are some customer records in the table
with a four-digit customer ID. The human resources manager wants the list of customers with a

E
four-digit customer ID so that she can update the database.

.
nc
Note: The file C:\094018Data\Working with Functions\Solution\Working with Functions.sql

US
contains one possible solution for these tasks. Try to perform these tasks on your own before
you refer to the solution file.

,I
AT ns
1. If SQL Server Management Studio is not running, launch it and connect to the
ON
server. Open a new query editor, and from the Available Databases list, select

io
Pub1.

E
2.
PL rat
List all columns from the Sales table that occurred during the first six months
of 2017, and execute the query.
DU pe
TI

87 rows should be returned in this format.


IC
lO
UA
ica
AL
og
T
7L
NO
EV

Add to the first query by entering another search condition to check that the
01

3.
DO

sale quantity is greater than or equal to 400, and list the output.
)2

10 rows should be returned in this format.


R
(C
FO

Mastery Builders
186 | SQL Querying: Fundamentals (Second Edition)

4. Modify the existing query to list the sum of quantity and count of
rows if the sale quantity is greater than or equal to 400 for the
sales made during the first six months of 2017, and execute the
query.

LY
The following result should be returned.

ON
5. List the details of customers who have a four-digit customer ID.
The following result should be returned.

E
.
nc
US
,I
AT ns
6. Close the Query Editor window without saving changes.
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Mastery Builders
SQL Querying: Fundamentals (Second Edition) | 187

Mastery Builder 4-1


Organizing Data

LY
Activity Time: 15 minutes

ON
Scenario
The sales manager decided to analyze customer demands of titles in the company. To do this, she
needs the total sales of each book present in the database so as to prepare a handout listing the
books in descending order of sales. She also wants the list of representatives who have sold 2000
books or more, sorted in ascending order of total sales quantity.

E
Note: The file C:\094018Data\Organizing Data\Solution\Organizing Data.sql contains one
possible solution for these tasks. Try to perform these tasks on your own before you refer to the

.
nc
solution file.

US
,I
1. If SQL Server Management Studio is not running, launch it and connect to the

AT ns
server. Open a new query editor, and from the Available Databases list, select
Pub1.
ON
io
2. List the part number and sum of quantity from the Sales table and execute the

E
PL rat
query. Group by part number and order by the sum of quantity in descending
order. Eliminate any NULL values in the quantity, and execute the query. You
DU pe
TI

should get 55 rows.


IC
lO

3. Write a new query to list the representatives who have sold more than 2000
UA

books, eliminating NULL values. Sort the list based on the sum of quantity in
ascending order and execute the query. You should get five rows.
ica

4. Close the Query Editor window without saving changes.


AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Mastery Builders
188 | SQL Querying: Fundamentals (Second Edition)

Mastery Builder 5-1


Retrieving Data from Multiple Tables

LY
Activity Time: 15 minutes

ON
Scenario
Management asks you to provide the following information:
• It is the holiday season and marketing has decided to send out discount coupons to
both existing and potential customers. Provide a list that contains the names and
addresses of all customers and potential customers.
• For an organizational internal audit, the auditor wants to review all sales and the

E
names of the representatives responsible for each sale. The auditor asks you to

.
provide a list of sales by order number, customer name, book title, sales

nc
US
representative name, and quantity sold.

,I
Note: The file C:\094018Data\Retrieving Data from Multiple Tables\Solution
\Retrieving Data from Multiple Tables.sql contains one possible solution for

AT ns
these tasks. Try to perform these tasks on your own before you refer to the
solution file.
ON
io
E
1. PL rat
If SQL Server Management Studio is not running, launch it and
connect to the server. Open a new query editor, and from the
DU pe
Available Databases list, select Pub1.
TI

IC
2. Write a query to retrieve the customer name and address from the
lO
UA

customers in both the Customers and Potential_Customers tables.


Display the results in a single result set.
ica

The query should produce 31 rows of data in this format.


AL
og
T
7L
NO
EV
01
DO
)2
R
(C

3. Write a query that lists sales by order number, customer name,


book title, sales representative name, and quantity sold.
FO

The query should produce 98 rows of data in this format.

Mastery Builders
SQL Querying: Fundamentals (Second Edition) | 189

LY
ON
4. Close the Query Editor window without saving changes.

E
.
nc
US
,I
AT ns
ON
io
E
PL rat
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Mastery Builders
190 | SQL Querying: Fundamentals (Second Edition)

Mastery Builder 6-1


Exporting Query Results

LY
Activity Time: 15 minutes

ON
Scenario
Your sales manager wants a list of book titles along with their sale price and
development cost for those books where the development cost is not NULL. The sales
manager wants to receive this list in a file he can use in Excel and also a web-based
application that requires XML data.

E
Note: The file C:\094018Data\Exporting Query Results\Solution\Exporting
Query Results.sql contains one possible solution for these tasks. Try to perform

.
nc
these tasks on your own before you refer to the solution file.

US
,I
1. If SQL Server Management Studio is not running, launch it and

AT ns
connect to the server. Open a new query editor window, and from
the Available Databases list, select Pub1.
ON
io
2. Display book titles along with their respective development cost

E
PL rat
and sale price. Eliminate NULL values in development cost, and list
book titles in ascending order.
DU pe
TI

Execute the query.


IC
3.
lO
UA

4. Save the result as My Books.csv


ica

5. Add options to display the result as an XML document.

6. Save the result as My Books.xml


AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Mastery Builders
Glossary

LY
ON
aggregate function comparison operators
A function that performs calculations on a Symbols used to compare two expressions

E
set of values and returns a single value. or values.

.
nc
US
AND operator concatenation
A logical operator that returns TRUE only A process of combining two string

,I
if both conditions are true. expressions into one string expression.

AT ns
arithmetic operators condition
ON
Symbols used to perform mathematical A search criterion used to retrieve or

io
calculations. manipulate specific information.

E
BETWEEN...AND operator PL rat cross join
An operator that searches for an inclusive A join that displays one row for every
DU pe
TI

range of values specified by the start and possible pairing of rows from two tables.
end values.
IC
CUBE operator
lO
UA

case conversion functions An operator that displays summary rows


Functions that you can use to convert the along with rows displayed by the GROUP
ica

case of a string. BY clause.

character extraction data type


AL
og

The process of extracting certain An attribute that determines the type of


characters from a string value. data that is stored in each column of a
T
7L

table.
NO

client
EV

A computer that has applications to use database


01

the services provided by the server. Data organized and stored on a computer
DO

that can be searched and retrieved by a


column alias computer program.
)2

A meaningful name assigned to the column


heading when the output is displayed. date function
R
(C

A function used to perform calculations on


comment date columns that contain date and time
FO

A non-executable set of words or information.


statements describing the intent of code.
DATEPART() function
A date function that you use to specify the
part of the date you want SQL Server to
192 | SQL Querying: Fundamentals (Second Edition)

return, such as the year, month, day, and join


hour. A process of combining results obtained
from two or more tables into one result
DENSE_RANK and presenting it as the output.
A ranking function that performs the same

LY
task as the RANK function, but assigns keyword
consecutive rank values for each row A reserved word used for defining,
within a specified partition in a result set. manipulating, and accessing data.

ON
DISTINCT keyword leading and trailing spaces
A keyword used to eliminate duplicate Spaces that are present in a column when
values in a list of values. data stored in a column is less than the
maximum number of characters that the
FOR clause used with the XML column can contain.
option

E
A clause used to return query results as an logical operator

.
XML option. An operator that tests for the truth of a

nc
US
condition.
function

,I
A piece of code with a specified name and LOWER
optional parameters that operates as a A function used to convert uppercase

AT ns
single logical unit, performs an action, and characters to lowercase letters.
returns the result.
ON
io
LTRIM
group A function used to remove blank spaces

E
A collection of two or more records
combined into one unit based on one or
PL rat before the values in a column.

NOT operator
DU pe
TI

more columns.
A logical operator that reverses the result
IC
GROUP BY clause of a search condition.
lO
UA

A clause used to group rows based on


grouping columns. NTILE
A ranking function that divides rows in
ica

HAVING clause each partition of a result set into a


A clause used to specify a search condition specified number of groups based on a
AL
og

for a group or an aggregate value. given value and ranks them according to
the partition.
T

IN operator
7L
NO

A logical operator used to check that a NULL


given value matches any values in a list. A value that can be stored in a column
EV

when the value is either unknown or


01

information undefined.
DO

Data that has been processed, interpreted,


)2

organized, structured, or presented in a operators


way that makes it meaningful or useful. Symbols or words used in expressions to
R
(C

manipulate values.
inner join
FO

A join that displays records from two OR operator


tables that have matching values. A logical operator that combines the
output of two conditions and returns
IS NULL clause TRUE when either of the conditions is true.
A clause that checks that a NULL value is
present.

Glossary
SQL Querying: Fundamentals (Second Edition) | 193

ORDER BY self join


A clause used to sort rows displayed in the A join that relates data in a table to itself.
output based on the specified column names.
server
outer join A computer that provides services to other

LY
A join that selects all rows from one table computers on a network.
along with the matching rows from the second
table. sorting
A method of arranging column values

ON
pattern matching displayed in the output in either ascending or
A method of searching for records that match descending order.
a specific combination of characters.
SQL
PIVOT (Structured Query Language) The language you
A relational operator used to rotate column use to communicate with an SQL database.

E
values from one column into multiple columns SQL consists of commands that you can use to

.
in the result set. retrieve, delete, and modify information in a

nc
US
database's tables.
query

,I
A request sent to the database to retrieve SQL statement
information from the database. An instruction written using the required

AT ns
syntax in SQL.
RANK
ON
io
A function that returns a ranking value for stored procedure
each row within a specified partition in a result A database object that consists of one or more

E
set. PL rat
SQL statements. SQL Server compiles stored
procedures in advance for optimized
ranking functions
DU pe
TI

performance.
Functions used to sequentially number the
IC
rows in a result set based on partitioning and string
lO
UA

ordering of the rows. A collection of letters, numbers, or other


characters in any combination.
ROLLUP operator
ica

An operator that displays, in a hierarchical string function


order, summary rows along with the usual rows A function that performs an operation on a
AL
og

displayed by the GROUP BY clause. string input value and returns a string or
numeric value.
T

ROW_NUMBER
7L
NO

One of the ranking functions that use SUBSTRING


sequential numbering to rank each row in the A function used to extract characters from a
EV

result set. A ranking function that returns a given string.


01

sequential number for each row within a


DO

specified partition in the result set. syntax


)2

The expected form of an instruction with


RTRIM clauses and placeholders for the actual
R
(C

A function used to remove blank spaces after elements that will be used in the instruction.
the values in a column.
FO

table
SELECT statement A collection of related information arranged in
An SQL statement used to retrieve information rows and columns.
from tables present in the database.

Glossary
194 | SQL Querying: Fundamentals (Second Edition)

table alias
A name provided to a table so that the table
can be referred to by the alias name.

trim functions

LY
Functions that enable you to remove the
leading and trailing blank spaces that are part
of a string of characters.

ON
UNION operator
An operator used to combine the result of two
or more queries into a single output.

UNPIVOT
A relational operator used to convert pivoted

E
columns to column values of a single column.

.
nc
US
UPPER
A function used to convert lowercase

,I
characters to uppercase letters.

AT ns
WHERE clause
A clause used to include conditions.
ON
io
wildcard

E
PL rat
Characters used to search for patterns within
data.
DU pe
TI

IC
lO
UA
ica
AL
og
T
7L
NO
EV
01
DO
)2
R
(C
FO

Glossary
Index

LY
ON
E
A objects 2

.
overview 2

nc
US
aggregate functions 82
data sorting 100
AND operator 42
data types

,I
arithmetic operators 39
date/time 75

AT ns
overview 25
B ON SUBSTRING-supported 93
BETWEEN...AND operator 56 date functions

io
converting 76

E
C PL rat overview 73
SMALLDATETIME 77
case conversion functions 90 DATEPART() function 77
DU pe
TI

character extraction 92 default column headings 40


IC
clauses DENSE_RANK function 105
lO

FOR XML 170 DISTINCT keyword 83


UA

GROUP BY 113, 114


HAVING 120
E
ica

IS NOT NULL 58
IS NULL 58 EXCEPT operator 142
eXtensible Markup Language, See XML
AL

ORDER BY 100
og

WHERE 37
T

client/server architecture 4 F
7L
NO

clients 4
FOR XML clause 170
column aliases 40
EV

functions
comments 27
01

aggregate 82
comparison operators 39
DO

case conversion 90
concatenation 93
)2

CAST () 76
conditional searches 36
CONVERT() 76
conditions 36
R

date 73
(C

cross joins 145


DATEPART() 77
CUBE operator 123
DENSE_RANK 105
FO

CUBE subclause 115


GROUPING_ID 115
LOWER 90
D LTRIM 92
databases nesting 78
196 | SQL Querying: Fundamentals (Second Edition)

NTILE 107 L
overview 72
leading and trailing spaces 91
RANK 105
LIKE operator 64
ranking 104
logical operators 41, 42
ROW_NUMBER 106, 107

LY
LOWER function 90
RTRIM 92
string 88
SUBSTRING 92 M
TRIM 92 multiple conditional operators 38

ON
types of 72 multiple table joins 150
UPPER 90
N
G
NOT operator 42
GROUP BY clause NTILE function 107

E
ordering 114 NULL 45, 57

.
overview 113

nc
US
specifications for 114
GROUPING_ID function 115
O

,I
grouping sets 115 operators
groups 113 AND 42

AT ns
ON arithmetic 39
BETWEEN...AND 56
H

io
comparison 39
HAVING clause 120 CUBE 123

E
PL rat EXCEPT 142
I IN 57
DU pe
TI

INTERSECT 142
information 8
IC
LIKE 64
inner joins 146
lO

logical 41, 42
IN operator 57
UA

multiple conditional 38
INTERSECT operator 142
NOT 42
IS NOT NULL clause 58
ica

OR 42
IS NULL clause 58, 59
PIVOT 128
precedence 44
AL
og

J ROLLUP 123
T

joins single conditional 38


7L
NO

cross 145 SQL Server 38


inner 146 UNION 136
EV

multiple table 150 UNPIVOT 129


01

outer 148 ORDER BY clause 100


DO

overview 145 OR operator 42


)2

self 149 outer joins 148


R
(C

K P
FO

keywords pattern matching 64


DISTINCT 83 PIVOT operator 128
overview 83
TOP n 107 Q
qualified names 147

Index
SQL Querying: Fundamentals (Second Edition) | 197

queries U
overview 14
UNION operator 136
processing order 14
UNPIVOT operator 129
saving 23
UPPER function 90
Query Editor 9

LY
R W
WHERE 41
RANK function 105
WHERE clause 37

ON
ranking functions 104
wildcards 63, 64
ROLLUP operator 123
windows
ROLLUP subclause 115
Query Editor 9
ROW_NUMBER function 106, 107

S X

E
XML 170
SELECT statement

.
nc
US
optional clauses 17
overview 14

,I
self joins 149
servers 4

AT ns
single conditional operators 38
sort 100
ON
io
spaces 91
SQL

E
arithmetic operators 40
command groups 7
PL rat
DU pe
TI

keywords 83
operators 38
IC
overview 7
lO
UA

pronunciation 7
Server data types 26
ica

wildcards 63
stored procedures 27
string functions 88
AL
og

strings 88
T

Structured Query Language, See SQL


7L

subclauses
NO

CUBE 115
EV

ROLLUP 115
01

SUBSTRING function 92
DO

syntax
)2

notation 17
overview 15
R
(C

T
FO

table aliases 149


tables 3
text data formats 166
TOP n keyword 107
trim functions 92

Index
FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY
FO
R
(C
EV
)2 AL
01
7L UA
DO og
NO ica TI
T lO ON
DU pe
PL rat US
IC io
AT ns E
E ,Inc
.
ON
LY

You might also like