SQL Nested Queries
SQL Nested Queries
• The ‘=’ operator may be used only if it is known in advance that the
inner SELECT statement always returns a single value
• An equivalent formulation may be defined using a join operation
Equivalent formulation
• The equivalent formulation with join is characterized by
• a FROM clause including all the tables referenced by the FROM clauses of
each SELECT statement
• appropriate join conditions in the WHERE clause
• if needed selection predicates added in the WHERE clause
FROM clause (no.1)
• Find the codes of the suppliers that are based in the same city as S1
SELECT SId
SX
FROM S
WHERE City = (SELECT City SY
FROM S
WHERE SId=‘S1’);
FROM clause (no.1)
• Find the codes of the suppliers that are based in the same city as S1
SELECT ...
FROM S AS SX, S AS SY
...
Join condition (no.1)
• Find the codes of the suppliers that are based in the same city as S1
SELECT SId
FROM S
WHERE City = (SELECT City
FROM S
WHERE SId=‘S1’);
Join condition (no.1)
• Find the codes of the suppliers that are based in the same city as S1
SELECT ...
FROM S AS SX, S AS SY
WHERE [Link]=[Link]
...
Selection predicate (no.1)
• Find the codes of the suppliers that are based in the same city as S1
SELECT SId
FROM S
WHERE City = (SELECT City
FROM S
WHERE SId=‘S1’);
SELECT clause (no.1)
• Find the codes of the suppliers that are based in the same city as S1
SELECT [Link]
FROM S AS SX, S AS SY
WHERE [Link]=[Link] AND
[Link]=‘S1’;
Equivalent formulation (no.2)
• Find the codes of the suppliers whose number of employees is
smaller than the maximum number of employees
SELECT SId
FROM S
WHERE #Employees < (SELECT MAX(#Employees)
FROM S);
AttributeName IN (NestedQuery)
16
The IN operator (no.1)
• Find the names of the suppliers who supply product P2
SP
SId PId Qty
S1 P1 300
(SELECT SId Codes
S1 P2 200
of the
S1 P3 400 SId FROM SP
S1 P4 200 S1 suppliers
WHERE PId=‘P2’)
S1 P5 100 S2 of P2
S1 P6 100 S3
S2 P1 300
S2 P2 400
S3 P2 200
S4 P3 200
S4 P4 300
S4 P5 400
The IN operator (no.1)
• Find the names of the suppliers who supply product P2
S
SId SName #Employees City
S1 Smith 20 London Set membership
SELECT SName
S2 Jones 10 Paris FROM S
S3 Blake 30 Paris Codes
WHERE SId IN (SELECT SId
S4 Clark 20 London of the
FROM SP
S5 Adams 30 Athens suppliers
WHERE PId=‘P2’); of P2 SId
S1
S2
S3
19
Example 1: Equivalent Formulation with Join
• Find the names of the suppliers who supply product P2
IN JOIN
SELECT SName SELECT SName
FROM S FROM S, SP
WHERE SId IN (SELECT SId WHERE [Link]=[Link]
FROM SP
AND PId=‘P2’;
WHERE PId=‘P2’);
20
Example 2: IN Operator
• Find the name of suppliers who provide at least one red product
SELECT SName
FROM S
WHERE SId IN (SELECT SId
FROM SP Red Supplier
WHERE PId IN (SELECT PId Product names
Supplier with
FROM P Red Product those
Codes
WHERE Color=‘Red’)); Codes codes
21
Example 2: Equivalent formulation
• Find the name of suppliers who provide at least one red product
IN JOIN
SELECT SName
SELECT SName FROM S,SP 1
1
FROM S WHERE [Link]=[Link]
WHERE SId IN
(SELECT SId
FROM SP
WHERE PId
IN (SELECT PId
FROM P
WHERE Color=‘Red’)); 22
Example 2: Equivalent formulation
• Find the name of suppliers who provide at least one red product
IN JOIN
SELECT SName
SELECT SName FROM S, SP, P 2
WHERE PId
IN (SELECT PId
FROM P
WHERE Color=‘Red’)); 23
Example 2: Equivalent formulation
• Find the name of suppliers who provide at least one red product
IN JOIN
SELECT SName
SELECT SName FROM S, SP, P
FROM S WHERE [Link]=[Link] AND
WHERE SId IN [Link]= [Link] AND 3
FROM SP
WHERE PId
IN (SELECT PId
3
FROM P
WHERE Color=‘Red’)); 24
• It expresses the concept of exclusion from a set of values
NOT IN
OPERATOR • It requires the identification of an appropriate set to be
excluded defined by
• a nested query
• a list of values
• There is no equivalent formulation with join
48
Example 1: Concept of exclusion
• Find the names of the suppliers who do not supply product P2
• it is not possible to express the query with a join operation
SELECT SName
FROM S, SP
WHERE [Link] = [Link]
AND PId <>'P2';
Wrong solution
• The query matches the request:
• Find the name of suppliers who provide at least one product other than P2
49
Wrong solution (no.1)
• Find the names of the suppliers who do not supply product P2
SP
S SId PId Qty
SId SName #Employees City
S1 P1 300
S1 Smith 20 London
S1 P2 200
S2 Jones 10 Paris
S1 P3 400
S3 Blake 30 Paris
S1 P4 200
S4 Clark 20 London
S1 P5 100
S5 Adams 30 Athens
S2 P1 300
S2 P2 400
R
S3 P2 200
SName S4 P3 200
Smith S4 P4 300
Jones S4 P5 400
Clark
The NOT IN operator (no.1)
• Find the names of the suppliers who do not supply product P2
• Set to be excluded
• suppliers of product P2
SELECT SName
FROM S
WHERE SId NOT IN (SELECT SId
FROM SP Codes of the suppliers
who supply P2
WHERE PId=‘P2’);
does not belong to
NOT IN and relational algebra (no.1)
• Find the names of the suppliers who do not supply product P2
pSName
pSName
- S p
pSId pSId
S sPId=‘P2’
sPId=‘P2’
S
SP
SP p: [Link]=[Link]
The NOT IN operator (no.2)
• Find the names of the suppliers who only supply product P2
• Set to be excluded
• suppliers of products other than P2
The NOT IN operator (no.2)
• Find the names of the suppliers who only supply product P2
SELECT SName
FROM S, SP
WHERE [Link] NOT IN (SELECT SId Codes of the suppliers
FROM SP who supply
at least one product
WHERE PId<>‘P2’) other than P2
AND [Link]=[Link];
Alternative solution (no.2)
• Find the names of the suppliers who only supply product P2
SELECT SName
FROM S
WHERE [Link] NOT IN (SELECT SId Codes of the suppliers
FROM SP who supply
at least one product
WHERE PId<>‘P2’) other than P2
AND [Link] IN (SELECT SId
FROM SP);
The NOT IN operator (no.3)
• Find the names of the suppliers who do not supply any red products
• Set to be excluded:
• suppliers of red products, identified by their codes
SELECT SName
FROM S
WHERE SId NOT IN
(SELECT SId
FROM SP
Codes of the
suppliers of at least one
WHERE PId IN (SELECT PId
red product FROM P
WHERE Color=‘Red’));
Wrong alternative (no.3)
• Find the names of the suppliers who do not supply any red products
SELECT SName
FROM S
WHERE SId IN
(SELECT SId
Codes of the
FROM SP
suppliers of WHERE PId NOT IN (SELECT PId
non-red FROM P
products
WHERE Color=‘Red’));
60
Example (no.1)
• Find the pairs of starting places and destinations for which none of
the trips lasts more than 2 hours
Example (no.1)
• Find the pairs of starting places and destinations for which none of
the trips lasts more than 2 hours
SELECT StartingPlace, Destination
FROM TRIP
WHERE (StartingPlace, Destination) NOT IN
(SELECT StartingPlace, Destination
Tuple FROM TRIP
constructor WHERE ArrivalTime-DepartureTime>2);
• The EXISTS operator admits a nested query as a
parameter and returns
• true if the nested query returns a non-empty set (that is, it
returns at least one tuple)
• false if the internal query returns the empty set (i.e., no
EXISTS tuple)
63
The EXISTS operator (no.1)
• Find the names of the suppliers of product P2
SELECT SName
FROM S
WHERE EXISTS (SELECT *
FROM SP
WHERE PId=‘P2’
AND [Link]=[Link] );
Correlation condition
R
SName
Smith
Jones
Blake
Scope of attributes
• A nested query may reference attributes defined within outer queries
• A query may not reference attributes defined
• within a nested query at an inner level
• within a different query at the same level
• The EXISTS operator admits a nested query as a
parameter and returns
• true if the nested query returns an empty set (i.e., no
tuple)
• false if the nested query returns a non-empty set (that is,
NOT EXISTS it returns at least one tuple)
71
The NOT EXISTS operator (no.1)
• Find the names of the suppliers that do not supply product P2
R
SName
Clark
Adams
• It may be required to bind the computation of a
nested query to the value(s) of one or more
attributes in an outer query
• the binding is expressed by one or more correlation
conditions
CORRELATION • A correlation condition
• must be specified in the WHERE clause of the nested
BETWEEN query that requires it
QUERIES • is a predicate that binds some attributes of tables
appearing in the nested query’s FROM clause to attributes
of tables appearing in the FROM clause of outer queries
• Correlation conditions may not be expressed
• within queries at the same nesting level
• with references to attributes of a table appearing in the
FROM clause of a nested query
79
Correlation among queries (no.1)
• For each product, find the code of the supplier who supplies the
highest quantity
• Find the codes of the trips whose duration is lower than the average
duration of the trips on the same route (i.e., same starting place and
destination)
SELECT TId
FROM TRIP AS TA
WHERE ArrivalTime-DepartureTime < (... Average
duration
of trips
on the current
) route
Correlation among queries (no.2)
TRIP (TId, StartingPlace, Destination,
DepartureTime, ArrivalTime)
• Find the codes of the trips whose duration is lower than the average
duration of the trips on the same route (i.e., same starting place and
destination)
SELECT TId
FROM TRIP AS TA
WHERE ArrivalTime-DepartureTime <
(SELECT AVG(ArrivalTime-DepartureTime) Average
FROM TRIP AS TB duration
... ) of trips
Correlation among queries (no.2)
TRIP (TId, StartingPlace, Destination,
DepartureTime, ArrivalTime)
• Find the codes of the trips whose duration is lower than the average
duration of the trips on the same route (i.e., same starting place and
destination)
SELECT TId
FROM TRIP AS TA
WHERE ArrivalTime-DepartureTime <
(SELECT AVG(ArrivalTime-DepartureTime)
FROM TRIP AS TB Correlation conditions
WHERE [Link]=[Link]
AND [Link]=[Link]);
DIVISION • In SQL, the division operation can be performed
using the COUNT operator, to verify that all the
OPERATOR elements of interest belong to the reference set
88
The division operation (no.1)
• Find the codes of the suppliers who supply all products
• In relational algebra we must use the division operator
pSId,PId pPId
SP P
Division in SQL (no.1)
• Find the codes of the suppliers who supply all products
• Remark
• all products that may be supplied are listed in table P
SELECT SId
For each supplier, FROM SP
total number of GROUP BY SId
products supplied Total
HAVING COUNT(*) = (SELECT COUNT(*)
number
FROM P) of products
Division in SQL (no.1)
• Find the codes of the suppliers who supply all products
SELECT SId
For each supplier, FROM SP
total number of GROUP BY SId
products supplied Total
HAVING COUNT(*) = (SELECT COUNT(*) number
FROM P) of products
Division in SQL (no.1) – Different SP TABLE
• Find the codes of the suppliers who supply all products
SELECT SId
For each supplier, FROM SP
total number of GROUP BY SId
products supplied Total
HAVING COUNT(DISTINCT PID)= (SELECT COUNT(*) number
FROM P); of products
Division in SQL: procedure (no.2)
• Find the codes of the suppliers who supply at least all of the products
supplied by supplier S2
• We must count
• the number of products supplied by S2
• the number of products supplied both by an arbitrary supplier and by S2
• The two counts must be equal
Division in SQL (no.2)
• Find the codes of the suppliers who supply at least all of the products
supplied by supplier S2
SELECT SId
FROM SP
For each supplier, WHERE PId IN (SELECT PId
the total number of Products
products supplied, FROM SP supplied by S2
including only the WHERE SId=‘S2’)
products supplied by GROUP BY SId
S2
HAVING COUNT(*)=(SELECT COUNT(*)
Number
FROM SP of products
WHERE SId=‘S2’); supplied by S2