ch7 Sub Query
ch7 Sub Query
Chapter elevent
Ch7 Sub Query
Amoud University
Faculty of Computing and ICT
Sub Query
• Sub Query: A select query contains another select query is called sub Query.
• In this, there will be two queries those are called as inner query and outer query.
• When it is executed, first inner query is executed later outer query will be executed
• Syntax: select * from <Table Name> where (condition) (select *
• from…….. (Select * from….. (select * from……..)));
Single Row Subquery:
• Display all the employees whose salary is less than the maximum salary of all the employees.
• SELECT ename,sal FROM emp WHERE sal < (SELECT MAX(sal) FROM emp);
• 1) WAQ to find the details of employee who is earning the highest salary.
• Sol: select * from employe where Sal=(select MAX(sal) from employe)
• 2) WAQ to display employee details who are working in .NET department.
• Sol: select * from employee where EID IN (select EID FROM employee whereDNAME='.NET')
Multiple Row Subquery
• When subquery returns multiple rows. It is called multiple row subquery .
• A sub query, which returns more than one value .
• Note: we should multiple row operators with multiple row subqueries. They are three multiple
row operators.
• 1. ANY 2. IN 3. ALL
• ALL: Compares a value to every value in a list or returned by a query. Must be preceded by =, !=,
>, <, <=, >=. evaluates to TRUE if the query returns no rows.
examples
• 2) WAQ to find the details of employee who is earning second highest salary.
• select * from employee where Salary=(select MAX(salary)from employee where
Salary<(select MAX(salary) from employee)) //multiple sub query
• display employees whose salary is greater than every salesman’s salary ?
• SELECT ename FROM emp WHERE SAL > ALL ( SELECT sal FROM emp WHERE job =
'SALESMAN');
• Select * from emp Where sal > ALL(Select sal from emp Where deptno = 30);
• Ex: Select * from emp where sal < ALL(1600,2500,1250,3000,950);
• *ANY: Compares a value to each value in a list or returned by a query.
• Must be preceded by =, !=, >, <, <=, >=. Evaluates to FALSE if the query returns no rows.
• Select * from emp where sal > ANY(select sal from emp where deptno = 30);
• Select * from emp where sal < Any(select sal from emp where deptno = 30);
continue-----------
• IN:
• Select * from emp where ename IN(‘ALLEN’, ‘KING’,’FORD’);
• Select * from emp where sal IN(select sal from emp where deptno = 30);
• Example :-
• Displaye employee records whose job equals to job of SMITH or job of BLAKE ?
• SELECT * FROM emp WHERE job IN (SELECT job FROM emp WHERE ename IN
('SMITH','BLAKE'));