SQLServer Subqueries
Subquery in FROM clause
A subquery in a FROM clause acts similarly to a temporary table that is generated during the execution of a query and lost afterwards.
SELECT Managers.Id, Employees.Salary
FROM (
SELECT Id
FROM Employees
WHERE ManagerId IS NULL
) AS Managers
JOIN Employees ON Managers.Id = Employees.Id
Subquery in SELECT clause
SELECT
Id,
FName,
LName,
(SELECT COUNT(*) FROM Cars WHERE Cars.CustomerId = Customers.Id) AS NumberOfCars
FROM Customers
Subquery in WHERE clause
Use a subquery to filter the result set. For example this will return all employees with a salary equal to the highest
paid employee.
SELECT *
FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees)