Subqueries in SQL
Subqueries in SQL
Types of Subquery: -
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-
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
Select Avg(Sal) as AverageSalary
from EMP
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))
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
)
Let us now discuss about using a sub query in the SELECT clause.
Select Name,
(Select SUM(QuantitySold) from tblProductSales where ProductId =
tblProducts.Id) as TotalQuantity
from tblProducts
order by Name
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.
From the given result we need to find out PRODUCTID based on maximum
total value.
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,
(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