Consider a database that has the relation schema EMP (EmpId, EmpName, and DeptName). An instance of the schema EMP and a SQL query on it are given below:
SELECT AVG(EC.Num)
FROM EC
WHERE (DeptName, Num) IN
(SELECT DeptName, COUNT(EmpId) AS
EC(DeptName, Num)
FROM EMP
GROUP BY DeptName)The output of executing the SQL query is _____________ .
View worked solution
Answer: 2.6
The subquery groups the EMP table by DeptName and counts the number of employees in each department. This temporary relation is aliased as EC(DeptName, Num).
Grouping the given EMP instance by DeptName yields the following counts (Num) for each department:
- AA: 4 employees (EmpId 1, 2, 3, 4)
- AB: 3 employees (EmpId 5, 6, 7)
- AC: 3 employees (EmpId 8, 9, 10)
- AD: 2 employees (EmpId 11, 12)
- AE: 1 employee (EmpId 13)
The relation EC contains these 5 rows. The WHERE (DeptName, Num) IN (...) clause checks if each row of EC is present in the subquery's result. Since the subquery generates exactly the rows of EC, all 5 rows satisfy the condition.
Finally, the outer query computes the average of the Num column:
Free practice · Your answers on this page are not saved.
