Contenu connexe
Similaire à Sql xp 04 (20)
Sql xp 04
- 1. Using Subqueries and Managing Databases
Objectives
In this lesson, you will learn to:
Use subqueries
Use subqueries with the IN clause
Use subqueries with the EXISTS clause
Use nested subqueries
Use correlated subqueries
Use the SELECT INTO statement
Use the UNION operator
Create view, rename, and delete databases
©NIIT SQL/Lesson 4/Slide 1 of 45
- 2. Using Subqueries and Managing Databases
Subqueries
A subquery can be defined as a SELECT query that returns
a single value
Subqueries are nested within a SELECT, INSERT, UPDATE,
or DELETE statement
Subqueries can be used to retrieve data from multiple tables
and can be used as an alternative to a join
Subqueries can also be used inside the WHERE or HAVING
clause of the SELECT, INSERT, UPDATE, and DELETE
statements
©NIIT SQL/Lesson 4/Slide 2 of 45
- 3. Using Subqueries and Managing Databases
4.D.1 Using one Query in Another
List the contract recruiters who live in the same city as the
external candidate Barbara Johnson.
©NIIT SQL/Lesson 4/Slide 3 of 45
- 4. Using Subqueries and Managing Databases
Task List
Create a format for the query output
Identify the components of the query
Execute the query
Verify that the query output is as per the required results
©NIIT SQL/Lesson 4/Slide 4 of 45
- 5. Using Subqueries and Managing Databases
Create a format for the query output
Result
The required output from the query is the names of the
contract recruiters who reside in the same city as
'Barbara Johnson'
The required data is present in the ContractRecruiter and
ExternalCandidate tables
©NIIT SQL/Lesson 4/Slide 5 of 45
- 6. Using Subqueries and Managing Databases
Draft the query
Result
The required information is available in the
ExternalCandidate and ContractRecruiter tables
Therefore, the query using the SELECT statement should
be:
SELECT cName
FROM ContractRecruiter
WHERE cCity = (SELECT cCity
FROM ExternalCandidate
WHERE vFirstName = 'Barbara'
AND vLastName = 'Johnson')
©NIIT SQL/Lesson 4/Slide 6 of 45
- 7. Using Subqueries and Managing Databases
Execute the query
Action:
In the Query Analyzer window, type the query
Execute the query
©NIIT SQL/Lesson 4/Slide 7 of 45
- 8. Using Subqueries and Managing Databases
Verify that the query output is as per the required
results
Action:
Check whether:
® The required rows are displayed
©NIIT SQL/Lesson 4/Slide 8 of 45
- 9. Using Subqueries and Managing Databases
More on Subqueries
Subqueries with IN
A subquery introduced with IN returns zero or more
values
Example
SELECT Au_Id
FROM TitleAuthor
WHERE Title_Id IN
(SELECT Title_Id FROM Sales)
©NIIT SQL/Lesson 4/Slide 9 of 45
- 10. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
Subqueries with EXISTS
A subquery, when used with the EXISTS clause, always
returns data in terms of a TRUE or FALSE value
Example
SELECT Pub_Name
FROM Publishers
WHERE EXISTS (SELECT * FROM Titles
WHERE Type = 'business')
©NIIT SQL/Lesson 4/Slide 10 of 45
- 11. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
Subqueries with Aggregate Functions
Aggregate functions can also be used in subqueries
Example
SELECT Title
FROM Titles
WHERE Advance (SELECT AVG(Advance)
FROM Titles
WHERE Type = 'business')
©NIIT SQL/Lesson 4/Slide 11 of 45
- 12. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
Subqueries Restrictions
SQL Server restricts the use of certain methods and
techniques, and forces the implementation of certain
standards while using subqueries. The restrictions
imposed are:
® The column list of the SELECT statement of a
subquery introduced with a comparison operator can
include only one column
® The column used in the WHERE clause of the outer
query should be compatible with the column used in
the SELECT list of the inner query
©NIIT SQL/Lesson 4/Slide 12 of 45
- 13. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
® TheORDER BY clause and the GROUP BY clause
cannot be used in the inner query when =, !=, , =, ,
or = are used in the main query, as the inner query
may return more than one value that cannot be
handled by the outer query
©NIIT SQL/Lesson 4/Slide 13 of 45
- 14. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
Nested Subqueries
A subquery can itself contain one or more subqueries
Example
SELECT 'Author Name' = SUBSTRING
(Au_Fname, 1, 1) + '. '+ Au_Lname
FROM Authors
WHERE Au_Id IN (SELECT Au_Id
FROM TitleAuthor
WHERE Title_Id =(SELECT
Title_Id FROM Titles
WHERE Title = 'Net Etiquette'))
©NIIT SQL/Lesson 4/Slide 14 of 45
- 15. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
Correlated Subqueries
Can be defined as queries that depend on the outer
query for its evaluation
Example
SELECT Title, Type, Advance
FROM Titles t1
WHERE t1.Advance (SELECT AVG(t2.Advance)
FROM Titles t2 WHERE
t1.Type = t2.Type)
©NIIT SQL/Lesson 4/Slide 15 of 45
- 16. Using Subqueries and Managing Databases
More on Subqueries (Contd.)
Queries With Modified Comparison Operators
SQL Server provides the ALL and ANY keywords that
can be used to modify the existing comparison operator
©NIIT SQL/Lesson 4/Slide 16 of 45
- 17. Using Subqueries and Managing Databases
4.D.2 Extracting Data Into Another Table
To carry out an analysis of the profile of candidates who have
applied for recruitment in May 2001, you need to copy their
details into a new table.
©NIIT SQL/Lesson 4/Slide 17 of 45
- 18. Using Subqueries and Managing Databases
Task List
Identify the output requirements of the query
Draft the query
Execute the query
Verify that the query output is as per the required results
©NIIT SQL/Lesson 4/Slide 18 of 45
- 19. Using Subqueries and Managing Databases
Identify the output requirements of the query
Result:
The required output from the query is the transfer of data
from the ExternalCandidate table to a temporary table
called tempExternalCandidate
©NIIT SQL/Lesson 4/Slide 19 of 45
- 20. Using Subqueries and Managing Databases
Draft the query
SELECT INTO Statement
A SELECT statement with the INTO clause is used to
store the result set in a new table without a data definition
process. The SELECT INTO statement creates a new
table.
Syntax
SELECT columns_list
INTO new_table_name
FROM table_name1, table_name2,………,
table_name n
WHERE condition1, condition2,……….,
condition n
©NIIT SQL/Lesson 4/Slide 20 of 45
- 21. Using Subqueries and Managing Databases
Draft the query (Contd.)
Example
SELECT Title_Id, Title
INTO NewTitles
FROM Titles
WHERE Price $15
Result:
The required information is available in the
ExternalCandidate table
Therefore, the query using the SELECT statement should
be:
©NIIT SQL/Lesson 4/Slide 21 of 45
- 22. Using Subqueries and Managing Databases
Draft the query (Contd.)
SELECT * INTO tempExternalCandidate
FROM ExternalCandidate
WHERE DATEPART(mm,dDateOfApplication)= 5
AND DATEPART(yyyy,dDateOfApplication)= 2001
©NIIT SQL/Lesson 4/Slide 22 of 45
- 23. Using Subqueries and Managing Databases
Execute the query
Action
In the Query Analyzer window, type the query
Execute the query
©NIIT SQL/Lesson 4/Slide 23 of 45
- 24. Using Subqueries and Managing Databases
Verify that the query output is as per the required
results
Action:
Check whether:
®The target table has all data from the source table
Just a Minute…
Write a query to copy all the contents of InternalCandidate to
a table called backupInternalCandidate.
©NIIT SQL/Lesson 4/Slide 24 of 45
- 25. Using Subqueries and Managing Databases
4.D.3 Combining Data From Two Tables
A list of contract recruiters and recruitment agencies along
with their phone numbers is required.
©NIIT SQL/Lesson 4/Slide 25 of 45
- 26. Using Subqueries and Managing Databases
Task List
Create a format for the query output
Draft the query
Execute the query
Verify that the query output is as per the required results
©NIIT SQL/Lesson 4/Slide 26 of 45
- 27. Using Subqueries and Managing Databases
Create a format for the query output
Result:
The required output from the query is a single list of
names and phone numbers of contract recruiters and
recruitment agencies
©NIIT SQL/Lesson 4/Slide 27 of 45
- 28. Using Subqueries and Managing Databases
Draft the query
UNION Operator
Is used to combine the result set of two or more queries
Syntax
SELECT column_list [INTO new_table_name]
[FROM clause] [WHERE clause]
[GROUP BY clause][HAVING clause]
[UNION [ALL]
SELECT column_list
[FROM clause] [WHERE clause]
[GROUP BY clause][HAVING clause]...]
[ORDER BY clause]
[COMPUTE clause]
©NIIT SQL/Lesson 4/Slide 28 of 45
- 29. Using Subqueries and Managing Databases
Draft the query (Contd.)
Result
The required information is available in the
ContractRecruiter and RecruitmentAgencies tables
Therefore, the query using the SELECT statement should
be:
SELECT cName,cPhone
FROM ContractRecruiter
UNION
SELECT cName, cPhone
FROM RecruitmentAgencies
©NIIT SQL/Lesson 4/Slide 29 of 45
- 30. Using Subqueries and Managing Databases
Execute the query
Action
In the Query Analyzer window, type the query
Execute the query
©NIIT SQL/Lesson 4/Slide 30 of 45
- 31. Using Subqueries and Managing Databases
Verify that the query output is as per the required
results
Action:
Check whether:
® All the required columns are displayed
® All rows from both tables are displayed as one list
Just a Minute…
Display the list of college names, newspaper names, and
their addresses in the following format:
Name Address
©NIIT SQL/Lesson 4/Slide 31 of 45
- 32. Using Subqueries and Managing Databases
Databases
A database is a collection of tables and objects such as
views, indexes, stored procedures, and triggers
System Databases
master Database-records all the server-specific
configuration information, including authorized users,
databases, system configuration settings, and remote
servers
tempdb Database-is a temporary database that is used
as an interim storage area
model Database-acts as a template or a prototype for the
new databases
msdb Database-supports SQL Server Agent
©NIIT SQL/Lesson 4/Slide 32 of 45
- 33. Using Subqueries and Managing Databases
Databases (Contd.)
System Tables
Are a set of tables that are used by SQL server to store
information about configuration, security, and object
information
SQL Server manages each database with the help of the
system tables, which contain all the system information
Just a Minute…
What is the purpose of model database in SQL Server?
©NIIT SQL/Lesson 4/Slide 33 of 45
- 34. Using Subqueries and Managing Databases
Databases (Contd.)
Files: The three types of files that a database has are:
® Primary
® Secondary
® Transaction Log
Filegroup: Is a collection of files
A file or filegroup cannot be used by more than one
database
A file can be a member of only one filegroup
©NIIT SQL/Lesson 4/Slide 34 of 45
- 35. Using Subqueries and Managing Databases
Creating a Database
A database can be created by using the CREATE
DATABASE statement
Syntax
CREATE DATABASE database_name
[ ON
[ filespec [ ,...n ] ]
[ , filegroup [ ,...n ] ] ]
[ LOG ON { filespec [ ,...n ] } ]
filespec ::=
©NIIT SQL/Lesson 4/Slide 35 of 45
- 36. Using Subqueries and Managing Databases
Creating a Database (Contd.)
[ PRIMARY ]
( [ NAME = logical_file_name , ]
FILENAME = 'os_file_name'
[ , SIZE = size ]
[ , MAXSIZE = { max_size | UNLIMITED } ]
[ , FILEGROWTH = growth_increment ] ) [
,...n ]
filegroup ::=
FILEGROUP filegroup_name filespec [,...n ]
©NIIT SQL/Lesson 4/Slide 36 of 45
- 37. Using Subqueries and Managing Databases
Viewing a Database
The information regarding the database such as owner, size,
date of creation, and status can be viewed using the
following:
sp_helpdb database_name
©NIIT SQL/Lesson 4/Slide 37 of 45
- 38. Using Subqueries and Managing Databases
Renaming a Database
The name of a database can be changed using the
sp_renamedb command. The database should not be in use
when it is being renamed, and it should be set to the single-
user mode
Syntax
sp_renamedb 'old_name', 'new_name'
©NIIT SQL/Lesson 4/Slide 38 of 45
- 39. Using Subqueries and Managing Databases
Deleting a Database
The DROP DATABASE statement is used to delete a
database
Syntax
DROP DATABASE database_name
Just a Minute…
List the three types of operating system files that store the
data and objects of SQL Server database.
©NIIT SQL/Lesson 4/Slide 39 of 45
- 40. Using Subqueries and Managing Databases
Modifying and displaying database options
The database options can be changed or displayed using:
sp_dboption database_name, option_name, value
Some of the database options are:
Dbo use only
Offline
Read only
Select into/bulkcopy
Single user
Trunc.log on chkpt
©NIIT SQL/Lesson 4/Slide 40 of 45
- 41. Using Subqueries and Managing Databases
Summary
In this lesson, you learned that:
Subqueries are nested within a SELECT, INSERT, UPDATE,
or DELETE statement
A subquery can be used inside the WHERE or HAVING
clauses of the outer SELECT, INSERT, UPDATE, or DELETE
statements
The subquery introduced with IN or NOT IN returns zero or
more values
The subquery used with the EXISTS clause returns data in
terms of TRUE or FALSE
©NIIT SQL/Lesson 4/Slide 41 of 45
- 42. Using Subqueries and Managing Databases
Summary (Contd.)
A subquery can contain one or more subqueries. There is no
restriction on the number of subqueries one can include with
the SELECT, INSERT, UPDATE, or DELETE statements
A correlated subquery can be defined as a query that depends
on the outer query for its evaluation
A SELECT statement with an INTO clause can be used to
store the result set in a new table without any data definition
process
The UNION operator is used to combine the result set of two
or more queries into one
©NIIT SQL/Lesson 4/Slide 42 of 45
- 43. Using Subqueries and Managing Databases
Summary (Contd.)
By default the result set of a UNION operator removes the
duplicate rows from the queries combined, unless an ALL
clause is specified with the UNION operator
A database consists of a collection of tables with data and
other objects such as views, indexes, stored procedures, and
triggers
SQL Server has the following system databases:
master
tempdb
model
msdb
©NIIT SQL/Lesson 4/Slide 43 of 45
- 44. Using Subqueries and Managing Databases
Summary (Contd.)
SQL Server stores its configuration, security, and object
information in tables called system tables
A database consists of the following types of files:
Primary data file
Secondary data file
Transaction log file
A filegroup is a collection of files. Filegroups allow files to be
grouped together
A database comprises of a primary filegroup and any user-
defined filegroup(s)
©NIIT SQL/Lesson 4/Slide 44 of 45
- 45. Using Subqueries and Managing Databases
Summary (Contd.)
Creation of a database involves determining the name of the
database, the size of the database, and the files used to store
data in the database
sp_helpdb is used to view the information regarding a
database
sp_renamedb is used to rename a database
The DROP DATABASE statement is used to delete a
database
sp_dboption is used to change or display database options
©NIIT SQL/Lesson 4/Slide 45 of 45