Relationships and JOINs
Subqueries and correlated queries
Use one query’s result in another.
Understand the concept
A subquery can appear as a scalar expression, a derived table in FROM or a predicate in WHERE. A scalar subquery must return at most one value; multiple rows raise an error. IN tests membership in a result set, and a derived table needs an alias.
A correlated subquery references the outer row. That logical dependence does not guarantee a separate physical execution for every row: the optimizer can transform the plan. Evaluate both readability and the actual execution plan.
Use it for above-average values and within-group comparisons.
Forgetting that a scalar subquery may return multiple rows.
One topic. Three levels of depth.
SELECT ProductName, Price FROM lab.Product WHERE Price > (SELECT AVG(Price) FROM lab.Product);Compares each price with the overall average.
This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.
Try it yourself first.
Find every product tied at the maximum price using a subquery.
Show the solution and explanation
SELECT ProductName, Price FROM lab.Product WHERE Price = (SELECT MAX(Price) FROM lab.Product);Returns Laptop and would retain ties at the maximum.