T-SQL 101: 116 Using Subqueries in SQL Server T-SQL

T-SQL 101: 116 Using Subqueries in SQL Server T-SQL

Subqueries allow us to reuse data from one query in another query. There are three basic ways that this can work:

Row sets (tables) - a subquery can return an entire row set with columns. The basic structure of that is shown in the example above.

Lists - a type of row set that has a single column. It’s often used with an IN clause.

Scalar values - a single value returned from a query i.e., one row with one column. These are often used in place of values in expressions or predicates.

These are important because sometimes you need to go and execute a query to find something out and then to be able to use what you found in another query.

Another reason you do this is sometimes you might not be able to work out how to build a complicated query but if you can build it up piece by piece using subqueries you can often break down the complexity and make queries easier to write. Again, in some cases, there are possible performance issues here but we’ll discuss those later.

Next, we’ll see examples of each of these.

Learning T-SQL

It’s worth your while becoming proficient in SQL. If you’d like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

2025-02-16