Professional Documents
Culture Documents
Slides RDBMS 5
Slides RDBMS 5
RDBMS – Part 5
s y s
f o
In
ER/CORP/CRS/DB92 Ver. No.: 1.0 Confidential Copyright © 2008, Infosys Technologies Ltd.
General Guideline
s
intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express
y
prior written permission of Infosys, this document and the information contained
s
herein may not be published, disclosed, or used for any other purpose.
f o
In
Copyright © 2008, Infosys Technologies Ltd. 2 Confidential
2
Confidential Information
s
Corporate and Infrastructure information about Infosys
Infosys’ project management and quality processes
y
Project experiences provided included as illustrative case studies
Any disclosure of Confidential Information to, or use of it by a third party, will
s
be damaging to Infosys.
Ownership of all Infosys Confidential Information, no matter in what media it
o
resides, remains with Infosys.
f
Confidential information in this document shall not be disclosed, duplicated or
used – in whole or in part – for any purpose other than reading without specific
In
written permission of an authorized representative of Infosys.
This document also contains third party confidential and proprietary
information. Such third party information has been included by Infosys after
receiving due written permissions and authorizations from the party/ies. Such
third party confidential and proprietary information shall not be disclosed,
duplicated or used – in whole or in part – for any purpose other than reading
without specific written permission of an authorized representative of Infosys.
3
Recap
Aggregate Function
Group By
Relational Algebra
s
Cartesian Product
y
Inner Join
s
Self Join
Outer Join
f o
In
Copyright © 2008, Infosys Technologies Ltd. 4 Confidential
4
Session Plan
Sub Query
Independent Sub Query
Correlated Query
s
Exists and Not Exists
o s y
In f
Copyright © 2008, Infosys Technologies Ltd. 5 Confidential
5
Education and Research
We enable you to leverage knowledge anytime, anywhere!
SUB-QUERIES
s y s
f o
In
Copyright © 2008, Infosys Technologies Ltd. 6 Confidential
Sub-queries
s y s
o
The sub query is enclosed in parentheses
f
.
In
Copyright © 2008, Infosys Technologies Ltd. 7 Confidential
7
Independent SUB QUERIES
Inner query is independent of outer query.
s y s
List the name of Item whose unit price is greater than the unit price of
o
item id BAK101
SELECT ItemName
In f
WHERE UnitPrice
>
FROM Item
If the Inner Query does
not have any reference
of outer Query tables
then it is independent
Sub query
Sub-queries:
A sub-query is a query within a query. A sub-query answers the queries that have multiple parts; the
sub-query answers one part of the question, and the parent query answers the other part. When
you nest many sub-queries, the innermost query is evaluated first.
SubQueries can be used in SELECT , FROM, WHERE and HAVING clauses.
For e.g :
Select all sales reps who have a higher quota than sales rep 101.
We need to analyze this query and understand how to break it into sub problems
1. First we need to find out what is the quota of sales rep 101
2. Based on this info, we need to select sales reps who have a higher quota than this value
3. So, the inner query will find the quota of sales rep 101 and the outer query will extract sales reps
exceeding this quota value. The solution would look like:
SELECT Rep
FROM SalesReps
WHERE Quota >
SELECT Quota
FROM SalesReps
WHERE Empl_Num = 101;
8
Retrieval using SUB QUERIES
Item
ItemId ItemName
s
UnitPrice
s y
Class
f o
SELECT ItemId, ItemName, UnitPrice
n
FROM Item
I (SELECT
SELECT MAX(UnitPrice)
MAX
FROM Item);
=
Get the Maximum Unit
Price available in the
item table
9 Confidential
9
Retrieval using SUB QUERIES
List the second highest Unit price from the item table.
Item
ItemId ItemName
s
UnitPrice
s y
Class
f o SELECT MAX
MAX(UnitPrice)
Discard the
In
FROM Item highest Unit Price
WHERE UnitPrice
Get the highest Unit
!= Price
(SELECT
SELECT MAX(UnitPrice)
MAX FROM Item);
;
10
Retrieval using SUB QUERIES
List the details of the item whose unit price is more than the average Unit
price of items.
s
Item
y
ItemId ItemName UnitPrice Class
f o
SELECT ItemId,ItemName,UnitPrice s
In
FROM Item
WHERE UnitPrice
Get the average Unit
> Price
11
Retrieval using SUB QUERIES
List the id of the customer and sum of total purchase amount for those
customers whose sum of total purchase amount is more than the average
of the sum of total purchase amount of other Customers.
CustomerPurchase
s y sBillId NetPrice
o
SELECT CustomerId,Sum(NetPrice)
(SELECT AVG(SUM
f
FROM CustomerPurchase
In
GROUP BY CustomerId
HAVING SUM
SUM(NetPrice)
AVG SUM(NetPrice))
SUM
>
FROM CustomerPurchase
Get the average of Sum
of Net price of all the
purchases
GROUP BY CustomerId);
);
Copyright © 2008, Infosys Technologies Ltd. 12 Confidential
12
Dry running the inner query of previous example
CustomerPurchase
CustomerId ItemId QtyPurchased BillId NetPrice
C1 STN001 5 1001 150
C2 GRO001 1 1002 10
s
C1 ELC001 1 1001 5000
C2 STN002 2 1002 400
y
C3 STN002 2 1003 400
f o
net Price for each group
s
After grouping by Customer Id and finding sum of
In
CustomerId Sum(NetPrice)
C1 5150 Avg(sum(NetPrice))
C2 410 1986.666667
C3 400 After finding
average of sum
of net price for
each group
13
Retrieval using SUB QUERIES
List the details of the customer(s) who has paid a bill of maximum amount.
Customer CustomerId CustomerName DateOfReg UserId Password
s
BillId NetPrice
y
SELECT CustomerId, CustomerName Get the customer
s
id(s) who have paid
FROM Customer the maximum bill.
Assuming one bill
o
WHERE CustomerId will be paid by only
f
one Customer
IN
In
(SELECT CustomerId FROM CustomerPurchase
GROUP BY BillId, CustomerId HAVING SUM(NetPrice)
SUM
=
(SELECT
SELECT MAX(SUM
MAX SUM(NetPrice))
SUM FROM CustomerPurchase GROUP
BY BillId));
Get the maximum of
Copyright © 2008, Infosys Technologies Ltd. 14 Confidential Sum of Net price of all
the bill ids
You can reduce the three level sub query by joining Customer and CustomerPurchase of first and
second query.
(left as an exercise)
14
Dry running the innermost query of previous example
CustomerPurchase
CustomerId ItemId QtyPurchased BillId NetPrice
C1 STN001 5 1001 150
C2 GRO001 1 1002 10
s
C1 ELC001 1 1001 5000
C2 STN002 2 1002 400
y
C3 STN002 2 1003 400
o
sum of net Price for each group
f s
In
BillId Sum(NetPrice)
1001 5150 Max(sum(NetPrice))
1002 410 5150
1003 400 After finding
maximum of
sum of net
price for each
group
15
Correlated SUB QUERIES
You can refer to the table in the FROM clause of the outer query
in the inner query using Correlated sub-queries.
s
The inner query is executed separately for each row of the outer
y
query.
s
(i.e. In Co-Related Sub-queries, SQL performs a sub-query over
and over again – once for each row of the main query. )
f o
In
Copyright © 2008, Infosys Technologies Ltd. 16 Confidential
16
Correlated SUB QUERIES
List the details of the item which is having maximum unit price in each
class .
SELECT Io.ItemId,Io.ItemName,Io.UnitPrice
FROM Item Io
s y s
Note the
Since it is correlated
query for each item in
o
reference of outer the item table the inner
WHERE UnitPrice table in inner query will execute once
f
query and find the maximum
= unit price for that class.
In
(SELECT
SELECT Max(UnitPrice) FROM Item Ii
WHERE Ii.Class = Io.Class
);
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-query cannot
be used in the parent queries. The scope is only the current query level and its sub-queries.
17
Dry running the previous query
Io
ItemId ItemName UnitPrice Class Inner query is
STN001 Pen 30 A executing for
the first row of
BAK003 Bread 20 A outer Query
s
ELC001 Mobile 5000 C
Ii
ItemId ItemName
o
UnitPrice
s y Class
f
STN001 Pen 30 A
BAK003 Bread 20 A
ELC001
I
Max(UnitPrice)
30
n Mobile 5000
Maximum of
Class A only
C
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-query cannot
be used in the parent queries. The scope is only the current query level and its sub-queries.
18
Dry running the previous query
Io
ItemId ItemName UnitPrice Class Inner query is
executing for
STN001 Pen 30 A the second
BAK003 Bread 20 A row of outer
Query
s
ELC001 Mobile 5000 C
Ii
ItemId ItemName
o
UnitPrice
s y Class
f
STN001 Pen 30 A
BAK003 Bread 20 A
ELC001
I
Max(UnitPrice)
30
n Mobile 5000
Maximum of
Class A only
C
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-query cannot
be used in the parent queries. The scope is only the current query level and its sub-queries.
19
Dry running the previous query
Io
ItemId ItemName UnitPrice Class Inner query is
STN001 Pen 30 A executing for
the third row
BAK003 Bread 20 A of outer Query
s
ELC001 Mobile 5000 C
Ii
ItemId ItemName
o
UnitPrice
s y Class
f
STN001 Pen 30 A
BAK003 Bread 20 A
ELC001
I
Max(UnitPrice)
5000
n Mobile 5000
Maximum of
Class C only
C
Note:
The column names in the parent queries are available for reference in sub-queries. The column names from the tables in the sub-query cannot
be used in the parent queries. The scope is only the current query level and its sub-queries.
20
Correlated SUB QUERIES
List the customer details of the customers, whose total NetPrice is more
than 1000.
Customer
CustomerId CustomerName DateOfReg UserId Password
s y s BillId NetPrice
o
SELECT CustomerId,CustomerName FROM Customer C
f
Note the
WHERE reference of outer
Since it is correlated
In
table in inner
query for each
1000<(SELECT
(SELECT Sum(netprice) FROM query
customer in the
customer table the
customerpurchase CP inner query will
execute once and sum
WHERE CP.Custid = C.CustId)
) of all net amount for
that customer.
21
Dry run the previous query
Customer
CustomerId CustomerName DateOfReg UserId Password
C1 John 1-Mar-09 John1001 John@123
C2 Jack 10-Mar-09 Jack1002 Jack@123
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
C5
CustomerPurchase
o
Simon
s y Symon1005 Symon@123
CustomerId
C1
C2
C1
C2
C3
In f ItemId QtyPurchased
STN001
GRO001
ELC001
STN002
STN002
5
1
1
2
2
BillNo
1001
1002
1001
1002
1003
NetPrice
150
10
5000
400
400
22
Education and Research
We enable you to leverage knowledge anytime, anywhere!
EXISTS VS NOT-EXISTS
s y s
f o
In
Copyright © 2008, Infosys Technologies Ltd. 23 Confidential
EXISTS
y s
If the query following the EXISTS returns at least one row, the
EXISTS returns TRUE
s
f o
If the query following the EXISTS returns no rows, the EXISTS
In
returns FALSE
EXISTS:
The EXISTS operator is always followed by a sub-query in parentheses. EXISTS evaluates to TRUE
if the sub-query returns at least one row.
24
Retrieval using EXISTS
List the details of Customers who have purchased an item.
Customer
CustomerId CustomerName DateOfReg UserId Password
s
CustomerPurchase CustomerId ItemId QtyPurchased BillId NetPrice
o s y
f
For each customer in
the customer table the
WHERE inner query executes to
In
check whether such
customer record is
EXISTS present in the
CustomerPurchase table
(SELECT
SELECT *
FROM CustomerPurchase CP
WHERE C.CustomerId=CP.CustomerId);
Copyright © 2008, Infosys Technologies Ltd. 25 Confidential
25
Dry running the previous query
Customer
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
y
For first row
C5 Simon Symon1005 Symon@123 of outer
s
Query inner
CustomerPurchase query is
executing
Custome
rId ItemId
In
C1 STN001 5 1001 150
C2 GRO001 1 1002 10
C1 ELC001 1 1001 5000 For first row of
outer Query
C2 STN002 2 1002 400 Inner query
satisfies two
C3 STN002 2 1003 400 rows hence
EXISTS will
return TRUE
26
Dry running the previous query
Customer
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
y
For second
C5 Simon Symon1005 Symon@123 row of outer
s
Query inner
CustomerPurchase query is
executing
Custome
rId ItemId
In
C1 STN001 5 1001 150
C2 GRO001 1 1002 10
C1 ELC001 1 1001 5000 For second row
C2 STN002 2 1002 400 of outer Query
Inner query
C3 STN002 2 1003 400 satisfies two
rows hence
EXISTS will
return TRUE
27
Dry running the previous query
Customer
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
y
For third row
C5 Simon Symon1005 Symon@123 of outer
s
Query inner
CustomerPurchase query is
executing
Custome
rId ItemId
In
C1 STN001 5 1001 150
C2 GRO001 1 1002 10
C1 ELC001 1 1001 5000
C2 STN002 2 1002 400 For third row of
outer Query
C3 STN002 2 1003 400 Inner query
satisfies one
row hence
EXISTS will
return TRUE
Copyright © 2008, Infosys Technologies Ltd. 28 Confidential
28
Dry running the previous query
Customer
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
y
For Forth row
C5 Simon Symon1005 Symon@123 of outer
s
Query inner
CustomerPurchase query is
o
executing
Custome
rId
C1
C2
C1
C2
C3
ItemId
STN001
In
GRO001
ELC001
STN002
STN002
f QtyPurchased
5
1
1
2
2
BillNo
1001
1002
1001
1002
1003
NetPrice
150
10
5000
400
400
For forth row of
outer Query
Inner query
satisfies no row
hence EXISTS
will return
FALSE
29
Dry running the previous query
Customer
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
y
C5 Simon Symon1005 Symon@123 Foroffifth
outer
row
s
Query inner
CustomerPurchase query is
executing
Custome
rId ItemId
In
C1 STN001 5 1001 150
C2 GRO001 1 1002 10
C1 ELC001 1 1001 5000 For fifth row of
C2 STN002 2 1002 400 outer Query
Inner query
C3 STN002 2 1003 400 satisfies no row
hence EXISTS
will return
FALSE
30
Retrieval using EXISTS
List the details of Item which has been ordered to the supplier.
s
ItemOrder ItemId SupplierId QtyOrdered OrderDate DeliveryStatus DeliveryDate
f
query executes to check
whether such item
WHERE
In
record is present in the
ItemOrder table
EXISTS
(SELECT
SELECT *
FROM ItemOrder IO
WHERE I.ItemId=IO.ItemId);
Copyright © 2008, Infosys Technologies Ltd. 31 Confidential
31
Dry run the previous query
Item
ItemId ItemName UnitPrice Class
STN001 Pen 30 A
s
BAK003 Bread 20 A
ELC001 Mobile 5000 C
ItemOrder
o s y
f
ItemId SupplierId QtyOrdered OrderDate DeliveryStatus DeliveryDate
In
STN001 SUP001 50 1-Mar-09 Delivered 5-Mar-09
EL001 SUP004 10 10-Mar-09 Delivered 12-Mar-09
STN001 SUP002 40 15-Mar-09 Not Delivered
EL001 SUP005 15 20-Mar-09 Not Delivered
32
Retrieval using EXISTS
List the supplier details who have supplied items more than one.
Supplier SupplierId SupplierName SupplierContactNo
SELECT S.SupplierId,S.SupplierName
FROM Supplier S
o
has supplied more than
WHERE EXISTS one items.
(SELECT
SELECT *
In f
FROM ItemOrder IO
WHERE S.SupplierId=IO.SupplierId
GROUP BY SupplierId
HAVING COUNT
COUNT(*)>1 );
Copyright © 2008, Infosys Technologies Ltd. 33 Confidential
33
Dry run the previous query
Supplier
s
SUP003 Hari 9102020202
y
SUP004 Tom 9289208283
SUP005 Marie 9819393938
ItemOrder
f o
ItemId SupplierId QtyOrdered
s
OrderDate DeliveryStatus DeliveryDate
n
STN001 SUP001 50 1-Mar-09 Delivered 5-Mar-09
BAK003
EL001
STN001
ELC001
ISUP003
SUP004
SUP001
SUP005
20
10
40
15
34 Confidential
34
Retrieval using EXISTS
List the customer details whose total purchase amount is highest compared
to total purchase amount of other customers.
s
WHERE EXISTS
y
(SELECT *
s
FROM CustomerPurchase CP
WHERE C.CustomerId=CP.customerId
f o GROUP BY CP.
.CustomerId
In
HAVING SUM
SUM(NetPrice)
=
(SELECT MAX SUM(NetPrice))
SUM
MAX(SUM
FROM CustomerPurchase
GROUP BY CustomerId));
Copyright © 2008, Infosys Technologies Ltd. 35 Confidential
35
Dry run the previous query
Customer
CustomerId CustomerNAme DateOfReg UserId Password
C1 John 1-Mar-09 John1001 John@123
C2 Jack 10-Mar-09 Jack1002 Jack@123
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
C5
CustomerPurchase
o
Simon
s y Symon1005 Symon@123
CustomerId
C1
C2
C1
C2
C3
In f ItemId QtyPurchased
STN001
GRO001
ELC001
STN002
STN002
5
1
1
2
2
BillNo
1001
1002
1001
1002
1003
NetPrice
150
10
5000
400
400
36
Dry Run the previous Query
Customer
CustomerId CustomerNAme DateOfReg UserId Password
C1 John 1-Mar-09 John1001 John@123
C2 Jack 10-Mar-09 Jack1002 Jack@123
s
C3 Bob 12-Mar-09 Bob1003 Bob@123
C4 Allan 13-Mar-09 Allan1004 Allan@123
C5
CustomerPurchase
o
Simon
s y Symon1005 Symon@123
CustomerId
C1
C2
C1
C2
C3
In f ItemId QtyPurchased
STN001
GRO001
ELC001
STN002
STN002
5
1
1
2
2
BillNo
1001
1002
1001
1002
1003
NetPrice
150
10
5000
400
400
37
NOT EXISTS
The NOT EXISTS Keyword is used check whether a sub query produces
any row(s) of results
If the query following the NOT EXISTS returns no rows, the NOT
EXISTS returns TRUE
s y s
f o
If the query following the NOT EXISTS returns any row(s), the NOT
EXISTS returns FALSE
In
Copyright © 2008, Infosys Technologies Ltd. 38 Confidential
A not exists checks for the opposite condition than an Exists. It checks for the non-existence of a condition.
38
Retrieval using NOT EXISTS
o
present in the
f
NOT EXISTS CustomerPurchase table
In
(SELECT
SELECT *
FROM CustomerPurchase CP
WHERE C.CustomerId=CP.CustomerId);
39
Retrieval using NOT EXISTS
List the details of the items which has not been ordered to the supplier.
SELECT I.ItemId,I.ItemName
FROM Item I
WHERE
s y s
NOT EXISTS
f o
In
(SELECT
SELECT *
FROM ItemOrder IO
WHERE I.ItemId=IO.ItemId);
40
Summary
In independent sub query the inner query executes first and then
outer query executes utilizing the result obtained by inner query.
s
In correlated sub query the inner query executed one for every row of
y
outer query.
f o s
EXISTS returns TRUE if inner query used returns any one record.
NOT EXISTS returns TRUE if inner query does not return anything.
In
Copyright © 2008, Infosys Technologies Ltd. 41 Confidential
41
s y s
f o Thank You
In “The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may
not be disclosed in whole or in part at any time, to any third party without the prior written consent of
Infosys Technologies Ltd.”
“© 2008 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this
document belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted,
abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the
prior written consent of Infosys Technologies Ltd.”
42