Lecture 3 - Nested Queries Flashcards
What is a nested/inner query?
Nested query is a query within another (outer) query.
- SELECT-FROM-WHERE block within another outer WHERE clause.
- Nested query’s output is input to outer’s WHERE via: IN, ALL, EXISTS
What are the two types of nested queries?
- nested uncorrelated query
- nested correlated query
What is IN?
check if something is within a set
What is ALL?
compares a value with all the values from the inner’s output set
using >, >=, <, <=, =, <>
What is EXISTS?
Checks if resultant set of nested query is not empty.
What is a nested uncorrelated query?
first execute the nested query, and then
execute the outer query using inner’s output.
What is a nested correlated query?
for each tuple of the outer query, we execute the
nested query
Within nested correlated queries we have ?
global and local scopes
Problem with exists?
just focus on the count of the nested query or set, but doesn’t care about the content (can be all null)
Example of a nested correlated query?
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE E.SSN IN ( SELECT D.ESSN
FROM DEPENDENT AS D
WHERE E.FNAME = D.DEPENENT_NAME)
we are passing the employee to the inner query
Example of a nested uncorrelated query?
SELECT FNAME
FROM EMPLOYEE
WHERE DNO IN ( SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME = ‘Research’);
STUDENT (Name, StudentID, Class)
COURSE (Name, CourseID, Credits, School)
GRADES (StudentID, CourseID, Grade)
/Grade: {‘A’, ‘B’, ‘C’, ‘D’, ‘E’}/
Task: Retrieve the names of all students who have a Grade of ‘A’ in
all of their courses ( ‘distinction’ students)
SELECT S.Name
FROM STUDENT S
WHERE NOT EXISTS
(SELECT * FROM GRADES G
WHERE G.StudentID = S.StudentID
AND G.Grade <> ‘A’
)