Nested Queries, Aggregated Functions
Nested Queries, Aggregated Functions
• Comparison operator IN
Make a list of all project numbers for projects that involve an employee whose last name is
‘Smith’, either as a worker or as a manager of the department that controls the project.
Query:
SELECT DISTINCT Pnumber
Selects the project numbers of
FROM PROJECT projects that have an employee
with last name ‘Smith’ involved
WHERE Pnumber IN
as manager
( SELECT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND
Mgr_ssn=Ssn AND Lname=‘Smith’ )
OR
Pnumber IN Selects the project numbers of
projects that have an employee
( SELECT Pno with last name ‘Smith’ involved
FROM WORKS_ON, EMPLOYEE as worker
WHERE Essn=Ssn AND Lname=‘Smith’ );
Example - Nested Queries (Cont.)
Select the Essns of all employees who work on the same project and hours as
some project that employee ‘John Smith’ (whose Ssn = ‘123456789’) works on.
FROM WORKS_ON
FROM WORKS_ON
WHERE Essn=‘123456789’ );
Comparison Operators to Compare a single
value – ANY & ALL
• ALL operator: (v > ALL V) returns TRUE if the value v is greater than
all the values in the set (or multiset) V.
• Other operators that can be combined with ANY (or SOME) and
ALL: >, >=, <, <=, and <>
Example - ALL Operator
Return the names of employees whose salary is greater than the salary of all
the employees in department 5
Query:
SELECT Lname, Fname
FROM EMPLOYEE
FROM EMPLOYEE
WHERE Dno=5 );
Ambiguity in Nested Queries
• Possible ambiguity among attribute names if attributes of the
same name exist—one in a relation in the FROM clause of the
outer query, and another in a relation in the FROM clause of
the nested query.
FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT Essn FROM DEPENDENT AS D WHERE E.Fname = Dependent_name AND E.Sex = Sex);
Retrieve the name of each employee who has a dependent with the same first
name and is the same sex as the employee.
For every project located in ‘Stafford’, list the project number, the
controlling department number, and the department manager’s last
name, address, and birth date.
Query:
WHERE Plocation=‘Stafford’;
EXISTS Function
Query:
FROM EMPLOYEE
• For each EMPLOYEE tuple, the correlated nested query selects all DEPENDENT tuples whose
Essn value matches the EMPLOYEE Ssn.
• If the result is empty, no dependents are related to the employee, so we select that EMPLOYEE
tuple and retrieve its Fname and Lname.
Aggregate Functions
and Group by clause
Aggregate Functions
Aggregate Functions
Query
FROM EMPLOYEE;
Example - Aggregate Functions (Cont.)
Aggregate Functions
Query
WHERE Dname=‘Research’;
Example - Aggregate Functions (Cont.)
Query
SELECT COUNT ( * )
Query
Query
SELECT Lname, Fname Counts the number of
dependents that each
FROM EMPLOYEE employee has; if this is
greater than or equal to
WHERE ( SELECT COUNT (*) two, the employee tuple is
selected
FROM DEPENDENT