100% found this document useful (2 votes)
780 views78 pages

Official Microsoft Learning Product 20461C Querying Microsoft SQL Server

Uploaded by

Bogdan Bgd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (2 votes)
780 views78 pages

Official Microsoft Learning Product 20461C Querying Microsoft SQL Server

Uploaded by

Bogdan Bgd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 78

1-1

Module 1
Introduction to Microsoft SQL Server 2014
Contents:
Module Overview 1-1

Lesson 1: The Basic Architecture of SQL Server 1-2

Lesson 2: SQL Server Editions and Versions 1-5

Lesson 3: Getting Started with SQL Server Management Studio 1-7

Lab: Working with SQL Server 2014 Tools 1-13

Module Review and Takeaways 1-16

Module Overview
Before beginning to learn how to write queries with Microsoft SQL Server 2014, it is useful to understand
the overall SQL Server database platform, including its basic architecture, the various editions available for
SQL Server 2014, and the tools a query writer will use. This module will also prepare you to use SQL Server
Management Studio, SQL Server's primary development and administration tool, to connect to SQL Server
instances and create, organize, and execute queries.

Objectives
After completing this module, you will be able to:

• Describe the architecture of SQL Server 2014.


• Describe the editions of SQL Server 2014.

• Work with SQL Server Management Studio.


1-2 Introduction to Microsoft SQL Server 2014

Lesson 1
The Basic Architecture of SQL Server
In this lesson, you will learn about the basic architecture and concepts of Microsoft SQL Server 2014. You
will learn how instances, services, and databases interact, and how databases are structured. This will help
prepare you to begin working with SQL Server queries in upcoming modules.

Lesson Objectives
After completing this lesson, you will be able to describe:

• Relational databases and, specifically, the role and structure of SQL Server databases.

• The sample database used in this course.

• Client server databases.

• The structure of Transact-SQL queries.

Relational Databases
Typical relational databases comprise of several
tables that relate to each other. Each table typically
represents a class of entity which might be
something tangible, such as an employee, or
something intangible, such as a sales order. In this
example, a very simple database might have an
employee table and an order table, with employees
able to place orders.
We find meaningful information by using joins,
which are possible when two tables share values. To
continue the example, each order has an employee
ID for the person who placed the order. It is also
possible to join several tables. Let’s extend the example and add customers. Now each order also contains
a customer ID that can be used to link it to the new customer table. We can now display an employee and
their customers by joining all three tables. It is not necessary to display any order information, we can just
use this as a bridge between the other two tables.

Databases in SQL Server are containers for data and objects, including tables, views, stored procedures,
user accounts, and other management objects. An SQL Server database is always a single logical entity,
backed by multiple physical files.

SQL Server supports two types of databases—system and user. TSQL, the sample database you will be
using to write queries, is a user database. SQL Server's system databases include:

• master, the system configuration database.

• msdb, the configuration database for the SQL Server Agent service and other system services.

• model, the template for new user databases.

• tempdb, used by the database engine to store temporary data such as work tables. This database is
dropped and recreated each time SQL Server restarts. Never store anything you need to depend on in
it!

• Resource, a hidden system configuration database that provides system objects to other databases.
Querying Microsoft® SQL Server® 1-3

Database administrators and developers can create user databases to hold data and objects for
applications. You connect to a user database to execute your queries. You will need security credentials to
log on to SQL Server and a database account with permissions to access data objects in the database.

About the Course Sample Database


In this course, most of your queries will be written
against a sample database named TSQL2014. This is
designed as a small, low-complexity database
suitable for learning to write T-SQL queries. It
contains several types of objects:

• User-defined schemas, which are containers for


tables and views. You will learn about schemas
later in this course.

• Tables, which relate to other tables via foreign


key constraints.

• Views, which display aggregated information.

The TSQL2014 database is modeled to resemble a sales-tracking application for a small business. Some of
the tables you will use include:

• Sales.Orders, which stores data typically found in the header of an invoice (order ID, customer ID,
order date, and so on).
• Sales.OrderDetails, which stores transaction details about each order (parent order ID, product ID, unit
price, and so on).

• Sales.Customers, which stores information about customers (company name, contact details, and so
on).

• HR.Employees, which stores information about the company's employees (name, birthdate, hire date,
and so on).
Other tables are supplied to add context, such as additional product information, to these tables.

Client Server Databases


SQL Server is a client server system. This means that
the client software, which includes SQL Server
Management Studio and Visual Studio, is separate
from the SQL Server database engine.

When client applications send requests to the


database engine as T-SQL statements, SQL Server
performs all file, memory, and processor utilization
on the client's behalf. Clients never directly access
database files, unlike in desktop database
applications.

In the course, the client and server are running on


the same virtual machine, but in most environments
the client software is running on a separate machine to the database engine.
1-4 Introduction to Microsoft SQL Server 2014

Whether the database engine is local, or you are connecting to it over a network, it makes no difference
to the T-SQL code that we write. On the logon screen, you just need to specify the server that you are
connecting to.

Because you can connect to instances of SQL Server over a network, you can also refer to other databases
in a T-SQL script. To do this, you need to refer to a table, or other object, using its four-part name. This
takes the format of Instance.Database.Schema.Object. For example, the orders table in the dbo
schema, in the sales database on the MIA-SQL server’s default instance, would be referred to as MIA-
SQL.sales.dbo.orders. To connect to a remote server in a T-SQL script, you should set up the remote
instance as a linked server. In T-SQL you can add a linked server using the sp_addlinkedserver stored
procedure. Although there are many arguments that can be supplied, in its most straightforward, default,
use you could connect to the server in the previous example using the statement exec
sp_addlinkedserver n’MIA-SQL’.

Queries
T-SQL is a set-based language. This means that it
does not go through records row-by-row, but
instead pulls data from the server one table at a
time, or a subset of the table if it is filtered. This
makes SQL Server very efficient to deal with large
volumes of data, although writing a seemingly
straightforward query to add five percent to the
preceding row is quite complicated. SQL Server
does not typically consider what row a record is on,
it looks at the data within that row.

T-SQL scripts are stored in script files with an .sql


extension. These can be further organized into
projects.

Inside each file, the script can be ordered into batches, that are marked with the word GO at the end. It is
important to realize that each batch is run in its entirety before the next one is started. This is important if
things need to happen in a certain order. For example, if you had a script that created a table, and then
populated it with data, it would fail without batches. SQL Server would analyze the batch and reject the
statement that populated the table because the table does not currently exist. If you write the script to
create the table, type GO, and then write the script to populate the table. It will succeed because the table
exists when SQL Server assesses the second batch.
Querying Microsoft® SQL Server® 1-5

Lesson 2
SQL Server Editions and Versions
In this lesson, you will learn about the editions and versions of Microsoft SQL Server. You will learn which
editions of SQL Server 2014 are available, their distinguishing features, and which editions would be best
to use when planning a new deployment.

Lesson Objectives
After completing this lesson, you will be able to describe:

• The versions of SQL Server.

• The editions of SQL Server 2014.

• The choices when deploying SQL Server databases to the cloud.

SQL Server Versions


SQL Server 2014 is the latest version in the history
of SQL Server development. Originally developed
for the OS/2 operating system (versions 1.0 and
1.1), SQL Server versions 4.21 and later moved to
the Windows® operating system.

SQL Server's engine received a major rewrite for


version 7.0, and subsequent versions have
continued to improve and extend SQL Server's
capabilities, from the workgroup to the largest
enterprises.

Note: Although its name might suggest it,


SQL Server 2008 R2 is not a service pack for SQL Server 2008. It is an independent version
(number 10.5) with enhanced multiserver management capabilities, as well as new business
intelligence (BI) features.

Question: Have you worked with any versions of SQL Server prior to SQL Server 2012?
1-6 Introduction to Microsoft SQL Server 2014

SQL Server Editions


SQL Server offers several editions providing
different feature sets that target various business
scenarios. In the SQL Server 2012 release, the
number of editions was streamlined from previous
versions. The main editions are:

• Enterprise, which is the flagship edition. It


contains all of SQL Server 2014's features,
including BI services and support for
virtualization.
• Standard, which includes the core database
engine, as well as core reporting and analytics
capabilities. However, it supports fewer
processor cores and does not offer all the availability, security, and data warehousing features found
in Enterprise.

• Business Intelligence, which is a new edition. It provides the core database engine, full reporting
and analytics capabilities, and full BI services. However, like the Standard edition, it supports fewer
processor cores and does not offer all the availability, security, and data warehousing features.

SQL Server 2014 also offers other editions, such as Parallel Data Warehouse, Web, Developer, and Express,
each targeted for specific use cases.

This course uses core database engine features found in all editions.

SQL Server in the Cloud


SQL Server does not have to run locally, but can
also operate as a cloud-based database, taking two
forms. SQL Server could be running on a cloud-
based server that your organization has provisioned
and integrated with your infrastructure. If this is the
case, and the infrastructure is properly set up, you
should treat it as an instance of SQL Server on your
network. In fact, this might be the case and you are
completely unaware of it.

The other alternative is the Microsoft Azure™ SQL


Database. This allows you to provision databases
that use SQL Server technology in the cloud, but
without having to provision and configure a whole virtual machine. There are some limitations to T-SQL
when using the Microsoft Azure SQL Database, but nothing that will affect this course.

Additional Reading: For more information on the use of T-SQL in Microsoft Azure SQL
Databases, go to the MSDN article Transact-SQL Support (Microsoft Azure SQL Database):
http://go.microsoft.com/fwlink/?LinkID=394805
Querying Microsoft® SQL Server® 1-7

Lesson 3
Getting Started with SQL Server Management Studio
In this lesson, you will learn how to use SQL Server Management Studio (SSMS) to connect to an instance
of SQL Server, explore the databases contained in the instance, and work with script files containing

T-SQL queries.

Lesson Objectives
After completing this lesson, you will be able to:

• Start SSMS.

• Use SSMS to connect to on-premises SQL Server instances.

• Explore a SQL Server instance using Object Explorer.

• Create and organize script files.

• Execute T-SQL queries.


• Use Books Online.

Starting SSMS
SSMS is an integrated management, development,
and querying application with many features for
exploring and working with your databases. SSMS is
based on the Visual Studio shell. If you have
experience with Visual Studio, you will likely feel
comfortable with SSMS.
To start SSMS, you may:

• Use its shortcut on the Windows Start


screen.
• Enter its filename, SSMS.EXE, in a
command prompt window.

By default, SSMS will display a Connect to Server dialog box you can use to specify the server (or instance)
name and your security credentials. If you use the Options button to access the Connection Properties
tab, you can also supply the database to which you wish to connect. However, you can explore many
SSMS features without initially connecting to an SQL Server instance, so you may also cancel the Connect
to Server box and link to a server later.

After SSMS is running, you may wish to explore some of its settings, such as those found in the Tools,
Options box. SSMS can be customized in many ways, such as setting a default font, enabling line numbers
for scripts, and controlling the behavior of its many windows.

For more information on using SQL Server Management Studio, go to Use SQL Server Management
Studio in Books Online:
Use SQL Server Management Studio
http://go.microsoft.com/fwlink/?LinkID=402707
1-8 Introduction to Microsoft SQL Server 2014

Connecting to SQL Server


To connect to an instance of SQL Server, you need
to specify several items, no matter which tool you
use:

• The name of the instance to which you want to


connect in the form: hostname\instancename.
For example, MIA-SQL\Proseware would
connect to the Proseware instance on the
Windows server named MIA-SQL. If you are
connecting to the default instance, you may
omit the instance name. For Microsoft Azure,
the server name is in four parts in the form:
<host>.database.windows.net.

• The name of the database. If you do not specify this, you will be connected to the database
designated as your account's default by the database administrator, or to the master database if no
default has been specifically assigned. In Microsoft Azure, it is important to choose the correct
database as you may not change connections between user databases. You would need to disconnect
and reconnect to the desired database.

• The authentication mechanism required by the server. This may be Windows Authentication, in which
your Windows network credentials will be passed to SQL Server (no entry required), or SQL Server
Authentication, in which a username and password for your account must be created by a database
administrator (you enter them at connection time). SQL Server Authentication is the only mechanism
supported by Microsoft Azure.

Question: Which authentication method do you use to log on to SQL Server in your
organization?

Working with Object Explorer


Object Explorer is a graphical tool for managing
SQL Server instances and databases. It is one of
several SSMS window panes available from the View
menu. Object Explorer provides direct interaction
with most SQL Server data objects, such as tables,
views, and procedures. Right-clicking an object,
such as a table, will display context-sensitive
commands, including query and script generators
for object definitions.

Note: Any operation performed in SSMS


requires appropriate permissions granted by a
database administrator. Being able to see an object or command does not necessarily imply
permission to use the object or issue the command.

SQL Server query writers most commonly use Object Explorer to learn about the structure and definition
of the data objects they want to use in their queries. For example, to learn the names of columns in a
table, you follow these steps:

1. Connect to the SQL Server, if necessary.


Querying Microsoft® SQL Server® 1-9

2. Expand the Databases folder to expose the list of databases.

3. Expand the relevant database to expose the Tables folder.

4. Expand the Tables folder to view the list of tables in the database.

5. Locate the table you are interested in and expand it to find the Columns folder. The Columns folder
will display the names, data types, and other information about the columns that make up the table.
You can even drag the name of a database, table, or column into the query window to have it
entered and avoid typing it yourself.

Note: Selecting objects in the Object Explorer pane does not change any connections
made in other windows.

Working with Script Files and Projects


