SQL Server Student Guide-1
SQL Server Student Guide-1
Rationale
Databases are an integral part of an organization. Aspiring
database developers should be able to efficiently
implement and maintain databases. This knowledge will
enable them to build robust database solutions.
Objectives
After completing this course, the student should be able to:
Identify SQL Server tools
Query data from a single table
Query data from multiple tables
Manage databases and tables
Manipulate data in tables
Implement indexes, views, and full-text search
Implement stored procedures and functions
Implement triggers and transactions
Implement managed code
Implement services for message-based
communication
Entry Profile
The students who want to take this course should have:
Knowledge of RDBMS concepts.
Basic knowledge of computers.
Exit Profile
Role of a Database Server
Chapter 1 Organizations have always been storing and managing
business data. Earlier, organizations used to store data on
Overview of SQL Server paper. With an increase in the usage of computers,
organizations started maintaining the same information in
In today’s competitive environment, an organization needs
computers. Data was stored in an organized way, and it
a secure, reliable, and productive data platform for its
was also easy to retrieve data faster than before. As data
business applications. SQL Server provides a platform to
retrieval became easy and fast, organizations started using
build and manage data applications. In addition, it
business or Web applications to support the business
combines data analysis, reporting, integration, and
operations.
notification services that enable organizations to build and
deploy efficient Business Intelligence (BI) solutions. Consider a scenario. A Web application might be used by
an organization to manage the data of the employees. This
This chapter discusses the importance of a database
application retrieves and manipulates the data stored in a
server. In addition, it provides an overview of SQL Server,
data source, such as MS SQL Server and Oracle. To
its components, and features. Further, this chapter
retrieve and manipulate the data stored in a data store, you
introduces the Structured Query Language (SQL) that is
need to use a data access technology in the application. A
used to manipulate the data in a database server. Lastly, it
data access technology interacts with a data source and
discusses the tools provided by SQL Server to improve the
enables you to retrieve and manipulate data through the
productivity of the database developer and manage the
application. The application can retrieve data from the
server.
data source using any of the following data access
Objectives technologies:
Language-Integrated Query (LINQ)
In this chapter, you will learn to: ADO.NET Entity Framework
Appreciate SQL Server as a database server WCF Data Services
Identify the SQL Server tools Sync Framework
All these technologies use ADO.NET at the core level.
ADO.NET further implements SQL to access data from
Introduction to SQL Server the data store.
Every organization needs to maintain information related Business or Web applications accept data as input, process
to employees, customers, business partners, or business the data based on business requirements, and provide data
transactions. Organizations build business applications or information as output. For example, an application
with a user-friendly interface to store and manipulate this maintains the details of the number of cars sold for a
information and to generate reports. For this, they need a particular brand, such as Ferrari. Each car has a unique
platform to store and maintain this information in an identification number that is already stored in an
efficient way. Various Database Management Systems application. Whenever a sale happens, the application
(DBMS) and Relational Database Management Systems checks whether the unique identification number provided
(RDBMS), such as SQL Server, Oracle, and Sybase, for the car is correct or not. If the unique identification
provide the platforms for storing and maintaining this number is correct then the sale details for the same is
information. updated in the application. The data is saved and an output
message confirming that the data has been saved is
SQL Server is a database engine introduced by Microsoft.
displayed to the user. This process of checking whether the
It provides an environment used to create and manage
unique identification number exists in the system or not is
databases. It allows secure and efficient storage and
called a business rule.
management of data. In addition, it provides other
components and services that support the business Consider another scenario. The Human Resource
intelligence platform to generate reports and help in department of an organization uses an application to
analyzing historical data and predicting future trends. manage the employee data. The users need to add the
details of new employees. For this, the application
As a database developer, it is important for you to identify
provides an interface to enter the employee details. These
the role of a database server in an organization. You can
details are validated for accuracy based on business rules.
design a database effectively if you know all the
For example, a business rule is defined to check that the
components and services of SQL Server. In addition, you
date of joining of the new employee is less than or equal to
need to understand the basics of SQL, a language that is
the current date. If the data meets the requirements, it is
used to query and manage data.
saved in the data store. only on the server and not on all the clients.
Based on the preceding scenario, a business application A two-tier architecture is also called the client-server
can have the following elements: architecture. A client sends the request for a service and a
The User Interface (UI) or the presentation server provides that service. Most RDBMSs, such as
element through which data is entered. Microsoft Access, SQL Server, and Oracle, support client-
The application logic or the business rule server architecture. RDBMS provides centralized
element, which helps in validating the entered functionality while supporting many users.
data. Three-Tier Architecture
The data storage or the data management When implementing complex business solutions in a two-
element, which manages the storage and retrieval tier architecture, the tier on which the business logic is
of data. implemented becomes over loaded. As a result, it takes
These elements form the base of the models or more time to execute. Therefore, to provide further
architectures used in application development. All these flexibility, the two-tier architecture can be split into three
elements can exist on the same computer as a single tiers. In three-tier architecture, the first tier is the client
process or on different computers as different processes. tier. The second or the middle tier is called the business
Depending on the placement of these elements, the tier. The third tier is called the server tier. The server tier
application architecture can be categorized as: contains a database server that manages the data.
Single-tier architecture In this architecture, an additional tier called a business tier
Two-tier architecture has been added between the client tier and the server tier,
Three-tier architecture as shown in the following figure.
N-tier architecture
Single-Tier Architecture
In a single-tier architecture, all elements of a business
application are combined as a single process. If multiple
users need to work on this application then it needs to be
installed on the computer of every user. This type of
architecture has one disadvantage. In case some errors are
identified in the application then after rectifying the same,
the application has to be installed again on the system of
every user. This is a time-consuming process.
Two-Tier Architecture
To solve the problems of single-tier application, two-tier
architecture was introduced. In two-tier architecture, the
application is divided into two parts. One part handles the
data, while the other provides the user interface. A Three-Tier Client/Server Architecture
Therefore, this architecture is called two-tier architecture.
The business tier consists of all the business rules. It
These two parts can be located on a single computer or on
consists of the application logic that implements business
separate computers over a network. The part that handles
rules and validates the data. The advantage of a three-tier
the UI is called the client tier. The part that implements
application is that it allows you to change the business
the application logic and validates the input data based on
rules without affecting the other two tiers.
the business rules is called the server tier, as shown in the
For example, in a banking application for loans, the user
following figure.
tier is the frontend used by the customer to specify the
loan details. The server tier can consist of an RDBMS in
which the data is stored. The business tier lies between the
other two tiers and consists of business rules, such as the
loan limit and the interest rate charged to a customer. If
there is a change in the rate of interest, only the middle tier
component needs to be modified.
N-Tier Architecture
As the business complexities increased, the business tier
A Two-Tier Architecture became larger and unmanageable. This led to the evolution
In the preceding architecture, the maintenance, upgrade, of n-tier architecture, where the business services model
and general administration of data is easier, as it exists was divided into smaller manageable units. N-tier
architecture is also called a multi-tier architecture.
In this architecture, one component near the client tier is
responsible to do the client side validation and send the
data to the presentation tier. Therefore, it is possible to
keep the UI-centric processing component on a computer
near the client. The UI-centric processing component is
responsible for processing the data retrieved from and sent
to the presentation tier. In addition, you may have another
component near the database server to manipulate and
validate the data. You can keep the data-centric processing
components on another computer near the database server,
so that you gain significant performance benefits. Data-
centric processing components are responsible for
accessing the data tier to retrieve, modify, and delete data
to and from the database server.
The n-tier architecture consists of the following layers:
Client tier The Architecture of the Web Applications
UI-centric processing components Depending on the type of business rules, the applications
Data-centric processing objects can be implemented on any of the tiers, such as Web
Database server clients, Web server, or the database server.
The banking application, when further expanded, can To provide support to applications where users can send
represent an example of n tier architecture. The client tier requests simultaneously, the database server needs to be
would consist of the user interface, which would include fast, reliable, and secure. SQL Server is one such complete
the user interface controls, such as forms, menus, and database platform that provides a fast, reliable, and secure
toolbars. The server tier would consist of data-handling RDBMS. It also helps in data analysis with integrated BI
including saving data to the database server. tools. The BI tools are used to prepare reports that are
The business logic would include the rules and guidelines analyzed further to make efficient business decisions.
for different types of accounts, interest rates, fixed
deposits, ATMs, and loan rules. All of these would form
the middle tier. However, there would be some rules that SQL Server Elements
need to be implemented both on the user interface and on SQL Server contains a number of elements. Each element
the database. You can place these rules either on the UI- in SQL Server provides various tools and services to
centric processing components or data-centric processing improve the database efficiency. The various elements in
components, based on the functionality. SQL Server, such as SQL Server Database Engine,
Applications that follow multi-tier architecture can be Analysis services, and SQL Server Data tools, working
used across various locations. For example, in Web together constitute its architecture. However, you need to
applications, an application is stored on the Web server. understand the most important and basic elements of SQL
The clients access the application from any location Server that are frequently used while querying data.
through a browser. The clients make requests to the Web SQL Server has the following elements:
server and receive responses.
The following figure shows the architecture of the Web
Services
Services are the applications that are started automatically
applications.
during the startup of the computer system. Services
provide support to create and manage databases in
different environments. Multiple services are set up on the
computer system when the SQL Server is installed, which
includes some of the following services:
SQL Server Database Engine: It provides
support to store, query, process, and secure data
on a database server. It allows you to create and
manage database objects such as tables, views,
stored procedures, and triggers.
SQL Server Agent: It is used to automate
administrative tasks by creating and managing
jobs, alerts, and operators.
SQL Server Data Tools: It allows developers to
create, debug, and maintain databases and
database objects using an integrated development
environment offered by Microsoft Visual Studio.
Instances
An instance is the basic unit of program installation and
program execution. It is a copy of the .EXE file that
represents the programs and resources supported on SQL
Server. You can install multiple instances of SQL Server
on a single computer. Each instance is segregated from
other instances based on disk files usage and resources
allocation. SQL Server provides the following types of
instances:
Default Instance: The default instance of SQL The Components of SQL Server
Server is identified by the name of the computer As shown in the preceding figure, SQL Server consists of
on which the instance is running. SQL Server the following core components:
allows you to install only one default instance of Database engine
SQL Server on a system. Integration services
Named Instances: The named instance of SQL Analysis services
Server is identified by both, the computer name Reporting services
and the instance name. SQL Server allows you to Master Data services
create more than one named instance of SQL Database Engine
Server on a system. A database engine provides support to store, query,
Tools process, and secure data on a database server. It allows
SQL Server provides various tools that enable you to you to create and manage database objects, such as tables,
query and manage the database engine. These tools are: views, stored procedure, and triggers. Apart from
SQL Server Management Studio: It is a providing support for data management, a database engine
powerful tool that provides a simple and also provides the following background services:
integrated environment to develop and manage Service Broker: Provides support for
the SQL Server database objects. asynchronous communication between clients
SQLCMD Tool: It allows you to execute T-SQL and the database server, thereby enabling reliable
statements at the command prompt mode. query processing. The client application sends a
SQL Server Configuration Manager Tool: It request to the database server and continues to
manages utility services, such as client network work. These requests are queued up at the server
utility, server network utility, and service manager in case the server is not available to process the
utility services. request immediately. A Service Broker ensures
SQL Server Installation Center: It provides you that the request is processed whenever the server
the ability to add, delete, or modify the features of is available.
SQL Server, such as adding a new feature to an The following figure shows the implementation
existing server or upgrading SQL Server. of Service Broker in the order processing system.
Components Description
Object Explorer An Object Explorer window
provides the ability to
register, browse, and
manage servers. Using
Object Explorer, you can
also create, browse, and
manage server components. window provides an
The Object Explorer allows organized view of your
you to configure the projects and files. In this
following components: explorer, you can right-click
Security: Used to on a project or file to
create login and manage or set their
users, and to assign properties.
permissions. Query Editor The Query Editor window
Replication: Used provides the ability to
to create and execute queries written in T-
manage publishers SQL. It can be invoked by
and subscribers. selecting the New Query
SQL Server Agent: option from the File menu or
Used to automate the New Query button from
administrative tasks the Standard toolbar.
by creating and Template Explorer The Template Explorer
managing jobs, window provides a set of
alerts, and templates of SQL queries to
operators. perform standard database
Management: operations. You can use
Used to configure these queries to reduce the
Distributed time spent in creating
Transaction queries.
Coordinator, Dynamic Help The Dynamic Help window
Database Mail is available from the Help
service, or SQL menu of SQL Server
Server logs. In Management Studio. This
addition, it is used tool automatically displays
for managing links to relevant information
policies and while users work in the
governing Management Studio
resources of SQL environment.
Server.
Server Objects: The Components of the SQL Server Management Studio
Used to create and Interface
manage backups,
endpoints, and
triggers. Task 1.1: Opening SQL Server
Object Explorer Details The Object Explorer Details Management Studio
provide the detailed
description of all the objects
in SQL Server.
Registered Servers The Registered Servers
SQL Server Data Tools
window displays all the SQL Server Data Tools (SSDT) is a replacement for
servers registered with the Business Intelligence Development Studio and is used to
management studio. It also work with relational databases and BI projects. It allows
helps record connection developers to create, debug, and maintain databases and
information for each database objects by using an integrated development
registered server including environment offered by MS Visual Studio. SQL Server
the authentication type, Object Explorer in Visual Studio gives a view of the
default database, network database objects. This view is similar to as offered by SQL
protocol characteristics, Server management studio. Database objects like tables,
encryption, and time-out views, or procedures can be created, modified, or deleted
parameters. by using the options available in SQL Server Object
Solution Explorer The Solution Explorer Explorer. SSDT offers tools and project types to work with
the Analysis, Reporting, and Integration services.
Therefore, SSDT has combined various database
development tools into a single IDE.
Reference Reading
Introduction to SQL Server
The Numeric Data Types Unicode is an industry wide computing standard for
representing characters. It provides unique number to every
Character and String character so that these characters are represented in the
The character and string data types allow you to store text same way across different platforms and languages.
values in the database. The following table lists the
character and string data types supported by SQL Server. Date and Time
The date and time data types allow you to store date and
time values in the database. The following table lists the
date and time data types supported by SQL Server.
where,
expression1 and expression2 are any valid
combination of a constant, a variable, a function, or a
column-based expression.
The Output Derived After Using the Select Query In the WHERE clause, you can use a comparison operator
to specify a condition. The following SQL query retrieves
records from the Employee table where the vacation hour
Retrieving Selected Rows is less than 5:
SELECT EmployeeID, NationalIDNumber,
In a given table, a column can contain different values in Title, VacationHours FROM
different records. At times, you might need to view only HumanResources.Employee WHERE
those records that match a condition. For example, in a VacationHours < 5
manufacturing organization, an employee wants to view a The preceding query retrieves all the rows that satisfy the
list of products from the Products table that are priced specified condition by using the comparison operator, as
between $ 100 and $ 200. Consider another example, shown in the following figure.
where a teacher wants to view the names and the scores of
the students who scored more than 80%. Therefore, the
query must select the names and the scores from the table
with a condition added to the score column.
To retrieve selected rows based on a specific condition,
you need to use the WHERE clause in the SELECT
statement. Using the WHERE clause selects the rows that
satisfy the condition.
The following SQL query retrieves the department details
from the Department table, where the group name is
Research and Development:
SELECT * FROM
HumanResources.Department WHERE
GroupName = 'Research and Development' The Output Derived After Using the Select Query
The following figure shows the output of the preceding The following table lists the comparison operators
query. supported by SQL Server.
Operators Description
= Equal to
> Greater than
The Output Derived After Using the Select Query < Less than
In the preceding figure, the rows containing the Research >= Greater than or equal to
and Development group name are displayed. <= Less than or equal to
Using Comparison Operators to <>, != Not equal to
!< Not less than
Specify Conditions
!> Not greater than
You can specify conditions in the SELECT statement to
The Comparison Operators Supported by SQL Server The following SQL query retrieves records from
Sometimes, you might need to view records for which one the Department table when the GroupName is not
or more conditions hold true. Depending on the Quality Assurance:
requirements, you can retrieve records based on the SELECT * FROM
following conditions: HumanResources.Department WHERE
Records that match one or more conditions NOT GroupName = 'Quality
Records that contain values in a given range Assurance'
Records that contain any value from a given set The preceding query retrieves all the rows except
of values the rows that match the condition specified after
Records that match a pattern the NOT conditional expression.
Records that contain NULL values Retrieving Records That Contain
Records to be displayed in a sequence
Records from the top of a table
Values in a Given Range
Records without duplication of values Range operators retrieve data based on a range. The syntax
for using range operators in the SELECT statement is:
Retrieving Records that Match One or SELECT column_list
More Conditions FROM table_name
Logical operators are used in the SELECT statement to WHERE expression1 range_operator
retrieve records based on one or more conditions. While expression2 AND expression3
querying data, you can combine more than one logical
operator to apply multiple search conditions. In a SELECT
statement, the conditions specified in the WHERE clause where,
is connected by using the logical operators. The syntax for
using logical operators in the SELECT statement is:
SELECT column_list expression1, expression2, and expression3
FROM table_name are any valid combination of constants, variables,
WHERE conditional_expression1 {AND/OR} functions, or column-based expressions.
[NOT] range_operator is any valid range operator.
conditional_expression2 Range operators are of the following types:
where, BETWEEN: Specifies an inclusive range to
conditional_expression1 and search.
conditional_expression2 are any conditional The following SQL query retrieves records from
expressions. the Employee table where the number of hours
The three types of logical operators are: that the employees can avail to go on a vacation
OR: Returns a true value when at least one is between 20 and 50:
condition is satisfied. For example, the following SELECT EmployeeID, VacationHours
SQL query retrieves records from the Department FROM HumanResources.Employee
table when the GroupName is either WHERE VacationHours BETWEEN 20
Manufacturing or Quality Assurance: AND 50
SELECT * FROM NOT BETWEEN: Excludes the specified range
HumanResources.Department WHERE from the result set.
GroupName = 'Manufacturing' OR The following SQL query retrieves records from
GroupName = 'Quality Assurance' the Employee table where the number of hours
AND: Is used to join two conditions and returns a that the employees can avail to go on a vacation
true value when both the conditions are satisfied. is not between 40 and 50:
To view the details of all the employees of SELECT EmployeeID,VacationHours
AdventureWorks who are married and working as FROM HumanResources.Employee
a Production Technician – WC60, you can use the WHERE VacationHours NOT BETWEEN
AND logical operator, as shown in the following 40 AND 50
query: Retrieving Records That Contain Any
SELECT * FROM
HumanResources.Employee WHERE
Value from a Given Set of Values
Title = 'Production Technician - Sometimes, you might want to retrieve data after
WC60' AND MaritalStatus = 'M' specifying a set of values to check whether the specified
value matches any data of the table. This type of operation
NOT: Reverses the result of the search condition.
is performed by using the IN and NOT IN keywords. The
syntax for using the IN and NOT IN keywords in the name is five characters long and begins with ‘Sale’,
SELECT statement is: whereas the fifth character can be anything. For this, you
SELECT column_list need to use the ‘_’ wildcard character, as shown in the
FROM table_name following query:
WHERE expression list_operator SELECT * FROM
(‘value_list’) HumanResources.Department WHERE Name
where, LIKE 'Sale_'
expression is any valid combination of constants, The following table describes the wildcard characters that
variables, functions, or column-based expressions. are used with the LIKE keyword in SQL server.
list_operator is any valid list operator, IN or NOT
IN. Wildcard Description
value_list is the list of values to be included or % Represents any string of
excluded in the condition. zero or more character(s).
The IN keyword selects the values that match any one of _ Represents any single
the values given in a list. The following SQL query character.
retrieves the records of employees who are Recruiter, [] Represents any single
Stocker, or Buyer from the Employee table: character within the
SELECT EmployeeID, Title, LoginID FROM specified range.
HumanResources.Employee WHERE Title IN
[^] Represents any single
('Recruiter', 'Stocker', 'Buyer')
character not within the
Alternatively, the NOT IN keyword restricts the selection
specified range.
of values that match any one of the values in a list. The
following SQL query retrieves records of employees
The Wildcard Characters Supported by SQL Server
whose designation is not Recruiter, Stocker, or Buyer:
SELECT EmployeeID, Title, LoginID FROM The wildcard characters can be combined into a single
HumanResources.Employee WHERE Title expression with the LIKE keyword. The wildcard
NOT IN ('Recruiter', 'Stocker', characters themselves can be searched using the LIKE
'Buyer') keyword by putting them into square brackets ([]).
The following table describes the use of the wildcard
Retrieving Records That Match a characters with the LIKE keyword.
Pattern
When retrieving data, you can view selected rows that Expression Returns
match a specific pattern. For example, you are asked to LIKE ‘LO%’ All names that begin with
create a report that displays the names of all the products “LO”
of AdventureWorks beginning with the letter P. You can do LIKE ‘%ion’ All names that end with
this by using the LIKE keyword. The LIKE keyword is “ion”
used to search a string by using wildcards. Wildcards are
LIKE ‘%rt%’ All names that have the
special characters, such as ‘*’ and ‘%’. These characters
letters “rt” in them
are used to match patterns.
LIKE ‘_rt’ All three letter names
The LIKE keyword matches the given character string
ending with “rt”
with the specified pattern. The pattern can include
combination of wildcard characters and regular characters. LIKE ‘[DK]%’ All names that begin with
While performing a pattern match, regular characters must “D” or “K”
match the characters specified in the character string. LIKE ‘[A D]ear’ All four letter names that
However, wildcard characters are matched with fragments end with “ear” and begin
of the character string. with any letter from “A”
For example, if you want to retrieve records from the through “D”
Department table where the values of Name column begin LIKE ‘D[^c]%’ All names beginning with
with ‘Pro’, you need to use the ‘%’ wildcard character, as “D” and not having “c” as
shown in the following query: the second letter.
SELECT * FROM
HumanResources.Department WHERE Name The Use of the Wildcard Characters with the LIKE Keyword
LIKE 'Pro%'
Consider another example, where you want to retrieve the
The Like operator is not case-sensitive. For example,
rows from the Department table in which the department Like 'LO%' and Like 'lo%' will return the same result.
The Contact Table
The contact details contain the residential, office, and
mobile number of an employee. If the employee does not
have any of the contact numbers, it is substituted with a
null value. Now, you want to display a result set by
substituting all the null values with zero. To perform this
task, you can use the ISNULL() function. The ISNULL()
function replaces the null values with the specified
replacement value. The syntax for using the ISNULL()
Retrieving Records That Contain NULL function in the SELECT statement is:
ISNULL ( check_expression ,
Values replacement_value )
A NULL value in a column implies that the data value for
where,
the column is not available. You might be required to find
check_expression is the expression to be checked
records that contain null values or records that do not
contain NULL values in a particular column. In such a for null.
case, you can use the unknown_value_operator in your replacement_value is the value that replaces the
queries. null values in the resultset.
The syntax for using the unknown_value_operator in the For example, the following SQL query replaces the null
SELECT statement is: values with zero in the query output:
SELECT column_list SELECT EmployeeID, ISNULL(Residence,
FROM table_name 0) AS Residence, ISNULL(Office, 0.00)
WHERE column_name AS Office, ISNULL(Mobile Number, 0.00)
unknown_value_operator AS Mobile Number FROM Contact
where, The following figure displays the output of the preceding
unknown_value_operator is either the keyword IS query.
NULL or IS NOT NULL.
The following SQL query retrieves only those rows from
the EmployeeDepartmentHistory table for which the value
in the EndDate column is NULL:
SELECT EmployeeID, EndDate FROM
HumanResources.EmployeeDepartmentHisto
ry WHERE EndDate IS NULL
The Output Derived After Using the ISNULL()
No two NULL values are equal. You cannot compare Consider another example, the following SQL query
one NULL value with another. replaces the null values with zero in the SalesQuota
column in the query output:
NULL values are always the first item to be displayed in the SELECT SalesPersonID, ISNULL
output that is sorted in an ascending order. (SalesQuota, 0.00) AS 'Sales Quota'
At times, you might need to handle the null values in a FROM Sales.SalesPerson
table quiet differently. For example, the contact details of The following figure displays the output of the preceding
the employees are stored in the following Contact table. query.
the Contact table:
SELECT EmployeeID, COALESCE(Residence,
Office ,Mobile_Number)AS
Contact_Number FROM Contact
<offset_fetch> ::=
OFFSET [ integer_constant |
offset_row_count_expression ] [ ROW |
ROWS]
FETCH [ FIRST | NEXT ]
[integer_constant |
fetch_row_count_expression ] [ ROW
| ROWS ] ONLY
where,
OFFSET specifies the number of rows to be excluded
before the query execution. The value can be an integer
constant or an expression. The Output Derived After Using the OFFSET and FETCH
CLAUSES
FETCH specifies the number of rows to be returned in the
query execution. The value can be an integer constant or
an expression. FIRST and NEXT are similar. You can use It is mandatory to use ORDER BY clause with the
either of them with the FETCH clause. Similarly, ROW OFFSET and FETCH clause.
and ROWS are same, use either of them.
For example, you want to retrieve the records of
employees from the Employee table. But, you do not want FETCH clause can be used only with the OFFSET
to include the first 15 records in the result set. In such a clause.
case, you can use the OFFSET clause to exclude the first
15 records from the result set, as shown in the following
query:
Select
EmployeeID,NationalIDNumber,ContactID
,HireDate from HumanResources.Employee
Order By EmployeeID
OFFSET 15 ROWS
The following figure displays the output of the preceding
query.
Retrieving Records Without Duplication
of Values Task 2.1: Displaying Query
You can use the DISTINCT keyword when you need to Results in Different Formats
eliminate rows with duplicate values in a column. The
DISTINCT keyword eliminates the duplicate rows from
the result set. The syntax of the DISTINCT keyword is:
SELECT [ALL|DISTINCT] column_names Activity 2.1: Retrieving Data
FROM table_name
WHERE search_condition
where, Using Functions to Customize the
DISTINCT keyword specifies that only the records
containing non-duplicated values in the specified column Result Set
are displayed. While querying data from SQL Server, you can use
The following SQL query retrieves all the Titles beginning various in-built functions provided by SQL Server to
with PR from the Employee table: customize the result set. Customization includes changing
SELECT DISTINCT Title FROM the format of the string or date values or performing
HumanResources.Employee WHERE Title calculations on the numeric values in the result set. For
LIKE 'PR%' example, if you need to display all the text values in upper
The execution of the preceding query displays a title only case, you can use the upper() string function. Similarly, if
once. you need to calculate the square of the integer values, you
If the DISTINCT keyword is followed by more than one can use the power() mathematical function.
column name, then it is applied to all the columns. You Depending on the utility, the in-built functions provided
can specify the DISTINCT keyword only before the select by SQL Server are categorized as string functions, date
list. functions, mathematical functions, ranking functions, and
system functions.
Grouping Data
The Output Derived After Executing the Query
At times, you need to view data matching specific criteria The GROUP BY...HAVING clause is same as the
to be displayed together in the result set. For example, you SELECT...WHERE clause. The GROUP BY clause
want to view a list of all the employees with details of collects data that matches the condition and summarizes it
employees of each department displayed together. into an expression to produce a single value for each
You can group the data by using the GROUP BY, group. The HAVING clause eliminates all those groups
ROLLUP, CUBE, and PIVOT clauses of the SELECT that do not match the specified condition.
statement. The following query retrieves all the titles along with their
GROUP BY average vacation hours when the vacation hours are more
The GROUP BY clause summarizes the result set into than 30 and the group average value is greater than 55:
groups, as defined in the SELECT statement, by using SELECT Title, 'Average Vacation Hours'
aggregate functions. The HAVING clause further restricts = avg(VacationHours) FROM
the result set to produce the data based on a condition. The HumanResources.Employee WHERE
syntax of the GROUP BY clause is: VacationHours > 30 GROUP BY Title
SELECT column_list HAVING avg(VacationHours) >55
FROM table_name The GROUP BY clause can be applied on multiple fields.
WHERE condition You can use the following query to retrieve the average
[GROUP BY [ALL] expression [, value of the vacation hours that is grouped by Title and
expression] ManagerID in the Employee table:
[HAVING search_condition] SELECT Title, 'Manager ID' =
where, ManagerID, Average = avg
ALL is a keyword used to include those groups that do not (VacationHours) FROM
meet the search condition. HumanResources.Employee GROUP BY
expression specifies the column name(s) or Title, ManagerID
expression(s) on which the result set of the SELECT The following figure displays the output of the preceding
statement is to be grouped. query.
search_condition is the conditional expression on
which the result is to be produced.
The following SQL query returns the minimum and
maximum values of vacation hours for the different types
of titles where the number of hours that the employees can
avail to go on a vacation is greater than 80:
SELECT Title, Minimum = min
(VacationHours), Maximum = max
(VacationHours) FROM
HumanResources.Employee WHERE
VacationHours > 80 GROUP BY Title
The EmpTable Table
You want to view the average salary of the employees
combined for each region and department. You also want
to view the average salary of the employees regionwise
and departmentwise. To view the average salary of the
employees combined for each region and department, you
can use the following query:
The Output Derived After Executing the Query
SELECT Region, Department, avg(sal)
If you want to display all those groups that are excluded
AverageSalary
by the WHERE clause, then you can use the ALL keyword FROM EmpTable
along with the GROUP BY clause. GROUP BY
For example, the following query retrieves the records for Region, Department
the employee titles that are eliminated in the WHERE To view the average salary of the employees for each
condition: region, you can use the following query:
SELECT Title, VacationHours = sum SELECT Region, avg(sal) AverageSalary
(VacationHours) FROM FROM EmpTable
HumanResources.Employee WHERE Title IN GROUP BY
('Recruiter', 'Stocker', 'Design Region
Engineer') GROUP BY ALL Title ORDER BY
To view the average salary of the employees for each
sum (VacationHours)DESC
department, you can use the following query:
The following figure displays the output of the preceding SELECT Department, avg(sal)
query. AverageSalary
FROM EmpTable
GROUP BY
Department
Using the preceding queries, you can view the average
salary of the employees based on different grouping
criteria. If you want to view the results of all the previous
three queries in a single result set, you need to perform the
union of the results generated from the preceding queries.
However, instead of performing the union of the results,
you can use the GROUPING SET clause, as shown in the
following query:
SELECT Region, Department, AVG(sal)
AverageSalary
FROM EmpTable
GROUP BY
The Output Derived After Executing the Query GROUPING SETS
(
(Region, Department),
If you write the preceding query using GROUP BY
(Region),
clause, it will display three records.
(Department)
The GROUPING SETS clause is used to combine the )
result generated by multiple GROUP BY clauses into a The following figure displays the output of the preceding
single result set. For example, the employee details of the query.
organization are stored in the following EmpTable table.
102 2008 120000.00
102 2009 110000.00
103 2007 105000.00
103 2008 180000.00
103 2009 160000.00
104 2007 170000.00
104 2008 120000.00
104 2009 150000.00
PIVOT
The database users might need to view data in a user-
defined format. These reports might involve summarizing
data on the basis of various criteria. SQL Server allows The Output Derived After Using the PIVOT Operator
you to generate summarized data reports using the PIVOT Unpivot
clause of the SELECT statement. The UNPIVOT operator allows database users to
The PIVOT clause is used to transform a set of columns normalize the data that has earlier been pivoted. This
into values. PIVOT rotates a table-valued expression by operator transforms the multiple column values of a record
turning the unique values from one column in the into multiple records with the same values in a single
expression into multiple columns in the output. In column. For example, consider a table named Applicant
that stores the details of applicants. This table stores the
applicant‘s name and grade secured by the applicants in
matriculation, higher secondary, and graduation.
The following table shows the data stored in the Applicant
table.
Summary
In this chapter, you learned that:
Data type represents the type of data that a
database object can contain.
You can store the following types of data in a
database:
Structured data
Semi-structured data
Unstructured data
Data can be retrieved from a database by using
The Output Derived After Using the UNPIVOT Operator
the SELECT statement.
In the preceding figure, the table contains different rows Data of all the columns of a table can be retrieved
for each qualification that the applicant has completed. by specifying * in the SELECT statement.
Data that has to be retrieved based on a condition
is specified by adding the WHERE clause.
Synonyms are created to refer to a database tables.
object easily. The aggregate functions, such as avg(), count(),
Literals and user-defined headings are added to min(), max(), and sum() are used to retrieve
change the display. summarized data.
The concatenation operator is used to concatenate The GROUP BY, GROUP BY ALL, and PIVOT
a string expression. clauses are used to group the result set.
Arithmetic operators are used to perform The GROUPING SETS clause is used to combine
mathematical operations. the results generated by multiple GROUP BY
Comparison operators test the similarity between clauses into a single result set.
two expressions. The ROLLUP and CUBE operators are used to
Logical operators are used in the SELECT apply multiple levels of aggregation on result
statement to retrieve records based on one or sets.
matching conditions. The logical operators are The UNPIVOT operator allows to normalize the
AND, OR, and NOT. data that has earlier been pivoted.
Range operators retrieve data based on a range.
There are two types of range operators,
BETWEEN and NOT BETWEEN. Reference Reading
The IN keyword allows the selection of values
that match any one of the values in a list. Retrieving Data
The NOT IN keyword restricts the selection of
values that match any one of the values in a list. Reference Reading: Books Reference Reading: URLs
The LIKE keyword is used to specify the pattern Sams Teach Yourself SQL in http://msdn.microsoft.com/
search. 24 Hours by Ryan Stephens en-us/library/
The IS NULL keyword is used to retrieve missing and Ron Plew ms189499.aspx
values.
The ORDER BY clause is used to retrieve data in
a specific order.
Using Functions to Customize the
The TOP keyword retrieves only the first set of Result Set
rows, which can either be a number or a percent
of rows that will be returned from a query result. Reference Reading: Books Reference Reading: URLs
The OFFSET-FETCH clause is used to retrieve a Microsoft SQL Server 2012 http://msdn.microsoft.com/
number of records from anywhere in the result Step by Step by Patrick en-us/library/
set. LeBlanc ms174318.aspx
The DISTINCT keyword eliminates duplicate
rows. Summarizing and Grouping Data
The string functions are used to format data in the
result set.
The date functions are used to manipulate date Reference Reading: Books Reference Reading: URLs
values. Sams Teach Yourself SQL in http://msdn.microsoft.com/
The mathematical functions are used to perform 24 Hours by Ryan Stephens en-us/library/ms191500%
numerical operations. and Ron Plew 28v=SQL.105%29.aspx
The conversion functions are used to convert a Microsoft SQL Server 2012
data from one type to another. Step by Step by Patrick
The ranking functions are used to generate LeBlanc
sequential numbers for each row or to give a rank
based on specific criteria.
You can use the following functions to rank the
records:
row_number()
rank()
dense_ rank()
ntile()
The analytical functions are used to perform
comparisons between rows in the same table.
The system functions are used to query system
inner join is applied, only the rows with values satisfying
the join condition in the common column are displayed.
The rows in both the tables that do not satisfy the join
Chapter 3 condition are not displayed.
For example, the details of movies are stored in the
Querying Data by Using Joins and following Movies table.
Subqueries MovieID MovieName YearMade
In a normalized database, data related to an entity may be 1 My Fair Lady 1964
stored in multiple tables. When you need to view data 2 Unforgiven 1992
from related tables together, you can join the tables with 3 Time Machine 1997
the help of common attributes.
You can also use subqueries where the result of a query is The Movies Table
used as an input for the condition of another query. In The details of actors are stored in the following Actors
addition, you can store the result of a query as a temporary table.
result set by using Common Table Expressions (CTE). This
temporary result set exists only within the scope of a
MovieID FirstName LastName
single SQL statement. In addition you can also use
1 Rex Harrison
Derived Tables to simplify the queries involving complex
aggregate calculations. 1 Audrey Hepburn
This chapter discusses how to query data from multiple 2 Clint Eastwood
tables by applying various types of joins, such as inner 5 Humphrey Bogart
join, outer join, cross join,equi join, or self join. Further, it
explains how to use subqueries. Lastly, this chapter The Actors Table
discusses about temporary result sets created by using If you join the Movies table and Actors table using an
CTE. inner join, the result set will be retrieved as shown in the
following table.
Objectives
In this chapter, you will learn to:
Query data by using joins
Query data by using subqueries
Manage result sets
Querying Data by Using Joins The Result Set Obtained After Joining the Movies Table and the
Actors Table
When an SQL query executes, it returns a result set. A Notice that the last row of the Actors table is not present in
result set is a set of rows retrieved from a table. As a the result set because the corresponding matching record is
database developer, you may need to retrieve data from not found in the Movies table.
more than one table and display it in a single result set. In A join is implemented by using the SELECT statement,
such a case, different columns in the result set can obtain where the SELECT list contains the names of the columns
data from different tables. To retrieve data from multiple to be retrieved from the tables. The FROM clause contains
tables, SQL Server allows you to apply joins. Joins allow the names of the tables from which combined data is to be
you to view data from related tables in a single result set. retrieved. The WHERE clause specifies the condition,
You can join more than one table based on a common with a comparison operator, based on which the tables will
attribute. be joined.
Depending on the requirements to view data from multiple The syntax of applying an inner join in the SELECT
tables, you can apply different types of joins, such as inner statement is:
join, outer join, cross join, equi join, or self join. SELECT column_name, column_name
[,column_name]
FROM table1_name JOIN table2_name
Using an Inner Join ON table1_name.ref_column_name
join_operator
An inner join retrieves records from multiple tables after
table2_name.ref_column_name
comparing values present in a common column. When an
[WHERE search_condition] The following figure displays the data of the
where, EmployeePayHistory table.
table1_name and table2_name are the names of the
tables that are joined.
join_operator is the comparison operator based on
which the join is applied.
table1_name.ref_column_name and
table2_name.ref_column_name are the names of
the columns on which the join is applied.
WHERE specifies the search condition for the rows
returned by the query.
search_condition specifies the condition to be
satisfied to return the selected rows. The EmployeePayHistory Table
The following figure displays the output of the preceding
inner join query.
An inner join is the default join. Therefore, you can
also apply an inner join by using the JOIN keyword. In
addition, you can use the INNER JOIN keyword.
Whenever a column is mentioned in a join condition, it
should be referred by prefixing it with the table name to
which it belongs or with a table alias. A table alias is used
to refer to the table with another name or to uniquely
identify the table. The table alias is defined in the FROM
clause of the SELECT statement.
When listing the column names in the SELECT statement,
it is mandatory to use a table name or a table alias if an
ambiguity arises due to duplicate column names in
multiple tables.
The following query displays the Employee ID and Title
for each employee from the Employee table, and the Rate
and PayFrequency columns from the EmployeePayHistory
table:
SELECT e.EmployeeID,e.Title, The Output Derived by Executing the Inner Join Query
eph.Rate,eph.PayFrequency Based on the relationship between tables, you need to
FROM HumanResources.Employee e JOIN select the common column to set the join condition. In the
HumanResources.EmployeePayHistory eph preceding inner join query, the common column is
ON e.EmployeeID = eph.EmployeeID EmployeeID, which are the primary key of the Employee
In the preceding query, the Employee table and the table and the foreign key of the EmployeePayHistory
EmployeePayHistory table are joined on the common table.
column, EmployeeID. The query also assigns e as an alias Observe the result set after the join. The record of the
of the Employee table and eph as an alias of the employee with EmployeeID 1 from the Employee table is
EmployeePayHistory table. The column names are also joined with the record of the employee with EmployeeID
listed with the table alias names. 1 from the EmployeePayHistory table.
The following figure displays the data of the Employee While applying joins, you can also check for other
table. conditions. The following query retrieves the employee ID
and the designation from the Employee table for all the
employees whose pay rate is greater than 40:
SELECT ‘Employee ID’ = e.EmployeeID,
‘Designation’ = e.Title
FROM HumanResources.Employee e INNER
JOIN HumanResources.EmployeePayHistory
eph
ON e.EmployeeID = eph.EmployeeID
WHERE eph.Rate>40
The Employee Table In the preceding query, the tables are joined based on the
EmployeeID column, which is common in both the tables. Actors Table
In addition, only those records are selected where the In the preceding figure, the FirstName and LastName
value in the Rate column of the EmployeePayHistory table columns have the value NULL against the movie, Time
is greater than 40. Machine. This is because there are no records of actors in
the Actors table for the Time Machine movie.
Consider another example from the AdventureWorks, Inc.
Using an Outer Join The SpecialOfferProduct table contains a list of products
that are on special offer and the SalesOrderDetail table
In comparison to an inner join, an outer join displays the
stores the details of all the sales transactions. The users at
result set containing all the rows from one table and the
AdventureWorks, Inc. need to view the transaction details
matching rows from the other table. For example, if you
of the special offer products. In addition, they want to
create an outer join on table A and table B, it will show
view the ProductID of the special offer products for which
you all the records of table A and only those records from
no transaction has been done.
table B for which the condition on the common column
To perform this task, you can use the LEFT OUTER JOIN
holds true.
keyword, as shown in the following query:
An outer join displays NULL for the columns of the
SELECT DISTINCT (p.ProductID),
related table where it does not find any matching records.
p1.SpecialOfferID, p1.SalesOrderID,
The syntax of applying an outer join is:
p1.OrderQty, p1.UnitPrice
SELECT column_name, column_name
FROM Sales.SpecialOfferProduct p LEFT
[,column_name]
OUTER JOIN
FROM table1_name [LEFT | RIGHT| FULL]
[Sales].[SalesOrderDetail] p1 ON
OUTER JOIN table2_name
p.ProductID =p1.ProductID
ON table1_name.ref_column_name
ORDER BY p.ProductID
join_operator
The following figure displays the output of the preceding
table2_name.ref_column_name
query.
[WHERE search_condition]
An outer join is of the following types:
Left outer join
Right outer join
Full outer join
Using a Left Outer Join
A left outer join returns all rows from the table specified
on the left side of the LEFT OUTER JOIN keyword and
the matching rows from the table specified on the right
side. It displays NULL for the columns of the table
specified on the right side where it does not find any
matching records.
For example, you need to display the details of all the
movies and the corresponding details of the actors who
acted in those movies. To perform this task, you can join The Output Derived After Executing the Query
the Movies table and the Actors table by using a left outer The preceding figure displays NULL for the ProductIDs
join. The Movies table will be on the left side of the LEFT for which no transaction was performed.
OUTER JOIN keyword in the query. The following figure Using a Right Outer Join
displays the result set of using the left outer join between A right outer join returns all the rows from the table
the Movies table and the Actors table. specified on the right side of the RIGHT OUTER JOIN
keyword and the matching rows from the table specified
on the left side.
For example, you need to display the details of all the
actors and the corresponding details of the movies in
which they have acted. To perform this task, you can join
the Movies table and the Actors table by using a right
outer join. The Actors table will be on the right side of the
RIGHT OUTER JOIN keyword in the query.
The Result Set Obtained After Joining the Movies Table and the The following figure displays the result set of using the
right outer join between the Movies table and the Actors
table. matching rows from both the tables. However, the
matching records are displayed only once. In case of non-
matching rows, a NULL value is displayed for the
columns for which data is not available.
For example, you need to display the details of all the
movies along with all the actors combined in a single
result set. To perform this task, you can join the Movies
table and the Actors table by using a full outer join. The
following figure displays the result set of using the full
The Result Set Obtained After Joining the Movies Table and the outer join between the Movies table and the Actors table.
Actors Table
In the preceding figure, NULL is displayed against the
MovieID, MovieName, and YearMade columns for the
actor, Humphrey Bogart. This is because there are no
records for the actor, Humphrey Bogart in the Movies
table.
Consider the example of AdventureWorks, Inc. You want
to display the IDs of all the sales persons along with the
territory assigned to them. In addition, you need to display
the IDs of all those sales persons who have not been
assigned any territory. To perform this task, you can apply The Result Set Obtained After Joining the Movies Table and the
a right outer join between the Sales.SalesTerritory table Actors Table
and the Sales.SalesPerson table, as shown in the following Consider another example of AdventureWorks, Inc. You
query: want to display the IDs of all the sales persons along with
SELECT st.Name AS Territory, the territory assigned to them. In addition, you need to
sp.SalesPersonID display the IDs of all those sales persons who have not
FROM Sales.SalesTerritory st been assigned any territory. Similarly, you need to display
RIGHT OUTER JOIN Sales.SalesPerson sp all those territories which have not been assigned to any
ON st.TerritoryID = sp.TerritoryID sales person. To perform this task, you can apply a full
The following figure displays the output of the preceding outer join between the Sales.SalesTerritory table and the
query. Sales.SalesPerson table, as shown in the following query:
SELECT st.Name AS Territory,
sp.SalesPersonID
FROM Sales.SalesTerritory st
FULL OUTER JOIN Sales.SalesPerson sp
ON st.TerritoryID = sp.TerritoryID
The following figure displays the output of the preceding
query.
The Result Set Obtained After Cross Joining the Shape Table
and Color Table
Consider another example of a storehouse that sells
computers. As a database developer, you have saved the
configuration and price details of computers in the
ComputerDetails table, as shown in the following figure.
Working with Derived Tables The Output Derived After Executing the Statement
Now, you want to view the output of both the preceding
Sometimes, obtaining data in a result set is a complicated two queries in a single result set. To perform this task,
process as it might include some complex aggregate SQL Server provides you, with the concept of derived
calculations, involving fields of one or more tables. A tables. The derived tables is a virtual table, created by
simple query might not help in such a case. Therefore, you using a SELECT statement and is given an alias name
may need to simplify the process by using temporary using the AS clause. It is also referred to as the inline
tables or views. For example, the SalesOrderDetail table views. It can be referenced as a regular table or a view in
of the AdventureWorks database contains the details of the the SELECT statement. The derived table has its scope
orders placed by the customers. You want to find out the restricted within the query, can be used only within the
total quantity ordered and the total orders placed for a query, and ceases to exist once the query has finished
particular product. To accomplish this task, you need to executing. Unlike temporary tables or views, there is no
first use the following SQL statement to retrieve the total overhead of creation, deletion, or data insertion.
quantity ordered for the product: For example, consider the following statements:
SELECT ProductID, SUM(OrderQty) AS SELECT
TotalQuantityOrdered FROM Table1.Productid,TotalQuantityOrdered,
Sales.SalesOrderDetail TotalSalesOrdersPlaced
GROUP BY ProductId FROM
The following figure displays the output of the preceding (SELECT ProductID,SUM(OrderQty) AS
statement. TotalQuantityOrdered FROM
Sales.SalesOrderDetail
GROUP BY ProductId
)AS Table1
INNER JOIN
(SELECT ProductID,SUM(OrderQty) AS
TotalSalesOrdersPlaced FROM
Sales.SalesOrderDetail
GROUP BY ProductId ,SalesOrderId
) AS Table2
ON Table1.ProductID=Table2.ProductID
The following steps describe the execution of the
preceding statements:
1. The FROM clause of the preceding statement
creates two derived tables named, Table1 and joined with each row from the second table.
Table2. In an equi join, only the equality operator is used
2. The derived table, Table1, selects the total to specify the join condition.
number of orders placed for each product from A self join correlates one row in a table with other
the Sales.SalesOrderDetail table. rows in the same table.
3. The derived table, Table2, selects the total sales The IN clause in a subquery returns zero or more
orders placed for each product from the values.
Sales.SalesOrderDetail table. The EXISTS clause in a subquery returns data in
4. Finally, an inner join is used to obtain data from terms of a TRUE or FALSE value.
both the derived tables into a common result set. The ALL and ANY keywords are used in a
The following figure displays the output of the preceding subquery to modify the existing comparison
statements. operator.
Aggregate functions can also be used in
subqueries to generate aggregated values from the
inner query.
Subqueries that contain one or more queries are
specified as nested subqueries.
A correlated subquery can be defined as a query
that depends on the outer query for its evaluation.
SQL Server provides the APPLY operator that
allows you to combine the result sets retrieved
from table expressions.
There are two types of APPLY operators
supported by SQL Server. These are:
CROSS APPLY
OUTER APPLY
The Output Derived After Executing the Statement The CROSS APPLY operator returns only those
rows from the outer result set that match with the
inner result set.
Activity 3.3: Using CTE The OUTER APPLY operator returns all rows
from the outer result set even if the corresponding
row is not found in the inner result set.
The UNION operator is used to combine the data
Activity 3.4: Using Derived of two or more queries into a single result set.
The EXCEPT operator compares two result sets
Tables and returns the data from the first result set that is
not found in the second result set.
The INTERSECT operator returns the common
Summary rows after comparing two result sets. If the
common rows are not found, then NULL value is
In this chapter, you learned that: returned.
Joins and subqueries are used to retrieve data A CTE is used to create a temporary named result
from multiple tables. set.
An inner join combines records from multiple In a recursive CTE, result sets of more than one
tables by using a comparison operator on a query are combined to populate the CTE.
common column. A recursive CTE consists of the following
A left outer join returns all the rows from the left members to produce the required result:
table and the matching rows from the right table. Anchor query
A right outer join returns all the rows from the Recursive query
right table and the matching rows from the left A derived table is a virtual table, which is created
table. by using the SELECT statement with an alias in
A full outer join returns all the matching and non- the AS clause.
matching rows from both the tables on which the Derived table acts as a regular table or a view.
join is applied.
A cross join returns each row from the first table
Reference Reading
Querying Data by Using Joins
Dropping a Table
At times, when a table is not required, you need to delete
it. A table can be deleted along with all the associated
database objects such as its index, triggers, constraints,
and permissions. You can delete a table by using the
DROP TABLE statement. The syntax of the DROP
TABLE statement is: Activity 4.1: Managing Tables
DROP TABLE [ database_name .
[ schema_name ] .] table_name
where, Activity 4.2: Creating a
database_name specifies the name of the database
where the table is created. Partitioned Table
schema_name specifies the name of the schema to
which the table belongs.
table_name specifies the name of the table that needs Summary
to be dropped.
In this chapter, you learned that:
When a table is deleted, any other database object
referenced by the table needs to be deleted explicitly. This A database is a repository of information that
should be done before deleting the table. This is because if contains data in an organized way.
violations occur in the rule of referential integrity while The master database records all the server-
deleting a table, then an error occurs that restricts you specific configuration information, including
from deleting the table. Therefore, if your table is authorized users, databases, system configuration
referenced, you must delete the referenced table or the settings, and remote servers.
referenced constraint, and then delete the table. The tempdb database is a temporary database that
holds all the temporary tables and stored
For example, the Employee table in the HumanResource
procedures.
schema contains EmployeeID as its primary key. The
The model database acts as a template or a A check constraint enforces domain integrity by
prototype for new databases. restricting the values to be inserted in a column.
The msdb database supports the SQL Server The IN, LIKE, and BETWEEN keywords are
Agent. SQL Server Agent includes features that used to define the check constraint.
schedule periodic activities of SQL Server. A default constraint can be used to assign a
The Resource database is a read-only database constant value to a column, and the user need not
that contains all the system objects that are insert values for such a column.
included with SQL Server. A rule provides a mechanism for enforcing
The user-defined databases are created by the domain integrity for columns or user defined data
users to store data for client/server applications. types.
A database consists of the following types of User-defined data types are custom data types
files: defined by the users with a custom name.
Primary data file A partitioned table is created to manage the data
Secondary data file and improve the query performance.
Transaction log file You can modify a partition table by:
A database must consist of a primary data file and Modifying a partition scheme and partition
one transaction log file. function.
The CREATE DATABASE statement is used to Assigning a table as a partition to an
create a database, which also includes existing partitioned table.
determining the name of the database, the size of You can modify a partition function by splitting
the database, and the files used to store data in the or merging its boundary values.
database. Before adding the table as a partition to an
The DROP DATABASE statement is used to existing partitioned table, you must ensure that:
delete a database. The source and target tables must have the
Tables are used to store data. same column structure and order.
The CREATE TABLE statement is used to create The nullability of the partitioning columns
a table. must match.
Data integrity is enforced to keep the data in a The computed columns in both the tables
database accurate, consistent, and reliable. It is must have the same syntax.
broadly classified into the following categories: The ROWGUID properties of the tables
Entity integrity: Ensures that each row can must be the same.
be uniquely identified by an attribute called The boundary values of the source partition
the primary key. must be within the boundary of target
Domain integrity: Ensures that only a partition.
valid range of values is allowed to be stored The source and target tables must have the
in a column. same FOREIGN KEY constraints.
Referential integrity: Ensures that the The ALTER TABLE statement is used to modify
value of the foreign key match the value of a table.
the corresponding primary key. The DROP TABLE statement is used to delete a
User-defined integrity: Refers to a set of table.
rules specified by a user, which do not
belong to the entity, domain, and referential
integrity categories. Reference Reading
Constraints define rules that must be followed to
maintain consistency and correctness of data. Managing Databases
A primary key constraint is defined on a column
or a set of columns whose values uniquely Reference Reading: Books Reference Reading: URLs
identify rows in a table. Microsoft® SQL Server® http://msdn.microsoft.com/
The unique constraint is used to enforce 2012 Pocket Consultant by en-us/library/cc645585.aspx
uniqueness on non-primary key columns. William R. Stanek http://msdn.microsoft.com/
A foreign key constraint associates one or more Learning SQL by Alan en-us/library/
columns (the foreign key) of a table with an Beaulieu ms179422.aspx
identical set of columns (a primary key column in
another table) on which a primary key constraint
has been defined.
Managing Tables
Reference Reading: Books Reference Reading: URLs
SQL Server 2012 T-SQL http://msdn.microsoft.com/
Recipes: A Problem- en-us/library/
Solution Approach by Jason ms174979.aspx
Dewson http://msdn.microsoft.com/
en-us/library/
ms190273.aspx
A restriction placed on a value in a database used to
increase data integrity.
Cross Join
Glossary
A A join that combines each row from one table with each
Alias row of the other table.
A temporary intra-query substitute for a table name or D
column name. Data
APPLY Operator
The operator used to combine the result set of two queries Recorded facts pertaining to entities.
such that for each row of the first query, the second query Data Definition Language (DDL)
is evaluated to determine if any rows are returned.
Arithmetic Operators A language used to define the internal schema and
The operators used to perform mathematical operations, conceptual schema in a database.
such as addition, subtraction, division, and multiplication, Data Integrity
on numeric columns or on numeric constants. The concept of maintaining consistency and completeness
Attribute of data.
Data Manipulation Language (DML)
A column in a table. A language used to manipulate data using INSERT,
B UPDATE, and DELETE statements.
Batch Data Warehouse
An application with a computer database that collects,
A group of SQL statements submitted together to the SQL integrates, and stores an organization's data with the aim
Server for execution. of producing accurate and timely management of
Business Tier information and support for analysis techniques.
Database
The middle tier in a three-tier architecture where the A collection of logically associated or related data.
business logic is implemented. Default
C A value assigned to data when no value is supplied.
Cartesian Product Dialog
A bi-directional communication between two services.
A binary operation resulting in the combination of all rows Domain
of one table with all rows of another table. The set of all possible values that a column value can
Client Tier have.
E
The tier that handles the User Interface (UI) in a client- Equi Join
server architecture. A query that combines tables with the help of a foreign
Common Language Runtime (CLR) key and displays all the columns from both the tables. Is
similar to an inner join.
The core runtime environment in the Microsoft .NET Extensible Markup Language (XML)
Framework on which the applications run. A universal language used to generically identify data that
Common Table Expression (CTE) will be shared.
F
A temporary named result set defined within the execution Filegroup
scope of a single SQL statement. A collection of database files grouped together for
Concatenation Operator allocation and administration purposes.
I
An operator that is used to combine string expressions. Inner Query
Constant A subquery that is contained in another query. The result
of the inner query is used an input for the condition
An unvarying value used in a query. specified in the outer query.
Constraint J
Join
An operation used to combine related rows from two A design of the database typically using an entity
tables into one table based on a logical comparison of relationship diagram.
column values. Self Join
L A join condition where a table is joined with itself.
Literals Server Tier
The string values, enclosed in single quotes and added to The part that implements the application logic and
the SELECT statement, are printed in a separate column as manages the input data based on the business rules in a
they are written in the SELECT list. client server architecture.
Local Variables Structured Query Language (SQL)
Variables declared in a batch that can be used in any A language for defining the structure and processing of a
statement inside the batch. relational database.
M Subquery
Managed Code The inner query within the outer (main) query; usually one
The code written in any of the .Net supported languages SELECT query within another SELECT query.
that runs within the scope of the SQL CLR. U
Managed Database Object Unmanaged Code
A database object that can be created using CLR The code that is developed without considering the
integration in any of the .NET-supported languages and conventions and requirements of the common language
then can be embedded in the database. runtime.
N
.NET Framework
A software development platform focused on rapid
application development, platform independence, and
network transparency.
NULL
A value given to a data item when the result is unknown.
O
Outer Join
An join operation that displays the result set containing all
the rows from one table and the matching rows from
another table.
Q
Query
An SQL instruction used to retrieve data from one or more
tables or views. Queries begin with the SQL keyword
SELECT.
Queue
A container used to stores messages.
R
Referential Integrity
The property that guarantees the values from one column
depending on the values from another column are present
in the other column.
Result Set
Output of an SQL statement.
Row
A horizontal slice of a table. A row is also known as a
'tuple' and at times is called a 'record'. However, a record
usually refers to a physical representation of data and a
row refers to a logical representation.
S
Schema
stored procedures Stored Procedures
(simple
statements).
Certification Mapping Modify data by 5 Manipulating
The content in this course partially covers the objectives using INSERT, Data by Using
of Microsoft Exam 70-461 (Microsoft SQL Server 2012, UPDATE, and DML Statements
Database Development). DELETE
The following table lists the relevant exam objectives and statements.
the corresponding chapter numbers and section names. Combine datasets. 5 Manipulating
Data by Using
DML Statements
Exam Objective Chapter Section
Work with 7 Implementing
Create Database
functions. Functions
Objects (24%)
Troubleshoot and
Create and alter 4 Managing Tables
Optimize (25%)
tables using T-
SQL syntax(simple Optimize Queries. 9, 6, 7 Optimizing
statements). Performance,
Creating and
Create and alter 6 Creating and
Managing
views(simple Managing Views
Indexes,
statements).
Implementing
Create and modify 4 Managing Tables
Stored Procedures
constraints(simple
Manage 8 Implementing
statements).
transactions. Transactions
Create and alter 8 Implementing
Implement error 7 Implementing
DML triggers. Triggers
handling. Batches
Working with
Evaluate the use of 7 Implementing
Data (27%)
row-based Stored Procedures
Query data by 2 Retrieving Data
operations vs set-
using SELECT
based operations.
statements.
Implement 2, 3 Querying Data by Certification Mapping
subqueries Using Subqueries,
Managing Result
Sets, Summarizing To prepare for the exam, you need to refer to the
and Grouping Student Guide as well as the Activity Book.
Data
Implement data 2, 4, 5 Retrieving Data,
types. Managing Tables,
Manipulating
Data by Using
DML Statements
Implement 2, 4 Summarizing and
aggregate queries. Grouping Data,
Using Functions
to Customize the
Result Set,
Managing Tables
Query and 5 Manipulating
Manage XML XML Data
data.
Modify Data
(24%)
Create and alter 7 Implementing