A subquery, also known as a nested query or inner query, is a SQL query that is embedded within another SQL query, referred to as the outer query. A subquery is used to retrieve data that the outer query will use for further processing.
A subquery returning a single value.
Example
SELECT EmployeeName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
The inner query calculates the average salary. The outer query selects employees with a salary greater than the average.
A subquery returning multiple values.
Example
SELECT EmployeeName
FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Location = 'New York');
The inner query retrieves department IDs for departments in New York. The outer query selects employees who work in those departments.
A subquery that references columns from the outer query.
Example
SELECT EmployeeName, Salary
FROM Employees e1
WHERE Salary > (SELECT AVG(Salary) FROM Employees e2 WHERE e1.DepartmentID = e2.DepartmentID);
For each employee in the outer query, the subquery calculates the average salary in the same department. The outer query then selects employees whose salary exceeds the department average.