Professional Documents
Culture Documents
Reference: SUB-QUERIES
Connolly & Begg, Database Systems, CORRELATED QUERIES
Fifth Edition pp 154-161. JOINS
Fourth Edition pp 137-153. FROM CLAUSES
ETC.
SUB-QUERIES
PART
Part Description Price
No
223A 22mm clip 0.10
1212 22mm con 1.50
6341SS 3m tube 4.50
APPROACH TO RESOLVING A SUB-QUERY: List the descriptions of parts where the price is above the
1. CALCULATE THE AVERAGE OF THE VALUE ATTRIBUTE average price of a part.
(749.2)
2. RETRIEVE EACH OF THE ROWS FROM THE TABLE SELECT DESCRIPTION
WHERE THE VALUE ATTRIBUTE IS GREATER THAN 749.2 l9q2 FROM PART
3. PROJECT THE ORDER_NUM AND ORDER_DATE WHERE PRICE > ( SELECT AVG(PRICE)
ATTRIBUTES. FROM PART )
CORRELATED QUERIES
Approach to resolving a correlated-query: Average = 838.7 Approach to resolving a correlated-query: Average = 838.7
1. Retrieve the first row 1. Retrieve the first row
2. Get the cust_num 2. Get the cust_num
3. Calculate the average of the value attribute for all the rows with 3. Calculate the average of the value attribute for all the rows with
this cust_num this cust_num
4. If the value attribute of the current row is greater than the average 4. If the value attribute of the current row is greater than the average
value value
calculated return the row calculated return the row
5. Repeat for all rows in the table 5. Repeat for all rows in the table
Approach to resolving a correlated-query: Average = 656.7 Approach to resolving a correlated-query: Average = 838.7
1. Retrieve the first row 1. Retrieve the first row
2. Get the cust_num 2. Get the cust_num
3. Calculate the average of the value attribute for all the rows with 3. Calculate the average of the value attribute for all the rows with
this cust_num this cust_num
4. If the value attribute of the current row is greater than the average 4. If the value attribute of the current row is greater than the average
value value
calculated return the row calculated return the row
5. Repeat for all rows in the table 5. Repeat for all rows in the table
Emp Manager
SELF JOINS (3) SELF JOINS (3)
What parts do you need to make an engine?. What parts do you need to make an engine?.
PARTLIST
SuperPart SubPart
Product_name Part Product_name Part
Product_name Part
engine cylinder head engine cylinder head engine cylinder head
engine block
engine block engine block
cylinder head valve set
cylinder head valve set
cylinder head valve set cylinder head head casting cylinder head head casting
cylinder head head casting block block casting block block casting
block piston block piston
block block casting
block piston
engine
Select SuperPart.Product_name, SubPart.Part
cylinder head block l9q9 From Partlist SuperPart, Partlist SubPart
Where SuperPart.Part = SubPart.Product_name
valve set head casting block casting piston
Conclusion
In a sub-query, the nested query is evaluated once fpr the whole query.