SQL Server › Subqueries

What is a subquery in SQL Server, and how is it typically used within a larger query?

Beginner

Answer

A subquery is a query nested inside another query, often used within a WHERE clause to filter results based on the outcome of that inner query, within a SELECT list to calculate a related value, or within a FROM clause to treat its result as if it were a temporary table for the outer query to work with.
SELECT Name FROM Customers
WHERE CustomerId IN (SELECT CustomerId FROM Orders WHERE Amount > 1000);
Real-world example A marketing report finds all customers who have placed at least one order over a thousand dollars, using a subquery to first identify the relevant customer ids before selecting their names in the outer query.

Common follow-ups: What is the difference between a subquery in the WHERE clause versus the FROM clause?;Can a subquery return more than one column?