SSMS allows you to create and save T-SQL code in
text files, typically given an .sql file extension. Like
other Windows applications that open, edit, and
save files, SSMS provides access to file management
through the File menu, as well as standard toolbar
buttons.
In addition to directly manipulating individual script
files, SSMS provides a mechanism for initially saving
groups of files together and for opening, saving,
and closing them together. This mechanism uses
several conceptual layers to work with T-SQL script
files and related documents, using the Solution
Explorer pane to display and control them:

Object Parent Description

Solution None Top-level container for projects. Stored as a text file with an .ssmssln
extension, which references components contained within it. May contain
multiple projects. Displayed at the top of the object hierarchy in Solution
Explorer.

Project Solution Container for T-SQL scripts (called queries), stored database connection
metadata, and miscellaneous files. Stored as a text file with an .ssmssqlproj
extension, which references component scripts and other files.

Script Project T-SQL script file with an .sql extension. The core item of work in SSMS.

The benefits of using scripts organized in projects and solutions include the ability to immediately open
multiple script files in SSMS. You can open the solution or project file from within SSMS or Windows
Explorer.

To create a new solution, click the File menu and click New Project. (There is no “New Solution”
command.) Specify a name for the initial project, its parent solution, and whether you want the project to
be stored in a subfolder below the solution file in the location you indicate. Click OK to create the parent
objects.

To interact with Solution Explorer, open the pane (if necessary) from the View menu. To create a new
script that will be stored as part of the project, right-click the Queries folder in the project and click New
Query.
1-10 Introduction to Microsoft SQL Server 2014

Note: Using the New Query toolbar button or the new query commands on the File menu
will create a new script temporarily stored with the solution in the Miscellaneous Files folder. If
you wish to move an existing open query document into a solution currently open in Solution
Explorer, you will need to save the file. You can then drag the query into the project tree to save
it in the Queries folder. This will make a copy of the script file and place it in the solution.

It is important to remember to save the solution when exiting SSMS or opening another solution to
preserve changes to the file inventory. Saving a script using the Save toolbar button or the Save
<Queryname>.sql command on the File menu will only save changes to the current script file contents. To
save the entire solution and all its files, use the Save All command on the File menu or when prompted to
save the .ssmssln and .ssmssqlproj files on exit.

Executing Queries
To execute T-SQL code in SSMS, you first need to
open the .sql file that contains the queries, or type
your query into a new query window. Then decide
how much of the code in the script is to be
executed as follows:
• Select the code you wish to execute.

• If nothing is selected, SSMS will execute the


entire script, which is the default behavior.
When you have decided what you wish to execute,
you can run the code by doing one of the
following:

• Clicking the Execute button on the SSMS toolbar.

• Clicking the Query menu, then clicking Execute.

• Pressing the F5 key, the Alt+X keyboard shortcut, or the Ctrl+E keyboard shortcut.
By default, SSMS will display your results in a new pane of the query window. The location and
appearance of the results can be changed in the Options box, accessible from the Tools menu. To toggle
the results display and return to a full-screen T-SQL editor, use the Ctrl+R keyboard shortcut.
SSMS provides several formats for the display of query results:

• Grid, which is a spreadsheet-like view of the results, with row numbers and columns you can resize.
You can use Ctrl+D to select this before executing a query.
• Text, which is a Windows Notepad-like display that pads column widths. You can use Ctrl+T to select
this before executing a query.

• File, which allows you to directly save query results to a text file with an .rpt extension. Executing the
query will prompt a results file location. The file may then be opened by any application that can read
text files, such as Windows Notepad and SSMS. You can use Ctrl+Shift+F to select this before
executing a query.
Querying Microsoft® SQL Server® 1-11

Using Books Online


Books Online (often abbreviated BOL) is the
product documentation for SQL Server. BOL
includes helpful information on SQL Server's
architecture and concepts, as well as syntax
reference for T-SQL. BOL can be accessed from the
Help menu in SSMS. In a script window, context-
sensitive help for T-SQL keywords is available by
selecting the keyword and pressing Shift+F1.

Books Online can be browsed directly on


Microsoft's website:

Books Online for SQL Server 2014


http://go.microsoft.com/fwlink/?LinkID=402708
Note: Before SQL Server 2014, SQL Server provided the option to install Books Online
locally during SQL Server setup. In SQL Server 2014, Books Online does not ship with the product
installation media, so must be downloaded and installed separately.

The first time Help is invoked, you will be prompted to specify whether you wish to view Books Online
content online or locally.

For detailed instructions on how to download, install, and configure Books Online for local offline use, go
to the topic Get Started with Product Documentation for SQL Server:

Get Started with Product Documentation for SQL Server


http://go.microsoft.com/fwlink/?LinkID=402709

Demonstration: Introducing Microsoft SQL Server 2014


In this demonstration, you will see how to:
• Use SSMS to connect to an on-premises instance of SQL Server.

• Explore databases and other objects.

• Work with T-SQL scripts.

Demonstration Steps
Use SSMS to connect to an on-premises instance of SQL Server 2014
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. Run D:\Demofiles\Mod01\Setup.cmd as an administrator.


3. Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using
Windows authentication.
Explore databases and other objects
1. If the Object Explorer pane is not visible, click View and click Object Explorer.

2. Expand the Databases folder to see the list of databases.

3. Expand the AdventureWorks database.

4. Expand the Tables folder.


1-12 Introduction to Microsoft SQL Server 2014

5. Expand the Sales.Customer table.

6. Expand the Columns folder.

7. Show the list of columns, and point out the data type information for the ModifiedDate column.
Work with T-SQL scripts
1. If the Solution Explorer pane is not visible, click View and click Solution Explorer. Initially, it will be
empty.

2. Click the File menu, click New, click Project.

3. In the New Project box, under Installed Templates, click SQL Server Management Studio
Projects.

4. In the middle pane, click SQL Server Scripts.

5. In the Name box, type Module 1 Demonstration.

6. In the Location box, type or browse to D:\Demofiles\Mod01.

7. Point out the solution name, then click OK.

8. In the Solution Explorer pane, right-click Queries, then click New Query.

9. Type the following T-SQL code:

USE AdventureWorks;
GO
SELECT CustomerID, AccountNumber
FROM Sales.Customer;

10. Select the code and click Execute on the toolbar.


11. Point out the results pane.

12. Click File, and then click Save All.

13. Click File, and then click Close Solution.

14. Click File, click Recent Projects and Solutions, and then click Module 1 Demonstration.ssmssln.

15. Point out the Solution Explorer pane.

16. Close SQL Server Management Studio without saving any files.
Querying Microsoft® SQL Server® 1-13

Lab: Working with SQL Server 2014 Tools


Scenario
The Adventure Works Cycles Bicycle Manufacturing Company has adopted SQL Server 2014 as its
relational database management system of choice. You are an information worker who will be required to
find and retrieve business data from several SQL Server databases. In this lab, you will begin to explore the
new environment and become acquainted with the tools for querying SQL Server.

Objectives
After completing this lab, you will be able to:

• Use SQL Server Management Studio.

• Create and organize T-SQL scripts.

• Use SQL Server Books Online.

Estimated Time: 30 minutes

Virtual machine: 20461C-MIA-SQL


User name: ADVENTUREWORKS\Student

Password: Pa$$w0rd

Exercise 1: Working with SQL Server Management Studio


Scenario
You have been tasked with writing queries for SQL Server. Initially, you would like to become familiar with
the development environment and, therefore you have decided to explore SQL Server Management
Studio and configure the editor for your use.

The main tasks for this exercise are as follows:


1. Open Microsoft SQL Server Management Studio

2. Configure the Editor Settings

 Task 1: Open Microsoft SQL Server Management Studio


1. Start SSMS, but do not connect to an instance of SQL Server.
2. Close the Object Explorer and Solution Explorer windows.

3. Using the View menu, show the Object Explorer and Solution Explorer windows in SSMS.

 Task 2: Configure the Editor Settings


1. On the Tools menu, choose Options to open the Options window in SSMS and change the font size
to 14 for the text editor.

2. Change several additional settings in the Options window:

o Disable IntelliSense.

o Change the tab size to 6 spaces for T-SQL.

o Enable the option to include column headers when copying the result from the grid. Look under
Query Results, SQL Server, Results to Grid for the check box Include column headers when
copying or saving the results.
1-14 Introduction to Microsoft SQL Server 2014

Results: After this exercise, you should have opened SSMS and configured editor settings.

Exercise 2: Creating and Organizing T-SQL scripts


Scenario
Usually you will organize your T-SQL code in multiple query files inside one project. You will practice how
to create a project and add different query files to it.

The main tasks for this exercise are as follows:

1. Create a Project

2. Add an Additional Query File

3. Reopen the Created Project

 Task 1: Create a Project


1. Create a new project called MyFirstProject and store it in the folder D:\Labfiles\Lab01\Starter.

2. Add a new query file to the created project and name it MyFirstQueryFile.sql.
3. Save the project and the query file by clicking the Save All option.

 Task 2: Add an Additional Query File


1. Add an additional query file called MySecondQueryFile.sql to the created project and save it.

2. Open Windows Explorer, navigate to the project folder, and observe the created files in the file
system.

3. Back in SSMS, using Solution Explorer, remove the query file MySecondQueryFile.sql from the created
project. (Choose the Remove option, not Delete.)
4. Again, look in the file system. Is the file MySecondQueryFile.sql still there?

5. Back in SSMS, remove the file MyFirstQueryFile.sql and choose the Delete option. Observe the files in
Windows Explorer. What is different this time?

 Task 3: Reopen the Created Project


1. Save the project, close SSMS, reopen SSMS, and open the project MyFirstProject.

2. Drag the query file MySecondQueryFile.sql from Windows Explorer to the Queries folder under the
project MyFirstProject in Solution Explorer. (Note: If the Solution Explorer window is not visible,
enable it as you did in exercise 1).

3. Save the project.

Results: After this exercise, you should have a basic understanding of how to create a project in SSMS and
add query files to it.

Exercise 3: Using Books Online


Scenario
To be effective in your upcoming training and exercises, you will practice how to use Books Online to
efficiently check for T-SQL syntax.

The main tasks for this exercise are as follows:


Querying Microsoft® SQL Server® 1-15

1. Launch Books Online

2. Use Books Online

 Task 1: Launch Books Online


1. Launch Manage Help Settings from the Windows Start screen.

2. Configure Books Online to use the online option, not local help.

 Task 2: Use Books Online


1. Use Books Online to find information about SQL Server 2014 tools and add-in components.

Results: After this exercise, you should have a basic understanding of how to find information in Books
Online.
1-16 Introduction to Microsoft SQL Server 2014

Module Review and Takeaways


Review Question(s)
Question: Can an SQL Server database be stored across multiple instances?

Question: If no T-SQL code is selected in a script window, which lines will be run when you
click the Execute button?

Question: What does an SQL Server Management Studio solution contain?


3-1

Module 3
Writing SELECT Queries
Contents:
Module Overview 3-1

Lesson 1: Writing Simple SELECT Statements 3-2

Lesson 2: Eliminating Duplicates with DISTINCT 3-6

Lesson 3: Using Column and Table Aliases 3-10

Lesson 4: Writing Simple CASE Expressions 3-14

Lab: Writing Basic SELECT Statements 3-17

Module Review and Takeaways 3-22

Module Overview
The SELECT statement is used to query tables and views. You may also perform some manipulation of the
data with SELECT before returning the results. It is likely that you will use the SELECT statement more than
any other single statement in T-SQL. This module introduces you to the fundamentals of the SELECT
statement, focusing on queries against a single table.

Objectives
After completing this module, you will be able to:

• Write simple SELECT statements.


• Eliminate duplicates using the DISTINCT clause.

• Use column and table aliases.

• Write simple CASE expressions.


3-2 Writing SELECT Queries

Lesson 1
Writing Simple SELECT Statements
In this lesson, you will learn the structure and format of the SELECT statement, as well as enhancements
that will add functionality and readability to your queries.

Lesson Objectives
After completing this lesson, you will be able to:

• Understand the elements of the SELECT statement.

• Write simple single-table SELECT queries.

• Eliminate duplicate rows using the DISTINCT clause.


• Add calculated columns to a SELECT clause.

Elements of the SELECT Statement


The SELECT and FROM clauses are the primary
focus of this module. You will learn more about the
other clauses in later modules of this course.
However, your understanding of the order of
operations in logical query processing, from earlier
in the course, will remain important for how you
understand the proper way to write SELECT queries.

Remember that the FROM, WHERE, GROUP BY, and


HAVING clauses will have been evaluated before
the contents of the SELECT clause are processed.
Therefore, elements you write in the SELECT clause,
especially calculated columns and aliases, will not
be visible to the other clauses.

Additional information on SELECT elements can be found at:

SELECT (Transact-SQL)
http://go.microsoft.com/fwlink/?LinkID=402716
Querying Microsoft® SQL Server® 3-3

Retrieving Columns from a Table or View


The SELECT clause specifies the columns from the
source table(s) or view(s) that you want to return as
the result set of the query. In addition to columns
from the source table, you may add others in the
form of calculated expressions.

The FROM clause specifies the name of the table or


view that is the source of the columns in the SELECT
clause. To avoid errors in name resolution, it is a
best practice to specify both the schema and object
name of the table, in the form SCHEMA.OBJECT,
such as Sales.Customers.

If the table or view name contains irregular


characters, such as spaces or other special characters, you will need to delimit, or enclose, the name. T-
SQL supports the use of the ANSI standard double quotes "Sales Order Details" and the SQL Server-
specific square brackets [Sales Order Details].

