SQL/Lesson 4/Slide 1 of 45 Using Subqueries and Managing Databases Objectives In this lesson, you...
-
Upload
ginger-quinn -
Category
Documents
-
view
225 -
download
0
Transcript of SQL/Lesson 4/Slide 1 of 45 Using Subqueries and Managing Databases Objectives In this lesson, you...
SQL/Lesson 4/Slide 1 of 45
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
View, rename, and delete databases
SQL/Lesson 4/Slide 2 of 45
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
SQL/Lesson 4/Slide 3 of 45
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.
SQL/Lesson 4/Slide 4 of 45
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
SQL/Lesson 4/Slide 5 of 45
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
SQL/Lesson 4/Slide 6 of 45
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')
SQL/Lesson 4/Slide 7 of 45
Using Subqueries and Managing Databases
Execute the query
Action:
In the Query Analyzer window, type the query
Execute the query
SQL/Lesson 4/Slide 8 of 45
Using Subqueries and Managing Databases
Verify that the query output is as per the required results
Action:
Check whether:
The required rows are displayed
SQL/Lesson 4/Slide 9 of 45
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)
SQL/Lesson 4/Slide 10 of 45
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')
SQL/Lesson 4/Slide 11 of 45
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')
SQL/Lesson 4/Slide 12 of 45
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
SQL/Lesson 4/Slide 13 of 45
Using Subqueries and Managing Databases
More on Subqueries (Contd.)
The ORDER 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
SQL/Lesson 4/Slide 14 of 45
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'))
SQL/Lesson 4/Slide 15 of 45
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)
SQL/Lesson 4/Slide 16 of 45
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
SQL/Lesson 4/Slide 17 of 45
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.
SQL/Lesson 4/Slide 18 of 45
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
SQL/Lesson 4/Slide 19 of 45
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
SQL/Lesson 4/Slide 20 of 45
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_listINTO new_table_nameFROM table_name1, table_name2,………, table_name nWHERE condition1, condition2,………., condition n
SQL/Lesson 4/Slide 21 of 45
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:
SQL/Lesson 4/Slide 22 of 45
Using Subqueries and Managing Databases
Draft the query (Contd.)
SELECT * INTO tempExternalCandidate
FROM ExternalCandidate
WHERE DATEPART(mm,dDateOfApplication)= 5
AND DATEPART(yyyy,dDateOfApplication)= 2001
SQL/Lesson 4/Slide 23 of 45
Using Subqueries and Managing Databases
Execute the query
Action
In the Query Analyzer window, type the query
Execute the query
SQL/Lesson 4/Slide 24 of 45
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.
SQL/Lesson 4/Slide 25 of 45
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.
SQL/Lesson 4/Slide 26 of 45
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
SQL/Lesson 4/Slide 27 of 45
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
SQL/Lesson 4/Slide 28 of 45
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]
SQL/Lesson 4/Slide 29 of 45
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 ContractRecruiterUNION SELECT cName, cPhone
FROM RecruitmentAgencies
SQL/Lesson 4/Slide 30 of 45
Using Subqueries and Managing Databases
Execute the query
Action
In the Query Analyzer window, type the query
Execute the query
SQL/Lesson 4/Slide 31 of 45
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
SQL/Lesson 4/Slide 32 of 45
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
SQL/Lesson 4/Slide 33 of 45
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?
SQL/Lesson 4/Slide 34 of 45
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
SQL/Lesson 4/Slide 35 of 45
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
SQL/Lesson 4/Slide 36 of 45
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 Syntaxsp_renamedb 'old_name', 'new_name'
SQL/Lesson 4/Slide 37 of 45
Using Subqueries and Managing Databases
Deleting a Database
The DROP DATABASE statement is used to delete a database
SyntaxDROP DATABASE database_name
Just a Minute…
List the three types of operating system files that store the data and objects of SQL Server database.
SQL/Lesson 4/Slide 38 of 45
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
SQL/Lesson 4/Slide 39 of 45
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
SQL/Lesson 4/Slide 40 of 45
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
SQL/Lesson 4/Slide 41 of 45
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)
SQL/Lesson 4/Slide 42 of 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