SubQueries in SQL Server(TSQL)

 

In SQL Server, you can write query in a query. You can write the subqueries in the SELECT section, FROM section, and the WHERE section of the query. The Main query is also known as OUTER QUERY or OUTER SELECT, and subquery is known as INNER QUERY or INNER SELECT

In the following example, you can find subquery uses.

Example:

First, we create two tables as below and we add a few records to these tables.

Using subquery in SELECT section:

With the following query, we read the Name and DepartmentID columns in the Person table and the DepartmentName from the Department table with Subquery. This query will work better with the INNER JOIN method. I just wanted to show you how to use subqueries in the Select section of the query.

Using subquery in FROM section:

Let’s write the same query using the subquery in the FROM section as follows.

Using subquery in WHERE section:

Using a subquery in the WHERE section, let’s write a query as follows. In this query, we list the records that have the DepartmentName value ‘IT Department’.

dbtut
Author: dbtut

We are a team with over 10 years of database management and BI experience. Our Expertises: Oracle, SQL Server, PostgreSQL, MySQL, MongoDB, Elasticsearch, Kibana, Grafana.

Leave a Reply

Your email address will not be published. Required fields are marked *