End all statements with a semicolon (;) character. In SQL Server 2014, semicolons are an optional
terminator for most statements. However, future versions will require its use. For those current usages
when a semicolon is required, such as some common table expressions (CTEs) and some Service Broker
statements, the error messages returned for a missing semicolon are often cryptic. Therefore, you should
adopt the practice of terminating all statements with a semicolon.

Displaying Columns
To display columns in a query, you need to create a
comma-delimited column list. The order of the
columns in your list will determine their display in
the output, regardless of the order in which they
are defined in the source table. This gives your
queries the ability to absorb changes that others
may make to the structure of the table, such as
adding or reordering the columns.
T-SQL supports the use of the asterisk, or “star”
character (*) to substitute for an explicit column list.
This will retrieve all columns from the source table.
While suitable for a quick test, avoid using the * in
production work, as changes made to the table will cause the query to retrieve all current columns in the
table’s current defined order. This could cause bugs or other failures in reports or applications expecting a
known number of columns returned in a defined order.

By using an explicit column list in your SELECT clause, you will always get the desired results, as long as
the columns exist in the table. If a column is dropped, you will receive an error that will help identify the
problem and fix your query.
3-4 Writing SELECT Queries

Using Calculations in the SELECT Clause


In addition to retrieving columns stored in the
source table, a SELECT statement can perform
calculations and manipulations. Calculations can
manipulate the source column data and use built-in
T-SQL functions, which you will learn about later in
this course.

Since the results will appear in a new column,


repeated once per row of the result set, calculated
expressions in a SELECT clause must be scalar. In
other words, they must return only a single value.

Calculated expressions may operate on other


columns in the same row, on built-in functions, or a
combination of the two:

Calculated Expression
SELECT unitprice, qty, (unitprice * qty)
FROM Sales.OrderDetails;

The results appear as follows:

unitprice qty
--------------------- ------ ---------------------
14.00 12 168.00
9.80 10 98.00
34.80 5 174.00
18.60 9 167.40

Note that the new calculated column does not have a name returned with the results. To provide a name,
you use a column alias, which you will learn about later in this module.

To use a built-in T-SQL function on a column in the SELECT list, you pass the name of the column to the
function as an input:

Passing a Column
SELECT empid, lastname, hiredate, YEAR(hiredate)
FROM HR.Employees;

The results:

empid lastname hiredate


----------- -------------------- ----------------------- -------
1 Davis 2002-05-01 00:00:00.000 2002
2 Funk 2002-08-14 00:00:00.000 2002
3 Lew 2002-04-01 00:00:00.000 2002

You will learn more about date functions, as well as others, later in this course. The use of YEAR in this
example is provided only to illustrate calculated columns.

Note: Not all calculations will be recalculated for each row. SQL Server may calculate a
function’s result once at the time of query execution, and reuse the value for each row. This will
be discussed later in the course.
Querying Microsoft® SQL Server® 3-5

Demonstration: Writing Simple SELECT Statements


In this demonstration, you will see how to:

• Use simple SELECT queries

Demonstration Steps
Use Simple SELECT Queries

1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. Run D:\Demofiles\Mod03\Setup.cmd as an administrator.

3. Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using
Windows authentication.
4. Open the Demo.ssmssln solution in the D:\Demofiles\Mod03\Demo folder.

5. If the Solution Explorer pane is not visible, on the View menu, click Solution Explorer.

6. Open the 11 – Demonstration A.sql script file.

7. Follow the instructions contained within the comments of the script file.

8. Keep SQL Server Management Studio open for the next demonstration.
3-6 Writing SELECT Queries

Lesson 2
Eliminating Duplicates with DISTINCT
T-SQL queries may display duplicate rows, even if the source table has a key column enforcing
uniqueness. Typically, this is the case when you retrieve only a few of the columns in a table. In this lesson,
you will learn how to eliminate duplicates using the DISTINCT clause.

Lesson Objectives
In this lesson, you will learn to:

• Understand how T-SQL query results are not true sets and may include duplicates.

• Understand how DISTINCT may be used to remove duplicate rows from the SELECT results.

• Write SELECT DISTINCT clauses.

SQL Sets and Duplicate Rows


While the theory of relational databases calls for
unique rows in a table, in practice T-SQL query
results are not true sets. The rows retrieved by a
query are not guaranteed to be unique, even when
they come from a source table that uses a primary
key to differentiate each row. Nor are the rows
guaranteed to be returned in any particular order.
You will learn how to address this with ORDER BY
later in this course.
Add to this the fact that the default behavior of a
SELECT statement is to include the keyword ALL,
and you can begin to see why duplicate values
might be returned by a query, especially when you include only some of the columns in a table (and omit
the unique columns).

For example, consider a query that retrieves country names from the Sales.Customers table:

Select Query
SELECT country
FROM Sales.Customers;

A partial result shows many duplicate country names, which at best is too long to be easy to interpret. At
worst, it gives a wrong answer to the question: “How many countries are represented among our
customers?”

country
-------
Germany
Mexico
Mexico
UK
Sweden
Germany
Germany
France
UK
Querying Microsoft® SQL Server® 3-7

Austria
Brazil
Spain
France
Sweden
...
Germany
France
Finland
Poland
(91 row(s) affected)

The reason for this output is that, by default, a SELECT clause contains a hidden default ALL statement:

ALL Statement
SELECT ALL country
FROM Sales.Customers;

In the absence of further instruction, the query will return one result for each row in the Sales.Customers
table, but since only the country column is specified, you will see that column alone for all 91 rows.

Understanding DISTINCT
Replacing the default SELECT ALL clause with
SELECT DISTINCT will filter out duplicates in the
result set. SELECT DISTINCT specifies that the result
set must contain only unique rows. However, it is
important to understand that the DISTINCT option
operates only on the set of columns returned by the
SELECT clause. It does not take into account any
other unique columns in the source table. DISTINCT
also operates on all the columns in the SELECT list,
not just the first one.

The logical order of operations also ensures that the


DISTINCT operator will remove rows that may have
already been processed by WHERE, HAVING, and GROUP BY clauses.

Continuing the previous example of countries from the Sales.Customers table, to eliminate the duplicate
values, replace the silent ALL default with DISTINCT:

DISTINCT Statement
SELECT DISTINCT country
FROM Sales.Customers;

This will yield the desired results. Note that, while the results appear to be sorted, this is not guaranteed
by SQL Server. The result set now contains only one instance of each unique output row:

Country
---------
Argentina
Austria
Belgium
Brazil
Canada
Denmark
3-8 Writing SELECT Queries

Finland
France
Germany
Ireland
Italy
Mexico
Norway
Poland
Portugal
Spain
Sweden
Switzerland
UK
USA
Venezuela
(21 row(s) affected)

Note: You will learn additional methods for filtering out duplicate values later in this
course. Once you have learned them, you may wish to consider the relative performance costs of
filtering with SELECT DISTINCT versus those other means.

SELECT DISTINCT Syntax


Remember that DISTINCT looks at rows in the
output set, created by the SELECT clause. Therefore,
only unique combinations of column values will be
returned by a SELECT DISTINCT clause.

For example, if you query a table with the following


data in it, you might observe that there are only
four unique first names and four unique last names:

SELECT Statement
SELECT firstname, lastname
FROM Sales.Customers;

The results:

firstname lastname
---------- --------------------
Sara Davis
Don Funk
Sara Lew
Don Davis
Judy Lew
Judy Funk
Yael Peled

However, a SELECT DISTINCT query against both columns will retrieve all unique combinations of the two
which, in this case, is the same seven employees.

For a list of unique first names only, execute a SELECT DISTINCT only against the firstname column:

DISTINCT Syntax
SELECT DISTINCT firstname
Querying Microsoft® SQL Server® 3-9

FROM Sales.Customers;

The results:

firstname
----------
Don
Judy
Sara
Yael
(4 row(s) affected)

A challenge in designing such queries is that, while you may need to retrieve a distinct list of values from
one column, you might want to see additional attributes (columns) from others. Later in this course, you
will see how to combine DISTINCT with the GROUP BY clause as a way of further processing and
displaying information about distinct lists of values.

Demonstration: Eliminating Duplicates with DISTINCT


In this demonstration, you will see how to:
• Eliminate duplicate rows.

Demonstration Steps
Eliminate Duplicate Rows
1. Ensure that you have completed the previous demonstration in this module. Alternatively, start the
20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as
ADVENTUREWORKS\Student with the password Pa$$w0rd, and run
D:\Demofiles\Mod03\Setup.cmd as an administrator.

2. If SQL Server Management Studio is not already open, start it and connect to the MIA-SQL database
engine instance using Windows authentication, and then open the Demo.ssmssln solution in the
D:\Demofiles\Mod03\Demo folder.

3. In Solution Explorer, open the 21 – Demonstration B.sql script file.

4. Follow the instructions contained within the comments of the script file.

5. Keep SQL Server Management Studio open for the next demonstration.
3-10 Writing SELECT Queries

Lesson 3
Using Column and Table Aliases
When retrieving data from a table or view, a T-SQL query will name each column after its source. If
desired, columns may be relabeled by the use of aliases in the SELECT clause. However, columns created
with expressions will not be named automatically. Column aliases may be used to provide custom column
headers. At the table level, aliases may be used in the FROM clause to provide a convenient way of
referring to a table elsewhere in the query, enhancing readability.

Lesson Objectives
In this lesson you will learn how to:

• Use aliases to refer to columns in a SELECT list.

• Use aliases to refer to columns in a FROM clause.

• Understand the impact of the logical order of query processing on aliases.

Using Aliases to Refer to Columns


Column aliases can be used to relabel columns
when returning the results of a query. For example,
cryptic names of columns in a table such as qty may
be replaced with quantity.
Expressions that are not based on a source column
in the table will not have a name provided in the
result set. This includes calculated expressions and
function calls. While T-SQL doesn’t require that a
column in a result set have a name, it’s a good idea
to provide one.
In T-SQL, there are multiple methods of creating a
column alias, with identical output results.

One method is to use the AS keyword to separate the column or expression from the alias:

AS Keyword
SELECT orderid, unitprice, qty AS quantity
FROM Sales.OrderDetails;

Another method is to assign the alias before the column or expression, using the equals sign as the
separator:

Alias With an Equals Sign


SELECT orderid, unitprice, quantity = qty
FROM Sales.OrderDetails;

Finally, you can simply assign the alias immediately following the column name, although this is not a
recommended method:

Alias Following Column Name


SELECT orderid, unitprice, qty quantity
Querying Microsoft® SQL Server® 3-11

FROM Sales.OrderDetails;

While there is no difference in performance or execution, a variance in readability may cause you to
choose one or the other as a convention.

Warning: Column aliases can also be accidentally created, by omitting a comma between two column
names in the SELECT list.

For example, the following creates an alias for the unitprice column deceptively labeled quantity:

Accidental Alias
SELECT orderid, unitprice quantity
FROM Sales.OrderDetails;

The results:

orderid quantity
----------- ---------------------
10248 14.00
10248 9.80
10248 34.80
10249 18.60

As you can see, this could be difficult to identify and fix in a client application. The only way to avoid this
problem is to carefully list your columns, separating them properly with commas and adopting the AS
style of aliases to make it easier to spot mistakes.

Question: Which style of column aliases do you prefer? Why?

Using Aliases to Refer to Tables


Aliases may also be used in the FROM clause to
refer to a table, which can improve readability and
save redundancy when referencing the table
elsewhere in the query. While this module has
focused on single-table queries, which don’t
necessarily benefit from table aliases, this technique
will prove useful as you learn more complex queries
in subsequent modules.

To create a table alias in a FROM clause, you will


use syntax similar to several of the column alias
techniques.

You may use the keyword AS to separate the table


name from the alias. This style is preferred:

Table Alias Using AS


SELECT orderid, unitprice, qty
FROM Sales.OrderDetails AS OD;

You may omit the keyword AS and simply follow the table name with the alias:
3-12 Writing SELECT Queries

Table Alias Without AS


SELECT orderid, unitprice, qty
FROM Sales.OrderDetails OD;

To combine table and column aliases in the same SELECT statement, use the following approach:

Table and Column Aliases Combined


SELECT OD.orderid, OD.unitprice, OD.qty AS Quantity
FROM Sales.OrderDetails AS OD;

Note: There is no table alias equivalent to the use of the equals sign (=) in a column alias.

Since this module focuses on single-table queries, you might not yet see a benefit to using table aliases. In
the next module, you will learn how to retrieve data from multiple tables in a single SELECT statement. In
those queries, the use of table aliases to represent table names will become quite useful.

The Impact of Logical Processing Order on Aliases


An issue may arise in the use of column aliases.
Aliases created in the SELECT clause may not be
referred to in others in the query, such as a WHERE
or HAVING clause. This is due to the logical order
query processing. The WHERE and HAVING clauses
are processed before the SELECT clause and its
aliases are evaluated. An exception to this is the
ORDER BY clause.
An example is provided here for illustration and will
run without error:

ORDER BY With Alias


SELECT orderid, unitprice, qty AS quantity
FROM Sales.OrderDetails
ORDER BY quantity;

However, the following example will return an error, as the WHERE clause has been processed before the
SELECT clause defines the alias:

Incorrect WHERE With Alias


SELECT orderid, unitprice, qty AS quantity
FROM Sales.OrderDetails
WHERE quantity > 10;

The resulting error message:

Msg 207, Level 16, State 1, Line 1


Invalid column name 'quantity'.

