A Subquery is a SQL query nested inside another SQL statement. The inner query executes first and returns a value or result set that is used by the outer query. Subqueries can be used with SELECT, INSERT, UPDATE, DELETE, and WHERE clauses.
Many business questions require comparing records against calculated values or another dataset. Subqueries make these dynamic comparisons possible without manually entering values.
A manager wants to find employees earning more than the company's average salary. Instead of calculating the average manually, a subquery calculates it automatically and returns employees whose salary is higher.
SELECT
EmployeeName,
Salary
FROM Employees
WHERE Salary >
(
SELECT AVG(Salary)
FROM Employees
);
Subqueries are widely used in HR analytics, banking, finance, inventory management, customer segmentation, fraud detection, compliance reporting, and business intelligence dashboards.
- A Subquery is a query inside another query.
- The inner query executes first.
- The outer query uses the result of the inner query.
- Can return a single value or multiple values.
- Works with SELECT, INSERT, UPDATE, and DELETE.
- Simplifies complex SQL queries.
- Frequently used in analytical reporting.
What is a Subquery in SQL?
A Subquery is a SQL query written inside another SQL query whose result is used by the outer query.
Which query executes first in a Subquery?
The inner query executes first, followed by the outer query.