Subqueries: SELECT Select - List From WHERE Expr Operator
Subqueries: SELECT Select - List From WHERE Expr Operator
SELECT select_list
FROM table
( SELECT select_List
FROM table );
•WHERE clauss
•HAVING clause
•FROM clause
ln the syntax;
SELECT ename
FROM EMP
WHERE sal >
( SELECT sal FROM
emp WHERE
empno=7566);
ENAME
FORD
SCOTT
KING
FORD
Using a Subquery
7 rows selected.
SELECT ename, sal, deptno
FROM EMP
WHERE sal IN
( SELECT MIN(sal)
FROM emp
GROUP BY deptno );
FROM emp
( SELECT sal
FROM emp
8 rows selected.
SELECT empno, ename, job
FROM emp
WHERE sal > ALL
( SELECT AVG(sal)
FROM emp
GROUP BY deptno ) ;
Single-Row Subqueries
Operator Meaning
=
Equal to
>
Greater than
>=
Greater than or equal to
<
Less than
<=
<> , =! Less than or equal to
Not equal to
ENAME JOB
ADAMS CLERK
JAMES CLERK
MILLER CLERK
SMITH CLERK
ADAMS CLERK
JAMES CLERK
MILLER CLERK
7 rows selected
Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery
Multiple-Row Subqueries
2. Create a query to display the employee number and name for all employees who earn
more than the average salary. Sort the results in descending order of salary.
3. Write a query to display the employee number and name for all
employees who work in a department with any employee whose name
contains a T. Save your SQL statemant in a file called p6q3.sql .
24
4. Display the employee name, department number, and job title for
all employees whose department location is Dallas.
Solution with subquery:
5. Display the employee name and salary of all employees who report to
King.
Solution with self join:
AND
d.ename ='KING';
25
SELECT ename, sal
FROM emp
FROM emp
6. Display the department number, name,, and job for all employees in the
Sales department.
SELECT e.deptno, e.ename, e.job , d.dname
FROM emp e , dept d
WHERE e.deptno = d.deptno
AND
d.dname = 'SALES'
7. Modify p6q3.sql to display the employee number, name, and salary for
all employees who earn more than the average salary and who work in a
department with any employee with a T in their name. Rerun your query.