As a result, you will often need to repeat an expression more than once—in the SELECT clause, where you
may create an alias to name the column, and in the WHERE or HAVING clause:
Querying Microsoft® SQL Server® 3-13

Correct WHERE With Alias


SELECT orderid, YEAR(orderdate) AS orderyear
FROM Sales.Orders
WHERE YEAR(orderdate) = '2008'

Additionally, within the SELECT clause, you may not refer to a column alias that was defined in the same
SELECT statement, regardless of column order.

The following statement will return an error:

Column Alias used in SELECT Clause


SELECT productid, unitprice AS price, price * qty AS total
FROM Sales.OrderDetails;

The resulting error:

Msg 207, Level 16, State 1, Line 1


Invalid column name 'price'.

Demonstration: Using Column and Table Aliases


In this demonstration, you will see how to:

• Use column and table aliases.

Demonstration Steps
Use Column and Table Aliases

1. Ensure that you have completed the previous demonstration in this module. Alternatively, start the
20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as
ADVENTUREWORKS\Student with the password Pa$$w0rd, and run
D:\Demofiles\Mod03\Setup.cmd as an administrator.

2. If SQL Server Management Studio is not already open, start it and connect to the MIA-SQL database
engine instance using Windows authentication, and then open the Demo.ssmssln solution in the
D:\Demofiles\Mod03\Demo folder.

3. In Solution Explorer, open the 31 – Demonstration C.sql script file.

4. Follow the instructions contained within the comments of the script file.

5. Keep SQL Server Management Studio open for the next demonstration.
3-14 Writing SELECT Queries

Lesson 4
Writing Simple CASE Expressions
A CASE expression extends the ability of a SELECT clause to manipulate data as it is retrieved. Often when
writing a query, you need to substitute a value from a column of a table with another value. While you
will learn how to perform this kind of lookup from another table later in this course, you can also perform
basic substitutions using simple CASE expressions in the SELECT clause. In real-world environments, CASE
is often used to help make cryptic data held in a column more meaningful.

A CASE expression returns a scalar (single-valued) value based on conditional logic, often with multiple
conditions. As a scalar value, it may be used wherever single values can be used. Besides the SELECT
statement, CASE expressions can be used in WHERE, HAVING, and ORDER BY clauses.

Lesson Objectives
In this lesson you will learn how to:
• Understand the use of CASE expressions in SELECT clauses.

• Understand the simple form of a CASE expression.

Using CASE Expressions in SELECT Clauses


In T-SQL, CASE expressions return a single, or scalar,
value. Unlike some other programming languages,
in T-SQL CASE, expressions are not statements, nor
do they specify the control of programmatic flow.
Instead, they are used in SELECT clauses (and other
clauses) to return the result of an expression. The
results appear as a calculated column and should
be aliased for clarity.
In T-SQL queries, CASE expressions are often used
to provide an alternative value for one stored in the
source table. For example, a CASE expression might
be used to provide a friendly text name for
something stored as a compact numeric code.
Querying Microsoft® SQL Server® 3-15

Forms of CASE Expressions


In T-SQL, CASE expressions may take one of two
forms – simple CASE or searched (Boolean) CASE.

Simple CASE expressions, the subject of this lesson,


compare an input value to a list of possible
matching values:

1. If a match is found, the first matching value is


returned as the result of the CASE expression.
Multiple matches are not permitted.

2. If no match is found, a CASE expression returns


the value found in an ELSE clause, if one exists.

3. If no match is found and no ELSE clause is


present, the CASE expression returns a NULL.

For example, the following CASE expression substitutes a descriptive category name for the categoryid
value stored in the Production.Categories table. Note that this is not a JOIN operation, just a simple
substitution using a single table:

CASE Expression
SELECT productid, productname, categoryid,
CASE categoryid
WHEN 1 THEN 'Beverages'
WHEN 2 THEN 'Condiments'
WHEN 2 THEN 'Confections'
ELSE 'Unknown Category'
END AS categoryname
FROM Production.Categories

The results:

productid productname categoryid categoryname


--------- ------------ ---------- ---------------------
101 Tea 1 Beverages
102 Mustard 2 Condiments
103 Dinner Rolls 9 Unknown Category

Note: The preceding example is presented for illustration only and will not run against the
sample databases provided with the course.

Searched (Boolean) CASE expressions compare an input value to a set of logical predicates or expressions.
The expression can contain a range of values to match against. Like a simple CASE expression, the return
value is found in the THEN clause of the matching value.

Due to their dependence on predicate expressions, which will not be covered until later in this course,
further discussion of searched CASE expressions is beyond the scope of this lesson. See CASE (Transact-
SQL) in Books Online:
CASE (Transact-SQL)
http://go.microsoft.com/fwlink/?LinkID=402717
3-16 Writing SELECT Queries

Demonstration: Using a Simple CASE Expression


In this demonstration, you will see how to:

• Use a simple CASE expression.

Demonstration Steps
Use a Simple CASE Expression

1. Ensure that you have completed the previous demonstration in this module. Alternatively, start the
20461C-MIA-DC and 20461C-MIA-SQL virtual machines, log on to 20461C-MIA-SQL as
ADVENTUREWORKS\Student with the password Pa$$w0rd, and run
D:\Demofiles\Mod03\Setup.cmd as an administrator.

2. If SQL Server Management Studio is not already open, start it and connect to the MIA-SQL database
engine instance using Windows authentication, and then open the Demo.ssmssln solution in the
D:\Demofiles\Mod03\Demo folder.

3. In Solution Explorer, open the 41 – Demonstration D.sql script file.


4. Follow the instructions contained within the comments of the script file.

5. Close SQL Server Management Studio without saving any files.


Querying Microsoft® SQL Server® 3-17

Lab: Writing Basic SELECT Statements


Scenario
You are a business analyst for Adventure Works who will be writing reports using corporate databases
stored in SQL Server 2014. You have been provided with a set of business requirements for data and will
write basic T-SQL queries to retrieve the specified data from the databases.

Objectives
After completing this lab, you will be able to:

• Write simple SELECT statements.

• Eliminate duplicate rows by using the DISTINCT keyword.

• Use table and column aliases.


• Use a simple CASE expression.

Estimated Time: 40 minutes

Virtual machine: 20461C-MIA-SQL


User name: ADVENTUREWORKS\Student

Password: Pa$$w0rd

Exercise 1: Writing Simple SELECT Statements


Scenario
As a business analyst, you want a better understanding of your corporate data. Usually the best approach
for an initial project is to get an overview of the main tables and columns involved so you can better
understand different business requirements. After an initial overview, you will have to provide a report for
the marketing department because staff there would like to send invitation letters for a new campaign.
You will use the TSQL sample database.

The main tasks for this exercise are as follows:

1. Prepare the Lab Environment

2. View all the Tables in the TSQL Database in Object Explorer

3. Write a Simple SELECT Statement

4. Write a SELECT Statement that Includes Specific Columns

 Task 1: Prepare the Lab Environment


1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. Run Setup.cmd in the D:\Labfiles\Lab03\Starter folder as Administrator.

 Task 2: View all the Tables in the TSQL Database in Object Explorer
1. Using SSMS, connect to MIA-SQL using Windows authentication (if you are connecting to an on-
premises instance of SQL Server) or SQL Server authentication.

2. In Object Explorer, expand the TSQL database and expand the Tables folder.

3. Take a look at the names of the tables in the Sales schema.


3-18 Writing SELECT Queries

 Task 3: Write a Simple SELECT Statement


1. Open the project file D:\Labfiles\Lab03\Starter\Project\Project.ssmssln and the T-SQL script 51 - Lab
Exercise 1.sql. Ensure that you are connected to the TSQL database.

2. Write a SELECT statement that will return all rows and all columns from the Sales.Customers table.

Note: You can use drag-and-drop functionality to drag items like table and column names
from Object Explorer to the query window. Write the same SELECT statement using the drag-
and-drop functionality.

3. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\52 - Lab Exercise 1 - Task 2 Result.txt.

 Task 4: Write a SELECT Statement that Includes Specific Columns


1. Expand the Sales.Customers table in Object Explorer and expand the Columns folder. Observe all
columns in the table.
2. Write a SELECT statement to return the contactname, address, postalcode, city, and country columns
from the Sales.Customers table.

3. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\53 - Lab Exercise 1 - Task 3 Result.txt.

4. What is the number of rows affected by the last query? (Tip: Because you are issuing a SELECT
statement against the whole table, the number of rows will be the same as that for the whole
Sales.Customers table).

Results: After this exercise, you should know how to create simple SELECT statements to analyze existing
tables.

Exercise 2: Eliminating Duplicates Using DISTINCT


Scenario
After supplying the marketing department with a list of all customers for a new campaign, you are asked
to provide a list of all the different countries that the customers come from.

The main tasks for this exercise are as follows:


1. Write a SELECT Statement that Includes a Specific Column

2. Write a SELECT Statement that Uses the DISTINCT Clause

 Task 1: Write a SELECT Statement that Includes a Specific Column


1. Open the project file D:\Labfiles\Lab03\Starter\Project\Project.ssmssln and T-SQL script 61 - Lab
Exercise 2.sql. Ensure that you are connected to the TSQL database.

2. Write a SELECT statement against the Sales.Customers table showing only the country column.

3. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\62 - Lab Exercise 2 - Task 1 Result.txt.

 Task 2: Write a SELECT Statement that Uses the DISTINCT Clause


1. Copy the SELECT statement in Task 1 and modify it to return only distinct values.
Querying Microsoft® SQL Server® 3-19

2. Execute the written statement and compare the results that you achieved with the desired results
shown in file D:\Labfiles\Lab03\Solution\63 - Lab Exercise 2 - Task 2 Result.txt.

3. How many rows did the query in Task 1 return?

4. How many rows did the query in Task 2 return?

5. Under which circumstances do the following queries against the Sales.Customers table return the
same result?

SELECT city, region FROM Sales.Customers;


SELECT DISTINCT city, region FROM Sales.Customers;

6. Is the DISTINCT clause being applied to all columns specified in the query or just the first column?

Results: After this exercise, you should have an understanding of how to return only the different
(distinct) rows in the result set of a query.

Exercise 3: Using Table and Column Aliases


Scenario
After getting the initial list of customers, the marketing department would like to have more readable
titles for the columns and a list of all products in the TSQL database.

The main tasks for this exercise are as follows:

1. Write a SELECT Statement that Uses a Table Alias

2. Write A SELECT Statement That Uses Column Aliases

3. Write a SELECT Statement that Uses a Table Alias and a Column Alias

4. Analyze and Correct the Query

 Task 1: Write a SELECT Statement that Uses a Table Alias


1. Open the project file D:\Labfiles\Lab03\Starter\Project\Project.ssmssln and T-SQL script 71 - Lab
Exercise 3.sql. Ensure that you are connected to the TSQL database.

2. Write a SELECT statement to return the contactname and contacttitle columns from the
Sales.Customers table, assigning “C” as the table alias. Use the table alias C to prefix the names of the
two needed columns in the SELECT list. The benefit of using table aliases will become clearer in future
modules when topics such as joins and subqueries will be introduced.

3. Execute the written statement and compare the results that you achieved with the recommended
results shown in the file D:\Labfiles\Lab03\Solution\72 - Lab Exercise 3 - Task 1 Result.txt.

 Task 2: Write A SELECT Statement That Uses Column Aliases


1. Write a SELECT statement to return the contactname, contacttitle, and companyname columns.
Assign these with the aliases Name, Title, and Company Name, respectively, in order to return more
human-friendly column titles for reporting purposes.

2. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\73 - Lab Exercise 3 - Task 2 Result.txt. Notice specifically
the titles of the columns in the desired output.
3-20 Writing SELECT Queries

 Task 3: Write a SELECT Statement that Uses a Table Alias and a Column Alias
1. Write a query to display the productname column from the Production.Products table using “P” as
the table alias and Product Name as the column alias.

2. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\74 - Lab Exercise 3 - Task 3 Result.txt.

 Task 4: Analyze and Correct the Query


1. A developer has written a query to retrieve two columns (city and region) from the Sales.Customers
table. When the query is executed, it returns only one column. Your task is to analyze the query,
correct it to return two columns, and explain why the query returned only one.

SELECT city country


FROM Sales.Customers;

2. Execute the query exactly as written inside a query window and observe the result.

3. Correct the query to return the city and country columns from the Sales.Customers table.

Why did the query return only one column? What was the title of the column in the output? What is the
best practice when using aliases for columns to avoid such errors?

Results: After this exercise, you will know how to use aliases for table and column names.

Exercise 4: Using a Simple CASE Expression


Scenario
Your company has a long list of products, and the members of the marketing department would like to
have product category information in their reports. They have supplied you with a document containing
the following mapping between the product category IDs and their names:

categoryid Categoryname

1 Beverages

2 Condiments

3 Confections

4 Dairy Products

5 Grains/Cereals

6 Meat/Poultry

7 Produce

8 Seafood

They have an active marketing campaign, and would like to include product category information in their
reports.

The main tasks for this exercise are as follows:

1. Write a SELECT Statement


Querying Microsoft® SQL Server® 3-21

2. Write a SELECT Statement that Uses a CASE Expression

3. Write a SELECT Statement that Uses a CASE Expression to differentiate Campaign-Focused Products

 Task 1: Write a SELECT Statement


1. Open the project file D:\Labfiles\Lab03\Starter\Project\Project.ssmssln and T-SQL script 81 Lab
Exercise 4.sql. Ensure that you are connected to the TSQL database.

2. Write a SELECT statement to display the categoryid and productname columns from the
Production.Products table.

3. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\82 - Lab Exercise 4 - Task 1 Result.txt.

 Task 2: Write a SELECT Statement that Uses a CASE Expression


1. Enhance the SELECT statement in task 1 by adding a CASE expression that generates a result column
named categoryname. The new column should hold the translation of the category ID to its
respective category name, based on the mapping table supplied earlier. Use the value “Other” for any
category IDs not found in the mapping table.

2. Execute the written statement and compare the results that you achieved with the desired output
shown in the file D:\Labfiles\Lab03\Solution\83 - Lab Exercise 4 - Task 2 Result.txt.

 Task 3: Write a SELECT Statement that Uses a CASE Expression to differentiate


Campaign-Focused Products
1. Modify the SELECT statement in task 2 by adding a new column named iscampaign. This will show
the description “Campaign Products” for the categories Beverages, Produce, and Seafood and the
description “Non-Campaign Products” for all other categories.
2. Execute the written statement and compare the results that you achieved with the desired results
shown in the file D:\Labfiles\Lab03\Solution\84 - Lab Exercise 4 - Task 3 Result.txt.

Results: After this exercise, you should know how to use CASE expressions to write simple conditional
logic.
3-22 Writing SELECT Queries

Module Review and Takeaways


Best Practice: Terminate all T-SQL statements with a semicolon. This will make your code
more readable, avoid certain parsing errors, and protect your code against changes in future
versions of SQL Server.
Consider standardizing your code on the AS keyword for labeling column and table aliases. This
will make it easier to read and avoids accidental aliases.

Review Question(s)
Question: Why is the use of SELECT * not a recommended practice?

Question: What will happen if you omit a comma between column names in a SELECT
clause?

Question: What kind of result does a simple CASE statement return?


L4-1

Module 4: Querying Multiple Tables


Lab: Querying Multiple Tables
Exercise 1: Writing Queries That Use Inner Joins
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and

20461C-MIA-SQL virtual machines are both running, and then log on to

20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab04\Starter folder, right-click Setup.cmd and then click Run as administrator.

3. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Write a SELECT Statement that Uses an Inner Join


1. On the virtual machine, on the Taskbar, click SQL Server 2014 Management Studio. In the Connect
to Server window, type MIA-SQL in the Server name text box and click Connect.

2. On the File menu, click Open and click Project/Solution.


3. In the Open Project window, open the project D:\Labfiles\Lab04\Starter\Project\Project.ssmssln.

4. In Solution Explorer, double-click the query 51 - Lab Exercise 1.sql. (If Solution Explorer is not visible,
select Solution Explorer on the View menu or press Ctrl+Alt+L on the keyboard).

5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. In the query pane, type the following query after the task 1 description:

SELECT
p.productname, c.categoryname
FROM Production.Products AS p
INNER JOIN Production.Categories AS c ON p.categoryid = c.categoryid;

7. Highlight the written query and click Execute.

8. Observe the result and answer these questions:

o Which column did you specify as a predicate in the ON clause of the join? Why?

In this query, the categoryid column is the predicate. By intuition, most people would say that it
is the predicate because this column exists in both input tables. By the way, using the same name
for columns that contain the same data but in different tables is a good practice in data
modeling. Another possibility is to check for referential integrity through primary and foreign key
information using SQL Server Management Studio. If there are no primary or foreign key
constraints, you will have to acquire information about the data model from the developer.

o Let us say that there is a new row in the Production.Categories table and this new product
category does not have any products associated with it in the Production.Products table. Would
this row be included in the result of the SELECT statement written under the task 1 description?
No, because an inner join retrieves only the matching rows based on the predicate from both
input tables. Since the new value for the categoryid is not present in the categoryid column in the
Production.Products table, there would be no matching rows in the result of the SELECT
statement.
L4-2 Querying Microsoft® SQL Server®

Results: After this exercise, you should know how to use an inner join between two tables.
L4-3

Exercise 2: Writing Queries That Use Multiple-Table Inner Joins


 Task 1: Execute the T-SQL Statement
1. In Solution Explorer, double-click the query 61 - Lab Exercise 2.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. Highlight the written query under the Task 1 description and click Execute.

4. Observe that you get the error message:

Ambiguous column name 'custid'.

5. This error occurred because the custid column appears in both tables and you have to specify from
which table you would like to retrieve the column values.

 Task 2: Apply the Needed Changes and Execute the T-SQL Statement
1. Copy the T-SQL statement from Task 1. In the query window, click the line after the Task 2
description. On the toolbar, click Paste.

2. Add the column prefix “Customers” to the existing query so that it looks like this:

SELECT
Customers.custid, contactname, orderid
FROM Sales.Customers
INNER JOIN Sales.Orders ON Customers.custid = Orders.custid;

3. Highlight the modified query and click Execute.

 Task 3: Change the Table Aliases


1. Highlight the previous query. On the toolbar, click Edit and then Copy.

2. In the query window, click the line after the task 3 description. On the toolbar, click Edit and then
Paste. You have now copied the previous query to the same query window after the task 3
description.

3. Modify the T-SQL statement to use table aliases. Your query should look like this:

SELECT
c.custid, c.contactname, o.orderid
FROM Sales.Customers AS c
INNER JOIN Sales.Orders AS o ON c.custid = o.custid;

4. Highlight the written query and click Execute.

5. Compare the results with the Task 2 results.

6. Modify the T-SQL statement to include a full source table name as the column prefix. Your query
should now look like this:

SELECT
Customers.custid, Customers.contactname, Orders.orderid
FROM Sales.Customers AS c
INNER JOIN Sales.Orders AS o ON c.custid = o.custid;

7. Highlight the written query and click Execute.

8. Observe that you get the error messages:


L4-4 Querying Microsoft® SQL Server®

Msg 4104, Level 16, State 1, Line 2

The multi-part identifier "Customers.custid" could not be found.

Msg 4104, Level 16, State 1, Line 2

The multi-part identifier "Customers.contactname" could not be found.

Msg 4104, Level 16, State 1, Line 2

The multi-part identifier "Orders.orderid" could not be bound.

You received these error messages as, because you are using a different table alias, the full source
table name you are referencing as a column prefix no longer exists. Remember that the SELECT clause
is evaluated after the FROM clause, so you must use the table aliases when specifying columns in the
SELECT clause.

9. Modify the SELECT statement so that it uses the correct table aliases. Your query should look like this:

SELECT
c.custid, c.contactname, o.orderid
FROM Sales.Customers AS c
INNER JOIN Sales.Orders AS o ON c.custid = o.custid;

 Task 4: Add an Additional Table and Columns


1. In the query pane, type the following query after the task 4 description:

SELECT
c.custid, c.contactname, o.orderid, d.productid, d.qty, d.unitprice
FROM Sales.Customers AS c
INNER JOIN Sales.Orders AS o ON c.custid = o.custid
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid;

2. Highlight the written query and click Execute.

3. Observe the result. Remember that, when you have a multiple-table inner join, the logical query
processing is different from the physical implementation. In this case, it means that you cannot
guarantee the order in which the SQL Server optimizer will process the tables. For example, you
cannot guarantee that the Sales.Customers table will be joined first with the Sales.Orders table, and
then with the Sales.OrderDetails table.

Results: After this exercise, you should have a better understanding of why aliases are important and how
to do a multiple-table join.
L4-5

Exercise 3: Writing Queries That Use Self Joins


 Task 1: Write a Basic SELECT Statement
1. In Solution Explorer, double-click the query 71 - Lab Exercise 3.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT
e.empid, e.lastname, e.firstname, e.title, e.mgrid
FROM HR.Employees AS e;

4. Highlight the written query and click Execute.

5. Observe that the query retrieved nine rows.

 Task 2: Write a Query that Uses a Self Join


1. Highlight the previous query. On the toolbar, click Edit and then Copy.

2. In the query window, click the line after the task 2 description. On the toolbar, click Edit and then
Paste. You have now copied the previous query to the same query window after the task 2
description.

3. Modify the query by adding a self join to get information about the managers. The query should look
like this:

SELECT
e.empid, e.lastname, e.firstname, e.title, e.mgrid,
m.lastname AS mgrlastname, m.firstname AS mgrfirstname
FROM HR.Employees AS e
INNER JOIN HR.Employees AS m ON e.mgrid = m.empid;

4. Highlight the written query and click Execute.


5. Observe that the query retrieved eight rows and answer these questions:

o Is it mandatory to use table aliases when writing a statement with a self join? Can you use a full
source table name as an alias?

You must use table aliases. You cannot use the full source table name as an alias when
referencing both input tables. Eventually, you could use a full source table name as an alias for
one input table and another alias for the second input table.

o Why did you get fewer rows in the result from the T-SQL statement under the task 2 description
compared to the result from the T-SQL statement under the task 1 description?

In task 2’s T-SQL statement, the inner join used an ON clause based on manager information
(column mgrid). The employee who is the CEO has a missing value in the mgrid column so this
row is not included in the result.

Results: After this exercise, you should have an understanding of how to write T-SQL statements that use
self joins.
L4-6 Querying Microsoft® SQL Server®

Exercise 4: Writing Queries That Use Outer Joins


 Task 1: Write a SELECT Statement that Uses an Outer Join
1. In Solution Explorer, double-click the query 81 - Lab Exercise 4.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT
c.custid, c.contactname, o.orderid
FROM Sales.Customers AS c
LEFT OUTER JOIN Sales.Orders AS o ON c.custid = o.custid;

4. Highlight the written query and click Execute.

5. Inspect the result. Notice that the custid 22 and custid 57 rows have a missing value in the orderid
column. This is because there are no rows in the Sales.Orders table for these two values of the custid
column. In business terms, this means that there are currently no orders for these two customers.

Results: After this exercise, you should have a basic understanding of how to write T-SQL statements that
use outer joins.
L4-7

Exercise 5: Writing Queries That Use Cross Joins


 Task 1: Execute the T-SQL Statement
1. In Solution Explorer, double-click the query 91 - Lab Exercise 5.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. Highlight the T-SQL code under the task 1 description and click Execute. Don’t worry if you do not
understand the provided T-SQL code, as it is used here to provide a more realistic example for a cross
join in the next task.

 Task 2: Write a SELECT Statement that Uses a Cross Join


1. In the query pane, type the following query after the task 2 description:

SELECT
e.empid, e.firstname, e.lastname, c.calendardate
FROM HR.Employees AS e
CROSS JOIN HR.Calendar AS c;

2. Highlight the written query and click Execute.

3. Observe that the query retrieved 3,285 rows and that there are nine rows in the HR.Employees table.
Because a cross join produces a Cartesian product of both inputs, it means that there are 365
(3,285/9) rows in the HR.Calendar table.

 Task 3: Drop the HR.Calendar Table


1. Highlight the written query under the task 3 description and click Execute.

Results: After this exercise, you should have an understanding of how to write T-SQL statements that use
cross joins.
L4-8 Querying Microsoft® SQL Server®
L5-1

Module 5: Sorting and Filtering Data


Lab: Sorting and Filtering Data
Exercise 1: Writing Queries That Filter Data Using a WHERE Clause
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab05\Starter folder, right-click Setup.cmd and then click Run as administrator.

1. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Write a SELECT Statement that Uses a WHERE Clause


1. Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using
Windows authentication.

2. On the File menu, click Open and click Project/Solution.

3. In the Open Project window, open the project D:\Labfiles\Lab05\Starter\Project\Project.ssmssln.

4. In Solution Explorer, double-click the query 51 - Lab Exercise 1.sql. (If Solution Explorer is not visible,
select Solution Explorer on the View menu or press Ctrl+Alt+L on the keyboard.)

5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. In the query pane, type the following query after the task 1 description:

SELECT
custid, companyname, contactname, address, city, country, phone
FROM Sales.Customers
WHERE
country = N'Brazil';

7. Notice the use of the N prefix for the character literal. This prefix is used because the country column
is a Unicode data type. When expressing a Unicode character literal, you need to specify the character
N (for National) as a prefix. You will learn more about data types in the next module.
8. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement that Uses an IN Predicate in the WHERE Clause
1. In the query pane, type the following query after the task 2 description:

SELECT
custid, companyname, contactname, address, city, country, phone
FROM Sales.Customers
WHERE
country IN (N'Brazil', N'UK', N'USA');

2. Highlight the written query and click Execute.

 Task 4: Write a SELECT Statement that Uses a LIKE Predicate in the WHERE Clause
1. In the query pane, type the following query after the task 3 description:

SELECT
custid, companyname, contactname, address, city, country, phone
FROM Sales.Customers
L5-1

Module 5: Sorting and Filtering Data


Lab: Sorting and Filtering Data
Exercise 1: Writing Queries That Filter Data Using a WHERE Clause
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab05\Starter folder, right-click Setup.cmd and then click Run as administrator.

1. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Write a SELECT Statement that Uses a WHERE Clause


1. Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using
Windows authentication.

2. On the File menu, click Open and click Project/Solution.

3. In the Open Project window, open the project D:\Labfiles\Lab05\Starter\Project\Project.ssmssln.

4. In Solution Explorer, double-click the query 51 - Lab Exercise 1.sql. (If Solution Explorer is not visible,
select Solution Explorer on the View menu or press Ctrl+Alt+L on the keyboard.)

5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. In the query pane, type the following query after the task 1 description:

SELECT
custid, companyname, contactname, address, city, country, phone
FROM Sales.Customers
WHERE
country = N'Brazil';

