0% found this document useful (0 votes)
20 views

SQL Subqueries

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Subqueries

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

SQL Subqueries

Made Simple

Anish Chakravorty
Follow me on LinkedIn
What is a Subquery?
A subquery is simply a query within another
query.
It helps retrieve intermediate results to be
used in the main query.

Why use subqueries?


Perform advanced filtering and
calculations.
Simplify complex SQL queries.
Example Table
This is Employees Table which is used as
example.

EmployeeID Name Department Salary

1 Rohit HR 50,000

2 Meera Sales 60,000

3 Vikram IT 70,000

4 Anjali Sales 55,000

5 Sunita HR 65,000

6 Aman IT 80,000
Single Row Subquery
A subquery that returns only one row as a
result.

Example:
Find the employee with the highest salary:

Result:

Aman (highest salary: 80,000).


Multi-Row Subquery
A subquery that returns multiple rows as a
result.

Example:
Find employees who work in the same
department as ‘Rohit’:

Result:

Sunita (in HR department)


Correlated Subquery
A subquery that depends on values from
the outer query for execution.

Example:
Find employees whose salary is above the
average salary of their department:

Result:

Meera, Sunita, Aman (salaries above


their department average).
Nested Subquery
A subquery inside another subquery, used
for complex queries.

Example:
Find the employee with the second-highest
salary:

Result:

Vikram (second-highest salary: 70,000).


Scalar Subquery
A subquery that returns a single value,
often used in SELECT statements.

Example:
Display each employee's salary alongside the
company’s average salary:

Result:

Company
Name Salary
AvgSalary

Rohit 50,000 63,333

Meera 70,000 63,333


Key Benefits of
Subqueries

Simplify complex SQL logic.

Reuse subquery results in the main


query.

Perform advanced filtering and


calculations.

Combine with JOIN or GROUP BY for


powerful data analysis.
Follow me to
get more
Information
and content
like this.
Anish Chakravorty
Follow me on LinkedIn

You might also like