Page 194 - SQL
P. 194
Chapter 53: Subqueries
Remarks
Subqueries can appear in different clauses of an outer query, or in the set operation.
They must be enclosed in parentheses (). If the result of the subquery is compared to something
else, the number of columns must match. Table aliases are required for subqueries in the FROM
clause to name the temporary table.
Examples
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)
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
Subqueries in FROM clause
You can use subqueries to define a temporary table and use it in the FROM clause of an "outer"
query.
https://riptutorial.com/ 176