7. Notice the use of the N prefix for the character literal. This prefix is used because the country column
is a Unicode data type. When expressing a Unicode character literal, you need to specify the character
N (for National) as a prefix. You will learn more about data types in the next module.
8. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement that Uses an IN Predicate in the WHERE Clause
1. In the query pane, type the following query after the task 2 description:

SELECT
custid, companyname, contactname, address, city, country, phone
FROM Sales.Customers
WHERE
country IN (N'Brazil', N'UK', N'USA');

2. Highlight the written query and click Execute.

 Task 4: Write a SELECT Statement that Uses a LIKE Predicate in the WHERE Clause
1. In the query pane, type the following query after the task 3 description:

SELECT
custid, companyname, contactname, address, city, country, phone
FROM Sales.Customers
L5-2 Querying Microsoft® SQL Server®

WHERE
contactname LIKE N'A%';

2. Remember that the percent sign (%) wildcard represents a string of any size (including an empty
string), whereas the underscore (_) wildcard represents a single character.

3. Highlight the written query and click Execute.

 Task 5: Observe the T-SQL Statement Provided by the IT Department


1. Highlight the T-SQL statement provided under the task 4 description and click Execute.

2. Highlight the provided T-SQL statement. On the toolbar, click Edit and then Copy.

3. In the query window, click the line after the task 4 description. On the toolbar, click Edit and then
Paste. You have now copied the previous query to the same query window after the task 4
description.

4. Modify the query so that it looks like this:

SELECT
c.custid, c.companyname, o.orderid
FROM Sales.Customers AS c
LEFT OUTER JOIN Sales.Orders AS o ON c.custid = o.custid
WHERE
c.city = N'Paris';

5. Highlight the modified query and click Execute.

6. Observe the result. Is it the same as that of the first SQL statement? The result is not the same. When
you specify the predicate in the ON clause, the left outer join preserves all the rows from the left table
(Sales.Customers) and adds only the matching rows from the right table (Sales.Orders), based on the
predicate in the ON clause. This means that all the customers will show up in the output, but only the
ones from Paris will have matching orders. When you specify the predicate in the WHERE clause, the
query will filter only the Paris customers. So, be aware that, when you use an outer join, the result of a
query in which the predicate is specified in the ON clause can differ from the result of a query in
which the predicate is specified in the WHERE clause. (When using an inner join, the results are always
the same.) This is because the ON predicate is matching—it defines which rows from the non-
preserved side to match to those from the preserved side. The WHERE predicate is a filtering
predicate—if a row from either side doesn’t satisfy the WHERE predicate, the row is filtered out.

 Task 6: Write a SELECT Statement to Retrieve those Customers Without Orders


1. In the query pane, type the following query after the task 5 description:

SELECT
c.custid, c.companyname
FROM Sales.Customers AS c
LEFT OUTER JOIN Sales.Orders AS o ON c.custid = o.custid
WHERE o.custid IS NULL;

2. It is important to note that, when you are looking for a NULL, you should use the IS NULL, not the
equality operator. The equality operator will always return UNKNOWN when you compare something
to a NULL. It will even return UNKNOWN when you compare two NULLs.

3. The choice of which attribute to filter from the non-preserved side of the join is also important. You
should choose an attribute that can only have a NULL when the row is an outer row (for example, a
NULL originating from the base table). For this purpose, three cases are safe to consider:

o A primary key column. A primary key column cannot be NULL. Therefore, a NULL in such a
column can only mean that the row is an outer row.
L5-3

o A join column. If a row has a NULL in the join column, it is filtered out by the second phase of the
join. So a NULL in such a column can only mean that it is an outer row.

o A column defined as NOT NULL. A NULL in a column that is defined as NOT NULL can only mean
that the row is an outer row.

4. Highlight the written query and click Execute.

Results: After this exercise, you should be able to filter rows of data from one or more tables by using
WHERE predicates with logical operators.
L5-4 Querying Microsoft® SQL Server®

Exercise 2: Writing Queries That Sort Data Using an ORDER BY Clause


 Task 1: Write a SELECT Statement that Uses an ORDER BY Clause
1. In Solution Explorer, double-click the query 61 - Lab Exercise 2.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT
c.custid, c.contactname, o.orderid, o.orderdate
FROM Sales.Customers AS c
INNER JOIN Sales.Orders AS o ON c.custid = o.custid
WHERE
o.orderdate >= '20080401'
ORDER BY
o.orderdate DESC, c.custid ASC;

Notice the date filter. It uses a literal (constant) of a date. SQL Server recognizes “20080401” as a
character string literal and not as a date and time literal, but because the expression involves two
operands of different types, one needs to be implicitly converted to the other’s type. In this example,
the character string literal is converted to the column’s data type (DATETIME) because character
strings are considered lower in terms of data type precedence, with respect to date and time data
types.
Also notice that the character string literal follows the format “yyyymmdd”. Using this format is a best
practice because SQL Server knows how to convert it to the correct date, regardless of the language
settings.

4. Highlight the written query and click Execute.

 Task 2: Apply the Needed Changes and Execute the T-SQL Statement
1. Highlight the written query under the task 2 description and click Execute.
2. Observe the error message:

Invalid column name 'mgrlastname'.

3. This error occurred because the WHERE clause is evaluated before the SELECT clause and, at that
time, the column did not have an alias. To fix this problem, you must use the source column name
with the appropriate table alias. Modify the T-SQL statement to look like this:

SELECT
e.empid, e.lastname, e.firstname, e.title, e.mgrid,
m.lastname AS mgrlastname, m.firstname AS mgrfirstname
FROM HR.Employees AS e
INNER JOIN HR.Employees AS m ON e.mgrid = m.empid
WHERE
m.lastname = N'Buck';

4. Highlight the written query and click Execute.

 Task 3: Order the Result by the firstname Column


1. Highlight the previous query. On the toolbar, click Edit and then Copy.

2. In the query window, click the line after the task 3 description. On the toolbar, click Edit and then
Paste. You have now copied the previous query to the same query window after the task 3
description.
L5-5

3. Modify the T-SQL statement to include an ORDER BY clause that uses the source column name of
m.firstname. Your query should look like this:

SELECT
e.empid, e.lastname, e.firstname, e.title, e.mgrid,
m.lastname AS mgrlastname, m.firstname AS mgrfirstname
FROM HR.Employees AS e
INNER JOIN HR.Employees AS m ON e.mgrid = m.empid
ORDER BY
m.firstname;

4. Highlight the written query and click Execute.

5. Modify the ORDER BY clause so that it uses the alias for the same column (mgrfirstname). Your query
should look like this:

SELECT
e.empid, e.lastname, e.firstname, e.title, e.mgrid,
m.lastname AS mgrlastname, m.firstname AS mgrfirstname
FROM HR.Employees AS e
INNER JOIN HR.Employees AS m ON e.mgrid = m.empid
ORDER BY
mgrfirstname;

6. Highlight the written query and click Execute.

7. Observe the result. Why were you able to use a source column or alias column name? You can use
either one because the ORDER BY clause is evaluated after the SELECT clause and the alias for the
column name is known.

Results: After this exercise, you should know how to use an ORDER BY clause.
L5-6 Querying Microsoft® SQL Server®

Exercise 3: Writing Queries That Filter Data Using the TOP Option
 Task 1: Writing Queries That Filter Data Using the TOP Clause
1. In Solution Explorer, double-click the query 71 - Lab Exercise 3.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT TOP (20)


orderid, orderdate
FROM Sales.Orders
ORDER BY orderdate DESC;

4. Highlight the written query and click Execute.

 Task 2: Use the OFFSET-FETCH Clause to Implement the Same Task


1. In the query pane, type the following query after the task 2 description:

SELECT
orderid, orderdate
FROM Sales.Orders
ORDER BY orderdate DESC
OFFSET 0 ROWS FETCH FIRST 20 ROWS ONLY;

2. Remember that the OFFSET-FETCH clause was a new functionality in SQL Server 2012. Unlike the TOP
clause, the OFFSET-FETCH clause must be used with the ORDER BY clause.

3. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement to Retrieve the Most Expensive Products


1. In the query pane, type the following query after the task 3 description:

SELECT TOP (10) PERCENT


productname, unitprice
FROM Production.Products
ORDER BY unitprice DESC;

2. Implementing this task with the OFFSET-FETCH clause is possible but not easy because, unlike TOP,
OFFSET-FETCH does not support a PERCENT option.
3. Highlight the written query and click Execute.

Results: After this exercise, you should have an understanding of how to apply the TOP option in the
SELECT clause of a T-SQL statement.
L5-7

Exercise 4: Writing Queries That Filter Data Using the OFFSET-FETCH


Clause
 Task 1: OFFSET-FETCH Clause to Fetch the First 20 Rows
1. In Solution Explorer, double-click the query 81 - Lab Exercise 4.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT
custid, orderid, orderdate
FROM Sales.Orders
ORDER BY orderdate, orderid
OFFSET 0 ROWS FETCH FIRST 20 ROWS ONLY;

4. Highlight the written query and click Execute.

 Task 2: Use the OFFSET-FETCH Clause to Skip the First 20 Rows


1. In the query pane, type the following query after the task 2 description:

SELECT
custid, orderid, orderdate
FROM Sales.Orders
ORDER BY orderdate, orderid
OFFSET 20 ROWS FETCH NEXT 20 ROWS ONLY;

2. Highlight the written query and click Execute.

 Task 3: Write a Generic Form of the OFFSET-FETCH Clause for Paging


1. Solution: OFFSET (@pagenum - 1) * @pagesize ROWS FETCH NEXT @pagesize ROWS ONLY.
L5-8 Querying Microsoft® SQL Server®
L8-1

Module 8: Using Built-In Functions


Lab: Using Built-In Functions
Exercise 1: Writing Queries That Use Conversion Functions
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab08\Starter folder, right-click Setup.cmd and then click Run as administrator.

3. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Write a SELECT Statement that Uses the CAST or CONVERT Function
1. Start SQL Server Management Studio and connect to the MIA-SQL database engine using Windows
authentication.

2. On the File menu, click Open and click Project/Solution.

3. In the Open Project window, open the project D:\Labfiles\Lab08\Starter\Project\Project.ssmssln.

4. In Solution Explorer, double-click the query 51 - Lab Exercise 1.sql. (If Solution Explorer is not visible,
select Solution Explorer on the View menu or press Ctrl+Alt+L on the keyboard.)

5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. In the query pane, type the following query after the task 1 description:

SELECT N'The unit price for the ' + productname + N' is ' + CAST(unitprice AS
NVARCHAR(10)) + N' $.' AS productdesc
FROM Production.Products;

This query uses the CAST function rather than the CONVERT function. It is better to use the CAST
function because it is an ANSI SQL standard. You should use the CONVERT function only when you
need to apply a specific style during a conversion.

7. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement to Filter Rows Based on Specific Date Information
1. In the query pane, type the following query after the task 2 description:

SELECT orderid, orderdate, shippeddate, COALESCE(shipregion, 'No region') AS


shipregion
FROM Sales.Orders
WHERE
orderdate >= CONVERT(DATETIME, '4/1/2007', 101)
AND orderdate <= CONVERT(DATETIME, '11/30/2007', 101)
AND shippeddate > DATEADD(DAY, 30, orderdate);

2. Highlight the written query and click Execute.

3. Note that you could also write a solution using the PARSE function. The query would look like this:

SELECT orderid, orderdate, shippeddate, COALESCE(shipregion, 'No region') AS


shipregion
FROM Sales.Orders
L8-2 Querying Microsoft® SQL Server®

WHERE
orderdate >= PARSE('4/1/2007' AS DATETIME USING 'en-US')
AND orderdate <= PARSE('11/30/2007' AS DATETIME USING 'en-US')
AND shippeddate > DATEADD(DAY, 30, orderdate);

 Task 4: Write a SELECT Statement to Convert the Phone Number Information to an


Integer Value
1. In the query pane, type the following query after the task 3 description:

SELECT
CONVERT(INT, REPLACE(REPLACE(REPLACE(REPLACE(phone, N'-', N''), N'(', ''), N')', ''),
' ', '')) AS phonenoasint
FROM Sales.Customers;

This query is trying to use the CONVERT function to convert phone numbers that include characters
such as hyphens and parentheses into an integer value.

2. Highlight the written query and click Execute.

3. Observe the error message:

Conversion failed when converting the nvarchar value '67.89.01.23' to data type int.

Because you want to retrieve rows without conversion errors and have a NULL for those that produce
a conversion error, you can use the TRY_CONVERT function.
4. Modify the query to use the TRY_CONVERT function. The query should look like this:

SELECT
TRY_CONVERT(INT, REPLACE(REPLACE(REPLACE(REPLACE(phone, N'-', N''), N'(', ''), N')',
''), ' ', '')) AS phonenoasint
FROM Sales.Customers;

5. Highlight the written query and click Execute. Observe the result. The rows that could not be
converted have a NULL.

Results: The unit price for the Product HHYDP is 18.00 $.


L8-3

Exercise 2: Writing Queries That Use Logical Functions


 Task 1: Write a SELECT Statement to Mark Specific Customers Based on their Country
and Contact Title
1. In Solution Explorer, double-click the query 61 - Lab Exercise 2.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT
IIF(country = N'Mexico' AND contacttitle = N'Owner', N'Target group', N'Other') AS
segmentgroup, custid, contactname
FROM Sales.Customers;

4. The IIF function was new in SQL Server 2012. It was added mainly to support migrations from
Microsoft Access to SQL Server. You can always use a CASE expression to achieve the same result.

5. Highlight the written query and click Execute.

 Task 2: Modify the T-SQL Statement to Mark Different Customers


