0% found this document useful (0 votes)
426 views17 pages

Understanding SQL Subqueries and Examples

A subquery is a query nested inside another SQL statement. It allows you to fetch data from one table based on conditions in another table. There are two types of subqueries: single-row and multi-row. A subquery can be used in the SELECT, FROM, and WHERE clauses. The inner query executes first before the outer query, with the exception of correlated subqueries where the inner query depends on the outer query.

Uploaded by

Ashutosh Trivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
426 views17 pages

Understanding SQL Subqueries and Examples

A subquery is a query nested inside another SQL statement. It allows you to fetch data from one table based on conditions in another table. There are two types of subqueries: single-row and multi-row. A subquery can be used in the SELECT, FROM, and WHERE clauses. The inner query executes first before the outer query, with the exception of correlated subqueries where the inner query depends on the outer query.

Uploaded by

Ashutosh Trivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

.

 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 [Link] = [Link])
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 =
[Link]) 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 [Link] 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 =
[Link]) as TotalQuantity
from tblProducts
order by Name 

Common questions

Powered by AI

In a subquery, the inner query executes completely first and independently of the outer query. The results of the inner query are then passed to the outer query for further processing . In contrast, a correlated subquery executes once for each row processed by the outer query and depends on the outer query for its values. This means that the correlated subquery re-evaluates for each row returned by the outer query, making it dependent on the context of each row .

A correlated subquery can be less efficient than a non-correlated subquery because it must be executed repeatedly, once for each row processed by the outer query. This dependency on the outer query for its values leads to multiple executions, which can become computationally expensive for large data sets as opposed to a non-correlated subquery that executes just once independently of the outer query .

To find products that have never been sold, you can use a subquery to filter products by comparing their IDs to the distinct ProductId entries in the tblProductSales table. The query would be: 'SELECT Id, Name, Description FROM tblProducts WHERE Id NOT IN (SELECT DISTINCT ProductId FROM tblProductSales)'. This query identifies products not appearing in the sales record, effectively listing unsold products .

A subquery is essential in scenarios where calculations or testing conditions affect the main query results, such as when you want to compare an aggregate value with other values in the dataset. For example, determining if the salary of an employee is greater than the average salary of all employees requires calculating the average salary using a subquery first, which can then be compared across the dataset in the outer query . Such calculations are difficult to directly incorporate into JOIN operations because they require a distinct, separate evaluation against aggregated data, which JOINs do not inherently support without additional processing or subqueries.

Attempting to select non-aggregated columns alongside an aggregate function without using a subquery or grouping will result in the SQL error ORA-00937: "not a single-group group function". This error occurs because SQL requires all columns being selected alongside aggregate functions to be part of a GROUP BY clause unless they are computed through a subquery .

To efficiently determine the best-selling product by quantity, you can aggregate sales quantities by ProductId and identify the one with the maximum total. First, group by ProductId and sum the QuantitySold, then select the ProductId with the maximum sum: 'SELECT Name FROM tblProducts WHERE Id=(SELECT ProductId FROM (SELECT ProductId, SUM(QuantitySold) AS MaxQuantitySold FROM tblProductSales GROUP BY ProductId) WHERE MaxQuantitySold = (SELECT MAX(SUM(QuantitySold)) FROM tblProductSales GROUP BY ProductId))'. This efficiently uses nested subqueries to isolate the highest summed quantity and retrieve the associated product name .

When you need to include an aggregate function like AVG(SAL) in a SELECT statement alongside other columns without receiving the SQL error "not a single-group group function," you can use a subquery. The subquery allows you to calculate the aggregate function separately from selecting additional columns by ensuring that the aggregate computation is completed and aliased in the subquery context. For example, calculating the average salary within a subquery prevents the aggregate function from conflicting with non-aggregated columns in the main SELECT clause .

Joins should be used when you want to fetch data from multiple tables and need to display columns from more than one table in a single result set. They are efficient for combining rows from two or more tables, based on a related column between them . Subqueries are useful when you need to perform operations where the selection criteria depend on data from one or more tables, but you don't necessarily want to display columns from multiple tables together. Subqueries are often used to filter results of the outer query based on computations or conditions from another table .

Subqueries can be used to compare individual employee salaries against the rounded average salary calculations from the entire department, effectively allowing identification of employees earning above-average. The subquery calculates the average salary within its own scope. Filtering is then applied in the WHERE clause of the outer query to select only those employees whose salaries exceed this average, e.g., 'SELECT * FROM EMP WHERE SAL > (SELECT ROUND(AVG(SAL)) FROM EMP)' . This method is particularly useful when cross-referencing between departments without needing complex joins.

It is necessary to use an alias when a subquery returns a single value in a SELECT clause to label the column output clearly, making the results more readable and manageable. Without an alias, the result set can lack clarity and may not be compliant with the structure expected by some reporting tools. You implement this by following the subquery with an 'AS' clause that includes a descriptive alias; for example, '(SELECT ROUND(AVG(SAL)) FROM EMP) AS AVGSAL' assigns the resultant single value from the subquery to a column alias named 'AVGSAL' .

You might also like