Sie sind auf Seite 1von 28

Module 9:

Advanced Query
Techniques
Vidya Vrat Agarwal. | MCT, MCSD
Overview

 Introduction to Subqueries
 Subqueries Vs. Joins
 Parallel Subqueries
 Correlated Subqueries
 Using the EXISTS and NOT EXISTS Keywords
Introduction to Subqueries
Subqueries are Nested Select Statements.
Subqueries are “Select….From….Where” expression nested inside another
such expression.
USE pubs
SELECT pub_name Outer Query
FROM publishers
Outer Select
WHERE pub_id IN
(SELECT pub_id
Inner Query
FROM titles
WHERE type = 'business') Inner Select

The Inner query evaluate first and then based on it’s reslut the outer
query will be executed. i.e., “ Bottom-to-Top ”
Introduction to Subqueries

 Why to Use Subqueries

 To break down a complex query into a series of


logical steps
 To answer a query that relies on the results of an
other query
The ability to use “a Query within a Query” or “Nested Query”
is the original reason for the word “Structured” in the name
SQL ( Structured Query Language)
Subqueries Vs. Joins

select distinct pub_name,title


from publishers p JOIN titles t
on p.pub_id = t.pub_id
where t.type = 'business‘
One difference in using a join rather than a subquery is that the
join lets you show columns from more than one table in the
result.

Why to Use Joins Rather Than Subqueries

SQL Server executes joins faster than subqueries


Using Subqueries

 Enclose Subqueries in Parentheses


 Use Only One Expression or Column Name in the
select list, can’t use select * in Subquery.
 Use Subqueries in Place of an Expression
 Relational Database Engine processes the nested SQL
statement first and then result will be returned to the
outer query.
 Cannot Use Subqueries on Columns Containing Text
and Image Data Types
 No Limit to the Levels of Subqueries
Subqueries Returning a Single Value

 Subquery Replaces Expression in:


 select list
 WHERE clause introduced with = comparison operator

USE
USE northwind
northwind
SELECT
SELECT orderid,
orderid, customerid
customerid
FROM
FROM orders
orders
WHERE orderdate =
WHERE orderdate = (SELECT
(SELECT max(orderdate)
max(orderdate)
FROM
FROM orders)
orders)
Subqueries Returning a List of Values
 Subquery Replaces Expression in:
 WHERE clause introduced with the IN keyword

USE
USE northwind
northwind
SELECT
SELECT companyname
companyname
FROM
FROM customers
customers
WHERE
WHERE customerid
customerid IN
IN
(SELECT
(SELECT customerid
customerid
FROM
FROM orders
orders
WHERE
WHERE orderdate
orderdate >'1/1/95')
>'1/1/95')

Server: Msg 512, Level 16, State 1, Line 2


Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as an
expression.
Other Comparison Operator

USE northwind
SELECT orderid, customerid
FROM orders
WHERE orderdate > (SELECT orderdate FROM orders)

Server: Msg 512, Level 16, State 1, Line 2


Subquery returned more than 1 value. This is not permitted
when the subquery follows =, !=, <, <= , >, >= or when the
subquery is used as an expression.
Other Comparison Operator

USE northwind
SELECT orderid, customerid
FROM orders
WHERE orderdate > Any or Some (SELECT orderdate
FROM orders)

 ANY or SOME must be greater than at least one of the


values in the list of values returned by the subquery
Subqueries in UPDATE

Subqueries can be nested in UPDATE statements.


The following query doubles the price of all books published by New Moon
Books. The query updates the titles table; its subquery references the
publishers table.

UPDATE titles SET price = price * 2

WHERE pub_id IN
(SELECT pub_id

FROM publishers

WHERE pub_name = 'New Moon Books')


Subqueries in DELETE

Subqueries can be nested in DELETE statements.


DELETE sales
WHERE title_id IN
(SELECT title_id
FROM titles
WHERE type = 'business')
Paraller Subqueries
A Query having a Compound Where clause.

Select * from Distributer


Where discount >= ( Select Avg(discount)
from distributor)
And Ltime > (select Avg(Ltime)
from Distributor)
And Credit < (select Avg ( Credit)
from distributor
where city-’London’ )
Correlated Subquery
11 Outer query passes
Outer query passes
column
columnvalues
valuestotothe
theinner
innerquery
query
22 Inner query uses
Inner query uses
SELECT orderid, customerid
SELECT orderid, customerid that
thatvalue
valuetotosatisfy
satisfythe
theinner
innerquery
query
FROM
FROM orders
orders or1
or1
WHERE
WHERE 20
20 << (SELECT
(SELECT quantity
quantity
FROM
FROM [order
[order details]
details] od
od
WHERE
WHERE or1.orderid
or1.orderid == od.orderid
od.orderid
AND
AND od.productid
od.productid == 23)
23)
33 Inner query returns
Inner query returns
aavalue
valueback
backtotothe
theouter
outerquery
query
44 The process is repeated for the next
The process is repeated for the next
column
columnvalue
valueofofthe
theouter
outerquery
query

Back
BacktotoStep
Step11
Using the EXISTS and NOT EXISTS Keywords

 Use with Correlated Subqueries


 Determine Whether Data Exists in a List of Values
 SQL Server Process
 Outer query tests for the existence of rows
 Inner query returns TRUE or FALSE
 Data is not produced
USE
USE northwind
northwind
SELECT
SELECT lastname,
lastname, employeeid
employeeid
FROM
FROM employees
employees ee
WHERE
WHERE EXISTS
EXISTS (SELECT
(SELECT ** FROM
FROM orders
orders
WHERE
WHERE e.employeeid == orders.employeeid
e.employeeid orders.employeeid
AND
AND orderdate
orderdate == '9/5/97')
'9/5/97')
Check Your Understanding.
Q.1 What is SubQuery ?
Q.2. Why to use Subqueries ?
Q.3. A Subquery can be a Union ?

1. True
2. False
Q.4. Will this query produce result .?
SELECT *
FROM publishers
WHERE pub_id IN
(SELECT pub_id
FROM titles
WHERE type = 'business')

1. Yes
2. No
Q.5. Is there any limit to nest the queries. ?

1. Yes
2. No
Q.6. What is the Mistake in the following SQL Subquery.?

USE northwind
SELECT orderid, customerid
FROM orders
WHERE orderdate > (SELECT orderdate FROM orders)
Q.7. Does SQL Server executes Joins faster than
Subqueries.?

1. True
2. False
Q.8. Subqueries can not be nested in update
statements..?

1. True
2. False
Q.9. What will be the sequence of Execution of
this query.
USE pubs
SELECT au_lname, au_fname
FROM authors
WHERE au_id IN
( SELECT au_id
FROM titleauthor
WHERE title_id IN
( SELECT title_id
FROM titles
WHERE type = 'popular_comp'))
Q.10. What is the difference between SubQuery and
Correlated Query.?
Overview

 Introduction to Subqueries
 Subqueries Vs. Joins
 Parallel Subqueries
 Correlated Subqueries
 Using the EXISTS and NOT EXISTS Keywords
A burning desire is
The starting point of
All accomplishment.

Thank You.

Das könnte Ihnen auch gefallen