1. In the query pane, type the following query after the task 2 description:

SELECT
IIF(contacttitle = N'Owner' OR region IS NOT NULL, N'Target group', N'Other') AS
segmentgroup, custid, contactname
FROM Sales.Customers;

2. Highlight the written query and click Execute.

 Task 3: Create Four Groups of Customers


1. In the query pane, type the following query after the task 3 description:

SELECT CHOOSE(custid % 4 + 1, N'Group One', N'Group Two', N'Group Three', N'Group


Four') AS segmentgroup, custid, contactname
FROM Sales.Customers;

2. Highlight the written query and click Execute.

Results: After this exercise, you should know how to use the logical functions.
L8-4 Querying Microsoft® SQL Server®

Exercise 3: Writing Queries That Test for Nullability


 Task 1: Write a SELECT Statement to Retrieve the Customer Fax Information
1. In Solution Explorer, double-click the query 71 - Lab Exercise 3.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT contactname, COALESCE(fax, N'No information') AS faxinformation


FROM Sales.Customers;

This query uses the COALESCE function to retrieve customers’ fax information.

4. Highlight the written query and click Execute.

5. In the query pane, type the following query after the previous query:

SELECT contactname, ISNULL(fax, N'No information') AS faxinformation


FROM Sales.Customers;

This query uses the ISNULL function. What is the difference between the ISNULL and COALESCE
functions? COALESCE is a standard ANSI SQL function and ISNULL is not. So you should use the
COALESCE function.

6. Highlight the written query and click Execute.

 Task 2: Write a Filter for a Variable that Could Be a Null


1. Highlight the query provided under the task 2 description and click Execute.

2. Highlight the previous query. On the toolbar, click Edit and then Copy.

3. In the query window, click the line after the task 2 description. On the toolbar, click Edit and then
Paste. You have now copied the previous query to the same query window after the task 2
description.

4. Modify the query so that it looks like this:

DECLARE @region AS NVARCHAR(30) = NULL;


SELECT
custid, region
FROM Sales.Customers
WHERE region = @region OR (region IS NULL AND @region IS NULL);

5. Highlight the modified query and click Execute.

6. Test the modified query by setting the @region parameter to N'WA'. The T-SQL expression should
look like this:

DECLARE @region AS NVARCHAR(30) = N'WA';


SELECT
custid, region
FROM Sales.Customers
WHERE region = @region OR (region IS NULL AND @region IS NULL);

7. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement to Return All the Customers that Do Not Have a
Two-Character Abbreviation for the Region
1. In the query pane, type the following query after the task 3 description:
L8-5

SELECT custid, contactname, city, region


FROM Sales.Customers
WHERE
region IS NULL
OR LEN(region) <> 2;

2. Highlight the written query and click Execute.

Results: After this exercise, you should have an understanding of how to test for nullability.
L8-6 Querying Microsoft® SQL Server®
L9-1

Module 9: Grouping and Aggregating Data


Lab: Grouping and Aggregating Data
Exercise 1: Writing Queries That Use the GROUP BY Clause
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab09\Starter folder, right-click Setup.cmd and then click Run as administrator.

3. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Write a SELECT Statement to Retrieve Different Groups of Customers


1. Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using
Windows authentication.

2. On the File menu, click Open and click Project/Solution.

3. In the Open Project window, open the project D:\Labfiles\Lab09\Starter\Project\Project.ssmssln.

4. In Solution Explorer, double-click the query 51 - Lab Exercise 1.sql. (If Solution Explorer is not visible,
select Solution Explorer on the View menu or press Ctrl+Alt+L on the keyboard).

5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. In the query pane, type the following query after the task 1 description:

SELECT
o.custid, c.contactname
FROM Sales.Orders AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
WHERE o.empid = 5
GROUP BY o.custid, c.contactname;

7. Highlight the written query and click Execute.

 Task 3: Add an Additional Column From the Sales.Customers Table


1. Highlight the previous query. On the toolbar, click Edit and then Copy.

2. In the query window, click the line after the task 2 description. On the toolbar, click Edit and
then Paste.

3. Modify the T-SQL statement so that it adds an additional column. Your query should look like this:

SELECT
o.custid, c.contactname, c.city
FROM Sales.Orders AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
WHERE o.empid = 5
GROUP BY o.custid, c.contactname;

4. Highlight the written query and click Execute.

5. Observe the error message:


L9-2 Querying Microsoft® SQL Server®

Column 'Sales.Customers.city' is invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.

Why did the query fail? In a grouped query, you will get an error if you refer to an attribute that is not
in the GROUP BY list (such as the city column) or not an input to an aggregate function in any clause
that is processed after the GROUP BY clause.

6. Modify the SQL statement to include the city column in the GROUP BY clause. Your query should look
like this:

SELECT
o.custid, c.contactname, c.city
FROM Sales.Orders AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
WHERE o.empid = 5
GROUP BY o.custid, c.contactname, c.city;

7. Highlight the written query and click Execute.

 Task 4: Write a SELECT Statement to Retrieve the Customers with Orders for Each
Year
1. In the query pane, type the following query after the task 3 description:

SELECT
custid, YEAR(orderdate) AS orderyear
FROM Sales.Orders
WHERE empid = 5
GROUP BY custid, YEAR(orderdate)
ORDER BY custid, orderyear;

2. Highlight the written query and click Execute.

 Task 5: Write a SELECT Statement to Retrieve Groups of Product Categories Sold in a


Specific Year
1. In the query pane, type the following query after the task 4 description:

SELECT
c.categoryid, c.categoryname
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
INNER JOIN Production.Products AS p ON p.productid = d.productid
INNER JOIN Production.Categories AS c ON c.categoryid = p.categoryid
WHERE orderdate >= '20080101' AND orderdate < '20090101'
GROUP BY c.categoryid, c.categoryname;

2. Highlight the written query and click Execute.

Important note regarding the use of the DISTINCT clause:


In all the tasks in Exercise 1, you could use the DISTINCT clause in the SELECT clause as an alternative
to using a grouped query. This is possible because aggregate functions are not being requested.

Results: After this exercise, you should be able to use the GROUP BY clause in the T-SQL statement.
L9-3

Exercise 2: Writing Queries That Use Aggregate Functions


 Task 1: Write a SELECT Statement to Retrieve the Total Sales Amount Per Order
1. In Solution Explorer, double-click the query 61 - Lab Exercise 2.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT
o.orderid, o.orderdate, SUM(d.qty * d.unitprice) AS salesamount
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
GROUP BY o.orderid, o.orderdate
ORDER BY salesamount DESC;

4. Highlight the written query and click Execute.

 Task 2: Add Additional Columns


1. Highlight the previous query. On the toolbar, click Edit and then Copy.

2. In the query window, click the line after the task 2 description. On the toolbar, click Edit and
then Paste.
3. Modify the T-SQL statement so that it adds additional columns. Your query should look like this:

SELECT
o.orderid, o.orderdate,
SUM(d.qty * d.unitprice) AS salesamount,
COUNT(*) AS noofoderlines,
AVG(d.qty * d.unitprice) AS avgsalesamountperorderline
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
GROUP BY o.orderid, o.orderdate
ORDER BY salesamount DESC;

4. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement to Retrieve the Sales Amount Value Per Month
1. In the query pane, type the following query after the task 3 description:

SELECT
YEAR(orderdate) * 100 + MONTH(orderdate) AS yearmonthno,
SUM(d.qty * d.unitprice) AS saleamountpermonth
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
GROUP BY YEAR(orderdate), MONTH(orderdate)
ORDER BY yearmonthno;

2. Highlight the written query and click Execute.

 Task 4: Write a SELECT Statement to List All Customers with the Total Sales Amount
and Number of Order Lines Added
1. In the query pane, type the following query after the task 4 description:

SELECT
c.custid, c.contactname,
SUM(d.qty * d.unitprice) AS totalsalesamount,
MAX(d.qty * d.unitprice) AS maxsalesamountperorderline,
COUNT(*) AS numberofrows,
L9-4 Querying Microsoft® SQL Server®

COUNT(o.orderid) AS numberoforderlines
FROM Sales.Customers AS c
LEFT OUTER JOIN Sales.Orders AS o ON o.custid = c.custid
LEFT OUTER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
GROUP BY c.custid, c.contactname
ORDER BY totalsalesamount;

2. Highlight the written query and click Execute.

3. Observe the result. Notice that the values in the numberofrows and numberoforderlines columns are
different. Why? All aggregate functions ignore NULLs except COUNT(*), which is why you received
the value 1 for the numberofrows column. When you used the orderid column in the COUNT
function, you received the value 0 because the orderid is NULL for customers without an order.
L9-5

Exercise 3: Writing Queries That Use Distinct Aggregate Functions


 Task 1: Modify a SELECT Statement to Retrieve the Number of Customers
1. In Solution Explorer, double-click the query 71 - Lab Exercise 3.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. Highlight the provided T-SQL statement after the Task 1 description and click Execute.

4. Observe the result. Notice that the number of orders is the same as the number of customers. Why?
You are using the aggregate COUNT function on the orderid and custid columns and, since every
order has a customer, the COUNT function returns the same value. It does not matter if there are
multiple orders for the same customer because you are not using a DISTINCT clause inside the
aggregate function. If you want to get the correct number of distinct customers, you have to modify
the provided T-SQL statement to include a DISTINCT clause.
5. Modify the provided T-SQL statement to include a DISTINCT clause. The query should look like this:

SELECT
YEAR(orderdate) AS orderyear,
COUNT(orderid) AS nooforders,
COUNT(DISTINCT custid) AS noofcustomers
FROM Sales.Orders
GROUP BY YEAR(orderdate);

6. Highlight the written query and click Execute.

 Task 2: Write a SELECT Statement to Analyze Segments of Customers


1. In the query pane, type the following query after the task 2 description:

SELECT
SUBSTRING(c.contactname,1,1) AS firstletter,
COUNT(DISTINCT c.custid) AS noofcustomers,
COUNT(o.orderid) AS nooforders
FROM Sales.Customers AS c
LEFT OUTER JOIN Sales.Orders AS o ON o.custid = c.custid
GROUP BY SUBSTRING(c.contactname,1,1)
ORDER BY firstletter;

2. Highlight the written query and click Execute.

 Task 3: Write a SELECT Statement to Retrieve Additional Sales Statistics


1. In the query pane, type the following query after the task 3 description:

SELECT
c.categoryid, c.categoryname,
SUM(d.qty * d.unitprice) AS totalsalesamount,
COUNT(DISTINCT o.orderid) AS nooforders,
SUM(d.qty * d.unitprice) / COUNT(DISTINCT o.orderid) AS avgsalesamountperorder
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
INNER JOIN Production.Products AS p ON p.productid = d.productid
INNER JOIN Production.Categories AS c ON c.categoryid = p.categoryid
WHERE orderdate >= '20080101' AND orderdate < '20090101'
GROUP BY c.categoryid, c.categoryname;

2. Highlight the written query and click Execute.


L9-6 Querying Microsoft® SQL Server®

Results: After this exercise, you should have an understanding of how to apply a DISTINCT aggregate
function.
L9-7

Exercise 4: Writing Queries That Filter Groups with the HAVING Clause
 Task 1: Write a SELECT Statement to Retrieve the Top 10 Customers
1. In Solution Explorer, double-click the query 81 - Lab Exercise 4.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECT TOP (10)


o.custid,
SUM(d.qty * d.unitprice) AS totalsalesamount
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
GROUP BY o.custid
HAVING SUM(d.qty * d.unitprice) > 10000
ORDER BY totalsalesamount DESC;

4. Highlight the written query and click Execute.

 Task 2: Write a SELECT Statement to Retrieve Specific Orders


1. In the query pane, type the following query after the task 2 description:

SELECT
o.orderid,
o.empid,
SUM(d.qty * d.unitprice) as totalsalesamount
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
WHERE o.orderdate >= '20080101' AND o.orderdate < '20090101'
GROUP BY o.orderid, o.empid;

2. Highlight the written query and click Execute.

 Task 3: Apply Additional Filtering


1. Highlight the previous query. On the toolbar, click Edit and then Copy.
2. In the query window, click the line after the task 3 description. On the toolbar, click Edit and then
Paste.

3. Modify the T-SQL statement to apply additional filtering. Your query should look like this:

SELECT
o.orderid,
o.empid,
SUM(d.qty * d.unitprice) as totalsalesamount
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
WHERE o.orderdate >= '20080101' AND o.orderdate < '20090101'
GROUP BY o.orderid, o.empid
HAVING SUM(d.qty * d.unitprice) >= 10000;

4. Highlight the written query and click Execute.

5. Modify the T-SQL statement to include an additional filter to retrieve only orders handled by the
employee whose ID is 3. Your query should look like this:

SELECT
o.orderid,
o.empid,
SUM(d.qty * d.unitprice) as totalsalesamount
L9-8 Querying Microsoft® SQL Server®

FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
WHERE
o.orderdate >= '20080101' AND o.orderdate <= '20090101'
AND o.empid = 3
GROUP BY o.orderid, o.empid
HAVING SUM(d.qty * d.unitprice) >= 10000;

In this query, the predicate logic is applied in the WHERE clause. You could also write the predicate
logic inside the HAVING clause. Which do you think is better? Unlike with orderdate filtering, with
empid filtering, the result is going to be correct either way because you are filtering by an element
that appears in the GROUP BY list. Conceptually, it seems more intuitive to filter as early as possible.
This query then applies the filtering in the WHERE clause because it will be logically applied before
the GROUP BY clause. Do not forget, though, that the actual processing in the SQL Server engine
could be different.

6. Highlight the written query and click Execute.

 Task 4: Retrieve the Customers with More Than 25 Orders


1. In the query pane, type the following query after the task 4 description:

SELECT
o.custid,
MAX(orderdate) AS lastorderdate,
SUM(d.qty * d.unitprice) AS totalsalesamount
FROM Sales.Orders AS o
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid
GROUP BY o.custid
HAVING COUNT(DISTINCT o.orderid) > 25;

2. Highlight the written query and click Execute.

Results: After this exercise, you should have an understanding of how to use the HAVING clause.
L15-1

Module 15: Executing Stored Procedures


Lab: Executing Stored Procedures
Exercise 1: Using the EXECUTE Statement to Invoke Stored Procedures
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab15\Starter folder, right-click Setup.cmd and then click Run as administrator.

3. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Create and Execute a Stored Procedure


1. Start SQL Server Management Studio and connect to the MIA-SQL database engine using Windows
authentication.

2. On the File menu, click Open and click Project/Solution.

3. In the Open Project window, open the project D:\Labfiles\Lab15\Starter\Project\Project.ssmssln.

4. In Solution Explorer, expand the Queries node then double-click the query 51 - Lab Exercise 1.sql.
(If Solution Explorer is not visible, select Solution Explorer on the View menu or press Ctrl+Alt+L on
the keyboard.)
5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. Highlight the following T-SQL code under the task 1 description:

CREATE PROCEDURE Sales.GetTopCustomers AS


SELECT TOP(10)
c.custid,
c.contactname,
SUM(o.val) AS salesvalue
FROM Sales.OrderValues AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
GROUP BY c.custid, c.contactname
ORDER BY salesvalue DESC;

7. Click Execute. You have created a stored procedure named Sales.GetTopCustomers.

8. In the query pane, type the following T-SQL code after the previous T-SQL code:

EXECUTE Sales.GetTopCustomers;

9. Highlight the written T-SQL code and click Execute. You have executed the stored procedure.

 Task 3: Modify the Stored Procedure and Execute It


1. Highlight the following T-SQL code after the task 2 description:

ALTER PROCEDURE Sales.GetTopCustomers AS


SELECT
c.custid,
c.contactname,
SUM(o.val) AS salesvalue
FROM Sales.OrderValues AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
L15-2 Querying Microsoft® SQL Server®

GROUP BY c.custid, c.contactname


ORDER BY salesvalue DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

2. Click Execute. You have modified the Sales.GetTopCustomers stored procedure.

3. In the query pane, type the following T-SQL code after the previous T-SQL code:

EXECUTE Sales.GetTopCustomers;

4. Highlight the written T-SQL code and click Execute. You have executed the modified stored
procedure.

5. Compare both the code and the result of the two versions of the stored procedure. What is the
difference between them? In the modified version, the TOP option has been replaced with the
OFFSET-FETCH option. Despite this change, the result is the same.

If some applications had been using the stored procedure in task 1, would they still work properly
after the change you applied in task 2? Yes, since the result from the stored procedure is still the
same. This demonstrates the huge benefit of using stored procedures as an additional layer between
the database and the application/middle tier. Even if you change the underlying T-SQL code, the
application would work properly without any changes. There are also other benefits of using stored
procedures in terms of performance (for example, caching and reuse of plans) and security (for
example, preventing SQL injections).

Results: After this exercise, you should be able to invoke a stored procedure using the EXECUTE
statement.
L15-3

Exercise 2: Passing Parameters to Stored Procedures


 Task 1: Execute a Stored Procedure with a Parameter for Order Year
1. In Solution Explorer, double-click the query 61 - Lab Exercise 2.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. Highlight the following T-SQL code under the task 1 description:

ALTER PROCEDURE Sales.GetTopCustomers


@orderyear int
AS
SELECT
c.custid,
c.contactname,
SUM(o.val) AS salesvalue
FROM Sales.OrderValues AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
WHERE YEAR(o.orderdate) = @orderyear
GROUP BY c.custid, c.contactname
ORDER BY salesvalue DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

4. Click Execute. You have modified the Sales.GetTopCustomers stored procedure to accept the
parameter @orderyear. Notice that the modified stored procedure uses a predicate in the WHERE
clause that isn’t a search argument. This predicate was used to keep things simple. The best practice is
to avoid such filtering because it does not allow efficient use of indexing. A better approach would be
to use the DATETIMEFROMPARTS function to provide a search argument for orderdate:

WHERE o.orderdate >= DATETIMEFROMPARTS(@orderyear, 1, 1, 0, 0, 0, 0)


AND o.orderdate < DATETIMEFROMPARTS(@orderyear + 1, 1, 1, 0, 0, 0, 0)

5. In the query pane, type the following T-SQL code after the previous T-SQL code:

EXECUTE Sales.GetTopCustomers @orderyear = 2007;

Notice that you are passing the parameter by name as this is considered the best practice. There is
also support for passing parameters by position. For example, the following EXECUTE statement
would retrieve the same result as the T-SQL code you just typed:

EXECUTE Sales.GetTopCustomers 2007;

6. Highlight the written T-SQL code and click Execute.

7. After the previous T-SQL code, type the following T-SQL code to execute the stored procedure for the
order year 2008:

EXECUTE Sales.GetTopCustomers @orderyear = 2008;

8. Highlight the written T-SQL code and click Execute.

9. After the previous T-SQL code, type the following T-SQL code to execute the stored procedure
without specifying a parameter:

EXECUTE Sales.GetTopCustomers;

10. Highlight the written T-SQL code and click Execute.

11. Observe the error message:


L15-4 Querying Microsoft® SQL Server®

Procedure or function 'GetTopCustomers' expects parameter '@orderyear', which was not supplied.
This error message is telling you that the @orderyear parameter was not supplied.

12. Suppose that an application named MyCustomers is using the exercise 1 version of the stored
procedure. Would the modification made to the stored procedure in this exercise impact the usability
of the GetCustomerInfo application? Yes. The exercise 1 version of the stored procedure did not need
a parameter, whereas the version in this exercise does not work without a parameter. To avoid
problems, you can add a default parameter to the stored procedure. That way, the MyCustomers
application does not have to be changed to support the @orderyear parameter.

 Task 2: Modify the Stored Procedure to have a Default Value for the Parameter
1. Highlight the following T-SQL code under the task 2 description:

ALTER PROCEDURE Sales.GetTopCustomers


@orderyear int = NULL
AS
SELECT
c.custid,
c.contactname,
SUM(o.val) AS salesvalue
FROM Sales.OrderValues AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
WHERE YEAR(o.orderdate) = @orderyear OR @orderyear IS NULL
GROUP BY c.custid, c.contactname
ORDER BY salesvalue DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

2. Click Execute. You have modified the Sales.GetTopCustomers stored procedure to have a default
value (NULL) for the @orderyear parameter. You have also included an additional logical expression
to the WHERE clause.

3. In the query pane, type the following T-SQL code after the previous one:

EXECUTE Sales.GetTopCustomers;

This code tests the modified stored procedure by executing it without specifying a parameter.
4. Highlight the written query and click Execute.

5. Observe the result. How do the changes to the stored procedure in task 2 influence the MyCustomers
application and the design of future applications? The changes enable the MyCustomers application
to use the modified stored procedure, and no changes need to be made to the application. The
changes add new possibilities for future applications because the modified stored procedure accepts
the order year as a parameter.

 Task 3: Pass Multiple Parameters to the Stored Procedure


1. Highlight the following T-SQL code under the task 3 description:

ALTER PROCEDURE Sales.GetTopCustomers


@orderyear int = NULL,
@n int = 10
AS
SELECT
c.custid,
c.contactname,
SUM(o.val) AS salesvalue
FROM Sales.OrderValues AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
WHERE YEAR(o.orderdate) = @orderyear OR @orderyear IS NULL
GROUP BY c.custid, c.contactname
L15-5

ORDER BY salesvalue DESC


OFFSET 0 ROWS FETCH NEXT @n ROWS ONLY;

2. Click Execute. You have modified the Sales.GetTopCustomers stored procedure to have an additional
parameter named @n. You can use this parameter to specify how many customers to retrieve. The
default value is 10.

3. After the previous T-SQL code, type the following T-SQL code to execute the modified stored
procedure:

EXECUTE Sales.GetTopCustomers;

4. Highlight the written query and click Execute.

5. After the previous T-SQL code, type the following T-SQL code to retrieve the top five customers for
the year 2008:

EXECUTE Sales.GetTopCustomers @orderyear = 2008, @n = 5;

6. Highlight the written query and click Execute.

7. After the previous T-SQL code, type the following T-SQL code to retrieve the top 10 customers for the
year 2007:

EXECUTE Sales.GetTopCustomers @orderyear = 2007;

8. Highlight the written query and click Execute.

9. After the previous T-SQL code, type the following T-SQL code to retrieve the top 20 customers:

EXECUTE Sales.GetTopCustomers @n = 20;

10. Highlight the written query and click Execute.

11. Do the applications using the stored procedure need to be changed because another parameter was
added? No changes need to be made to the application.

 Task 4: Return the Result from a Stored Procedure Using the OUTPUT Clause
1. Highlight the following T-SQL code under the task 4 description:

ALTER PROCEDURE Sales.GetTopCustomers


@customerpos int = 1,
@customername nvarchar(30) OUTPUT
AS
SET @customername = (
SELECT
c.contactname
FROM Sales.OrderValues AS o
INNER JOIN Sales.Customers AS c ON c.custid = o.custid
GROUP BY c.custid, c.contactname
ORDER BY SUM(o.val) DESC
OFFSET @customerpos - 1 ROWS FETCH NEXT 1 ROW ONLY
);

2. Click Execute.

3. Find the following DECLARE statement in the provided code:

DECLARE @outcustomername nvarchar(30);


L15-6 Querying Microsoft® SQL Server®

This statement declares a parameter named @outcustomername.

4. After the DECLARE statement, add code that uses the OUTPUT clause to return the stored procedure’s
result as a variable named @outcustomername. Your code, together with the provided DECLARE
statement, should look like this:

DECLARE @outcustomername nvarchar(30);


EXECUTE Sales.GetTopCustomers @customerpos = 1, @customername = @outcustomername
OUTPUT;
SELECT @outcustomername AS customername;

5. Highlight all three T-SQL statements and click Execute.

Results: After this exercise, you should know how to invoke stored procedures that have parameters.
L15-7

Exercise 3: Executing System Stored Procedures


 Task 1: Execute the Stored Procedure sys.sp_help
1. In Solution Explorer, double-click the query 71 - Lab Exercise 3.sql.

2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following T-SQL code after the task 1 description:

EXEC sys.sp_help;

4. Highlight the written query and click Execute.

5. In the query pane, type the following T-SQL code after the previous T-SQL code:

EXEC sys.sp_help N'Sales.Customers';

6. Highlight the written query and click Execute.

 Task 2: Execute the Stored Procedure sys.sp_helptext


1. In the query pane, type the following T-SQL code after the task 2 description:

EXEC sys.sp_helptext N'Sales.GetTopCustomers';

2. Highlight the written query and click Execute.

 Task 3: Execute the Stored Procedure sys.sp_columns


1. In the query pane, type the following T-SQL code after the task 3 description:

EXEC sys.sp_columns @table_name = N'Customers', @table_owner = N'Sales';

2. Highlight the written query and click Execute.

 Task 4: Drop the Created Stored Procedure


1. Highlight the provided T-SQL statement under the task 4 description and click Execute.

Results: After this exercise, you should have a basic knowledge of invoking different system-stored
procedures.
L15-8 Querying Microsoft® SQL Server®
L16-1

Module 16: Programming with T-SQL


Lab: Programming with T-SQL
Exercise 1: Declaring Variables and Delimiting Batches
 Task 1: Prepare the Lab Environment
1. Ensure that the 20461C-MIA-DC and 20461C-MIA-SQL virtual machines are both running, and then
log on to 20461C-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd.

2. In the D:\Labfiles\Lab16\Starter folder, right-click Setup.cmd and then click Run as administrator.

3. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

 Task 2: Declare a Variable and Retrieve the Value


1. Start SQL Server Management Studio and connect to the MIA-SQL database engine using Windows
authentication.

2. On the File menu, click Open and click Project/Solution.

3. In the Open Project window, open the project D:\Labfiles\Lab16\Starter\Project\Project.ssmssln.

4. In Solution Explorer, expand Queries, and then double-click the query 51 - Lab Exercise 1.sql (If
Solution Explorer is not visible, select Solution Explorer on the View menu or press Ctrl+Alt+L on
the keyboard).
5. When the query window opens, highlight the statement USE TSQL; and click Execute on the toolbar
(or press F5 on the keyboard).

6. In the query pane, type the following T-SQL code after the task 1 description:

DECLARE @num int = 5;


SELECT @num AS mynumber;

7. Highlight the written T-SQL code and click Execute.

8. In the query pane, type the following T-SQL code after the previous one:

DECLARE
@num1 int,
@num2 int;
SET @num1 = 4;
SET @num2 = 6;
SELECT @num1 + @num2 AS totalnum;

9. Highlight the written T-SQL code and click Execute.

 Task 3: Set the Variable Value Using a SELECT Statement


1. In the query pane, type the following T-SQL code after the task 2 description:

DECLARE @empname nvarchar(30);


SET @empname = (SELECT firstname + N' ' + lastname FROM HR.Employees WHERE empid =
1);
SELECT @empname AS employee;

2. Highlight the written T-SQL code and click Execute.

You might also like