DBS Lecture27
DBS Lecture27
Systems
Lecture # 27
1
Sub Queries
2
Sub Queries
● In SQL a Subquery can be simply defined as
a query within another query.
● In other words we can say that a Subquery is
a query that is embedded in WHERE clause
of another SQL query.
3
●What are the Products whose unit price is
greater than the price of Tofu?
4
Subqueries
● We can write Subqueries in SQL Statements
● The Subquery(inner query) executes once
before the main query
● The result of Subquery is used by the main
query(outer query)
● Subquery can be placed in WHERE clause
5
SubQuery
●SELECT select_list
●FROM table
●WHERE expr operator
● (SELECT select_list
● FROM table);
6
Subquery
7
Using Subquery
1. Enclose subqueries in parentheses
2. Do not add an ORDER BY clause in
subquery
3. Use single row operator with single
row subquery
4. Use Multiple row operators with
multi-row subquery
8
Types of Subqueries
1. Single Row subqueries
9
Types of Subqueries
Single-row Subqueries
Main query
Subquery Returns 15.5
10
Types of Subqueries
Multiple-row Subqueries
Main query 15.5
Subquery Returns
10
15
11
Types of Subqueries
Multiple-Column Subqueries
Main query A 15.5
Subquery Returns
B 10
12
Single-Row Subquery
● Return only one row
● Use single row comparison operator
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
13
Display EmployeeID,FirsrtName of all
employees whose Title is same as that of
Robert
14
SELECT ProductID, ProductName FROM Products
WHERE UnitPrice>= (SELECT UnitPrice FROM Product
WHERE ProductName = ‘Konbu’)
AND UnitPrice <= (SELECT UnitPrice FROM Product WHERE
ProductName = ‘AniseedSyrup’);
16
Show product names and unitsOnOrder whose unitsonOrder
are greater than Chang and less than Aniseed Syrup?
Show product names and unitPrice whose UnitPrice is
greater equal than the price of Konbu and less than equal to
Tofu? 17
Subqueries With Aggregate
Functions
● We can use aggregate function in sub query
● Consider the question:
● Display the name and ids of all products
whose unit price is equal to the minimum
price?
18
19
Show name and id of the product who has maximum Unit Price ?
20
Subqueries With Aggregate Functions
● Recall aggregate functions can be used in two ways
1.Column Level
● SELECT MIN(UnitPrice)
FROM PRODUCTS;
2. Group Level
● SELECT MAX(UnitPrice)
FROM PRODUCTS
GROUP BY CategoryID;
21
Show names of product who has maximum Unit Price in each
category ?
Show product names whose maximum units on order in each
category?
22
ERROR
23
Multi-Row Subqueries
● Return more than one row
● Use multi-row comparison operator
Operator Meaning
IN Equal to a member in list
24
25
Show name of Customers who do not order for desks
26
ANY & ALL Operators
● These Operators are used in combination
with relational operators
● > ANY: Greater than Smallest value in list
● > ALL : Means Greater than Largest Value in
the List
27
28
29
30
31