Unit 2 Subquery
Unit 2 Subquery
2
Subqueries
SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");
Syntax :
Select select_list from table where expr opearator
(select select_list from table);
The subquery (inner query) executes once before the main query
(outer query) executes.
The main query (outer query) use the subquery
result.
Prepared By:-Darshana V.Halatwala 5
Using a Subquery
to Solve a Problem
“Who has a salary greater than Jones’?”
Main Query
Subquery
?
“What is Jones’ salary?”
In the example, the inner query determines the salary of employee 7566. The outer
query takes the result of the inner query and uses this result to display all the
employees who earn more than this amount.
ENAME
KING
FORD
SCOTT
Prepared By:-Darshana 10
Types of Subqueries
⚫ Single-row subquery : Queries that return only one row from the
inner SELECT statement
Main query
returns
Subquery CLERK
• Multiple-row subquery Queries that return more than one row from the
inner SELECT statement
Main query
returns
CLERK
Subquery
MANAGER
• Multiple-column subqueryQueries that return more than
one column from the inner SELECT statement
Main query
returns CLERK 7900
Subquery
MANAGER 7698
Prepared By:-Darshana V.Halatwala 11
Single-Row Subqueries
⚫ Return only one row
⚫ Use single-row comparison operators
Operator Meaning
= Equal to
ENAME JOB
JAMES CLERK
SMITH CLERK
ADAMS CLERK
MILLER CLERK
Prepared By:-Darshana V.Halatwala 13
Example:-
Find the employee whose salary is
second highest
Select max(sal) from emp where
sal<(select max(Sal) from emp);
Third highest:-
Select max(sal) from emp where sal<(
select max(sal) from emp where
sal<(select max(Sal) from emp));
ENAME JOB
MILLER CLERK
Prepared By:-Darshana V.Halatwala 15
Using Group Functions
in a Subquery
Display the employee name, job title, and salary of all employees
whose salary is equal to the minimum salary.
The SQL statement on the slide displays all the departments that
have a minimum salary greater than that of department 20.
ERROR:
ORA-01427: single-row subquery returns more than
one row
no rows selected
Operator Meaning
Syntax:-
SELECT column
FROM table1
WHERE column IN (
SELECT column
FROM table2
);
Query:-
Find the name of employees who are working on a project?
Select ename from emp where Eid IN (select Distinct(Eid)
from project);
Prepared By:-Darshana V.Halatwala 22
ANY Operator
Syntax:-
SELECT column
FROM table1
WHERE column ANY (
SELECT column
FROM table2
);
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);