You are on page 1of 15

SUBQUERIES

By
Neil A. Basabe
A subquery is a query place inside another
query.

syntax:
SELECT col-1, col-2, . . .
FROM table-1
WHERE operand operator ( SELECT col-1, col-b,...
FROM table-2
WHERE condition )
ORDER BY order-list

09/30/2020 Prepared by: SB Satorre 2


Rules:
1. Subqueries should be placed at the right side of the
operator in the WHERE clause or HAVING clause.
2. Subqueries should be placed inside the parenthesis.
3. The number of values returned by the subquery
should be equal and compatible with the value of
the operand in the WHERE clause.
4. The ORDER BY clause should be placed outside the
subquery.

09/30/2020 Prepared by: SB Satorre 3


Example 1
SELECT EMPNO, LASTNAME, SALARY
FROM EMPLOYEE
WHERE SALARY>(SELECT AVG(SALARY)
FROM EMPLOYEE);

Display the employee’s number, last name, salary of


all employees whose salary is more than the average
salary.

09/30/2020 Prepared by: SB Satorre 4


09/30/2020 Prepared by: SB Satorre 5
Example 2
SELECT EMPNO, LASTNAME, BONUS
FROM EMPLOYEE
WHERE BONUS=(SELECT MIN(BONUS)
FROM EMPLOYEE);

Display employee’s number, last name, and bonus of


all employees having the least bonus.

09/30/2020 Prepared by: SB Satorre 6


09/30/2020 Prepared by: SB Satorre 7
Example 3
SELECT EMPNO, LASTNAME, WORKDEPT, JOB
FROM EMPLOYEE
WHERE (WORKDEPT,JOB)=('D21','CLERK');

Display all employees who are assigned in ‘D21’ and


whose job description is ‘Clerk’.

09/30/2020 Prepared by: SB Satorre 8


09/30/2020 Prepared by: SB Satorre 9
Example 4

SELECT DEPTNO, DEPTNAME


FROM DEPARTMENT
WHERE DEPTNO NOT IN(SELECT DEPTNO
FROM PROJECT
WHERE DEPTNO IS
NOT NULL);

Display all departments that are not handling a


project.

09/30/2020 Prepared by: SB Satorre 10


09/30/2020 Prepared by: SB Satorre 11
Example 5
SELECT WORKDEPT,
AVG(SALARY) AS AVG_WORKDEPT
FROM EMPLOYEE
WHERE JOB<>'MANAGER'
GROUP BY WORKDEPT
HAVING AVG(SALARY)>(SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE JOB <>
'MANAGER');

Display the department and its average salary of


non-manager employees whose average salary is
more than the average.Prepared by: SB Satorre
09/30/2020 12
09/30/2020 Prepared by: SB Satorre 13
Example 6
From among the projects recorded in the PROJECT
table, run a query command that returns the project
number, name, start date, end date, and the project
duration (in days) of the PROJECT(s) with the least
number of working days. Furthermore, disregard
those negative duration values.

09/30/2020 Prepared by: SB Satorre 14


Laboratory Exercises – Sub-Queries

09/30/2020 Prepared by: SB Satorre 15

You might also like