In this post explains how to use subqueries in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server, a subquery is a query within a query. You can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.
For example:
The subquery portion of the SELECT statement above is:
This subquery allows you to find all product_id values from the inventory table that have a quantity greater than 10. The subquery is then used to filter the results from the main query using the IN condition.
This subquery could have alternatively been written as an INNER join as follows:
This INNER JOIN would run more efficiently than the original subquery. It is important to note, though, that not all subqueries can be rewritten using joins.
A subquery can also be found in the FROM clause. These are called inline views.
For example:
In this example, we've created a subquery in the FROM clause as follows:
This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields.
A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the SUM, COUNT, MIN, or MAX function, but you do not want the aggregate function to apply to the main query.
For example:
In this example, we've created a subquery in the SELECT clause as follows:
The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields.
The trick to placing a subquery in the select clause is that the subquery must return a single value. This is why an aggregate function such as the SUM, COUNT, MIN, or MAX function is commonly used in the subquery.