Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

.

 Query with in another Query is known as subquery.  A subquery must be


enclosed in brackets and can be used in SELECT, FROM, WHERE and
HAVING clauses
 If you want to fetch data from one table but based on condition of another
table then we should go for Subquery.

 Types of Subquery: -

1. Single row Subquery (getting single value) (using = operator)


2. Multi Sub Query (if query generating more than output value is
called [In operator uses]

 A subquery may occur in:


 A SELECT clause
 A FROM clause
 A WHERE clause

 The subquery can be nested inside a SELECT, INSERT, UPDATE, or


DELETE statement or inside another subquery.

 A subquery is usually added within the WHERE Clause of another SQL


SELECT statement.

 You can use the comparison operators, such as >, <, or =. The
comparison operator can also be a multiple-row operator, such as IN,
ANY, or ALL.

Execution Process-

 Inner most Query To outermost Query except in the case of co-related


query.
 The inner query executes first before its parent query so that the results
of an inner query can be passed to the outer query.

Que-
In which case joins required and In Which case Subquery is required?

Ans-
 If you want to fetch data from multiple table get placed one column
from table and another column from second table i.e. if you want to
fetch two columns from two table definitely, we should use joins.

 Subquery said if you are expecting the data from one table but based
on condition of another table it is better to use subquery.
SELECT and FROM clause in Subquery.
SELECT EMPNO,ENAME,JOB, SAL,AVG(SAL) FROM EMP
 Whenever we are using aggregate function in select statement if we are
using apart from aggregate function another column name in select
statement it will produce error. If you want to use another column-name also
along with aggregate function then we have to require to use subquery in
select statement.
ORA-00937: not a single-group group function
 A subquery in SELECT clause can return a single value (single row and
single column). It should be provided an alias name
A subquery in SELECT clause
SELECT EMPNO, ENAME, JOB, SAL, (SELECT ROUND (AVG (SAL))
FROM EMP) AS AVGSAL FROM EMP

A subquery in FROM clause


SELECT * FROM (SELECT EMPNO, ENAME, JOB, SAL FROM EMP) E
Write an query to display the avg salary of employees

Select Avg(Sal) as AverageSalary 
from EMP

Write an query to display the round off avg salary of employees

Select ROUND(Avg(Sal)) as AverageSalary 
from EMP

Write an query to display the employees who are getting more salary
than round off avg salary from tblemployee

 Select *
from EMP
where sal> (Select ROUND(Avg(Sal)) from EMP)
Write an query to display the employees who are working in Hr
department from tblemployee, tbldepartment

select Id,Name,Salary,Gender
from  tblemployee
where  departmentid=
(select deptid from  tbldepartment where  deptname='HR')

OR

select * from 
(SELECT Id, Name, Gender, Salary, Deptname
from tblEmployee
INNER JOIN tblDepartment
on tblEmployee.DepartmentId = tblDepartment.deptid)
where deptname='HR'
Write a query to display senior most employee details from emp table.

select *
from emp
where hiredate=( select min(hiredate) from  emp)

Write an query to display junior most employee details from emp table.
select *
from emp
where hiredate=( select max(hiredate) from  emp)
Write a query to Fetch details of employees who are getting highest salary.
select *
from emp
where sal= (select max(sal) from emp)

Write a query to Fetch details of employees who are getting Second highest
salary.
select *
from emp
where sal= (select max(sal) from emp where sal< select max(sal)
from emp))

Write a query to display highest paid deptno emp table.


select deptno from emp where sal=( select max(sal) from emp)

Write an query to display highest paid deptname dept emp table.


select dname from dept
where deptno = (select deptno from emp where sal= (select max(sal) from emp))
Write a query to display the employees who are working under 'BLAKE'
from emp table
select * from emp
where mgr= (select empno from emp where ename='BLAKE')

Display the department number in which the maximum total salary is paid to
the employees.
SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING
SUM(SAL)=(SELECT MAX(SUM(SAL)) FROM EMP GROUP BY
DEPTNO)

Display the department name in which the maximum total salary is paid to
the employees.
SELECT DNAME FROM DEPT WHERE DEPTNO=(SELECT DEPTNO
FROM EMP GROUP BY DEPTNO HAVING SUM(SAL)=(SELECT
MAX(SUM(SAL)) FROM EMP GROUP BY DEPTNO))
Multiple Row Subquery Examples
1. Write a query to find the employees whose salary is equal to the salary of at least one
employee in department of id 3?

select * from emp where sal in(select sal from emp where deptno=20)

Write a query to find the employees whose salary is greater than at least on employee in
department of id 500?

select * from emp where sal > any(select sal from emp where deptno=20)
Create Table tblProducts
(
Id number primary key,
Name varchar2(50),
Description varchar2(250)
)

