A Subquery is a SQL query written inside another SQL statement. The inner query executes first and returns a result that is used by the outer query. Subqueries can be used with SELECT, INSERT, UPDATE, DELETE, and WHERE clauses to retrieve data dynamically based on another query.
Many real-world business problems require comparing data against calculated values or another dataset. Subqueries allow analysts to build dynamic queries without manually entering filter values.
Suppose a manager wants to find employees earning more than the company's average salary. Instead of calculating the average manually, a subquery calculates the average salary first, and the outer query returns employees whose salary is greater than that value.
SELECT
EmployeeName,
Salary
FROM Employees
WHERE Salary >
(
SELECT AVG(Salary)
FROM Employees
);
Subqueries are widely used in reporting, HR analytics, finance, customer segmentation, fraud detection, inventory management, and business intelligence dashboards.
- A Subquery is a query inside another query.
- The inner query executes before the outer query.
- Subqueries can return single or multiple values.
- They are commonly used with WHERE and IN clauses.
- Subqueries reduce manual calculations.
- They simplify complex business queries.
- Subqueries improve query flexibility.
What is a Subquery in SQL?
A Subquery is a SQL query written inside another SQL query. The inner query executes first and its result is used by the outer query.
Where can Subqueries be used?
Subqueries can be used in SELECT, INSERT, UPDATE, DELETE, WHERE, HAVING, and FROM clauses depending on the database system.