A nested query, also known as a subquery, is a query within another SQL query. The inner query is executed first, and its result is used by the outer query. Subqueries can be used to filter, calculate, or manipulate data, and they allow you to perform more complex queries in a modular fashion.
SELECT column1
FROM table1
WHERE column2 = (SELECT column_name FROM table2 WHERE condition);
SELECT column1
FROM table1 AS t1
WHERE EXISTS (SELECT column_name FROM table2 AS t2 WHERE t2.column2 = t1.column1);
This type of subquery returns only one row and is typically used with comparison operators like =, >, <, etc.
Suppose we have an Employees table:
EmployeeID | FirstName | LastName | Salary |
---|---|---|---|
1 | John | Doe | 50000 |
2 | Jane | Smith | 60000 |
3 | Mike | Johnson | 70000 |
We want to find the details of the employee with the highest salary. Here's the query:
SELECT FirstName, LastName
FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees);
FirstName | LastName |
---|---|
Mike | Johnson |
A multi-row subquery returns multiple rows and is typically used with operators like IN, ANY, ALL.
You want to find employees who work in departments located in New York. Assume we have an Employees table and a Departments table:
EmployeeID | FirstName | DepartmentID |
---|---|---|
1 | John | 101 |
2 | Jane | 102 |
3 | Mike | 103 |
DepartmentID | DepartmentName | Location |
---|---|---|
101 | Sales | New York |
102 | HR | Boston |
103 | IT | New York |
Here’s the query:
SELECT FirstName
FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Location = 'New York');
FirstName |
---|
John |
Mike |
A correlated subquery refers to a column from the outer query and runs once for each row of the outer query. It depends on the outer query and cannot be run independently.
Find employees whose salary is higher than the average salary of their department. Assume we have the same Employees table with a DepartmentID column.
SELECT FirstName, Salary
FROM Employees E1
WHERE Salary > (SELECT AVG(Salary)
FROM Employees E2
WHERE E1.DepartmentID = E2.DepartmentID);
FirstName | Salary |
---|
Mike | 70000 |
You can also use a subquery in the FROM clause, treating the subquery as a temporary table.
SELECT AVG(Salary) AS AvgSalary
FROM (SELECT Salary FROM Employees WHERE DepartmentID = 101) AS SalesDept;
This query calculates the average salary of employees in the Sales department (DepartmentID = 101).