Create Table tblProductSales
(
Id number primary key ,
ProductId number,
UnitPrice number,
QuantitySold number

Insert into tblProducts values ('TV', '52 inch black color LCD TV')


Insert into tblProducts values ('Laptop', 'Very thin black color acer laptop')
Insert into tblProducts values ('Desktop', 'HP high performance desktop')

Insert into tblProductSales values(3, 450, 5)


Insert into tblProductSales values(2, 250, 7)
Insert into tblProductSales values(3, 450, 4)
Insert into tblProductSales values(3, 450, 9)
Write a query to retrieve products that are not at all sold?
This can be very easily achieved using subquery as shown below. 
Select Id, Name, Description
from tblProducts
where Id not in (Select Distinct ProductId from tblProductSales)
In this example, we have seen how to use a subquery in the where
clause.

In this example, we have seen how to use a subquery in the where


clause.

Let us now discuss about using a sub query in the SELECT clause. 

Write a query to retrieve the NAME and TOTALQUANTITY sold,


using a subquery.

Select Name,
(Select SUM(QuantitySold) from tblProductSales where ProductId =
tblProducts.Id) as TotalQuantity
from tblProducts
order by Name

From these examples, 


it should be very clear that, a subquery is simply a select statement, that
returns a single value and can be nested inside a SELECT, UPDATE,
INSERT, or DELETE statement. 

It is also possible to nest a subquery inside another subquery.

Subqueries are always encolsed in paranthesis and are also called as inner
queries, and the query containing the subquery is called as outer query.

The columns from a table that is present only inside a subquery, cannot be
used in the SELECT list of the outer query.
 In the TBLPRODUCTSALES table first we need to find that PRODUCTID
which occur maximum number of times.so how we can find out. For that we
make a group based PRODUCTID and count the number of values in each
group. Now we write the query to get the expected result.

SELECT PRODUCTID, COUNT (PRODUCTID) AS TOTAL FROM


TBLPRODUCTSALES GROUP BY PRODUCTID

 From the given result we need to find out PRODUCTID based on maximum
total value.

SELECT PRODUCTID FROM


(SELECT PRODUCTID, COUNT (PRODUCTID) AS TOTAL FROM
TBLPRODUCTSALES GROUP BY PRODUCTID) P
WHERE TOTAL= (SELECT MAX (COUNT (PRODUCTID)) FROM
TBLPRODUCTSALES GROUP BY PRODUCTID)

 The above query give the PRODUCTID which occur maximum number of
times in TBLPRODUCTSALES table. Now we need to select product name
from TBLPRODUCTS table whose id match to the above query result.
SELECT NAME FROM TBLPRODUCTS WHERE ID= (SELECT
PRODUCTID FROM (SELECT PRODUCTID, COUNT (PRODUCTID)
AS TOTAL FROM TBLPRODUCTSALES P GROUP BY PRODUCTID)
P WHERE TOTAL= (SELECT MAX (COUNT (PRODUCTID)) FROM
TBLPRODUCTSALES GROUP BY PRODUCTID))

SELECT NAME FROM TBLPRODUCTS WHERE ID= (SELECT


PRODUCTID FROM
(SELECT PRODUCTID, SUM (QUANTITYSOLD) AS
MAXQUANTITYSOLD FROM TBLPRODUCTSALES GROUP BY
PRODUCTID) P
WHERE MAXQUANTITYSOLD = (SELECT MAX (SUM
(QUANTITYSOLD)) FROM TBLPRODUCTSALES GROUP BY
PRODUCTID))

Correlated subquery in sql


find the details of all product which are not sold

Select * from tblproduct


where PRODUCTID not in (Select distinct productid from tblproductsales)

Write a query to retrieve the Product NAME and TOTALQUANTITY


sold, using a subquery.

Select Name,
(Select SUM(QuantitySold) from tblProductSales where ProductId =
tblProduct. PRODUCTID) as TotalQuantity
from tblProducts
order by Name 
In the example below, sub query is executed first and only once. The sub
query results are then used by the outer query. A non-corelated subquery can
be executed independently of the outer query.
Select [Id], [Name], [Description]
from tblProducts
where Id not in (Select Distinct ProductId from tblProductSales) 

If the subquery depends on the outer query for its values, then that sub
query is called as a correlated subquery. In the where clause of the subquery
below, "ProductId" column get it's value from tblProducts table that is
present in the outer query. So, here the subquery is dependent on the outer
query for it's value, hence this subquery is a correlated subquery. Correlated
subqueries get executed, once for every row that is selected by the outer
query. Corelated subquery, cannot be executed independently of the outer
query.
Select [Name],
(Select SUM(QuantitySold) from tblProductSales where ProductId =
tblProducts.Id) as TotalQuantity
from tblProducts
order by Name 

You might also like