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.
First, we create two tables as below and we add a few records to these tables.
CREATE TABLE [dbo].[Person](
[ID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
[DepartmentID] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Department](
[DepartmentID] [int] NOT NULL,
[DepartmentName] [varchar](50) NOT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Person] VALUES (1,'Nurullah',323),(2,'Faruk',356)
INSERT INTO [dbo].[Department] VALUES (323,'IT Department' ),(356,'Sales Department')
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.
(Select DepartmentName FROM [dbo].[Department] WHERE DepartmentID=mq.DepartmentID) subquery
FROM [dbo].[Person] mq
Using subquery in FROM section:
Let’s write the same query using the subquery in the FROM section as follows.
SELECT [Name],subquery.DepartmentID,subquery.DepartmentName FROM [dbo].[Person],
(Select [DepartmentID],[DepartmentName] FROM [dbo].[Department]) subquery
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’.
SELECT [Name],[DepartmentID] FROM [dbo].[Person]
WHERE [DepartmentID]=(Select [DepartmentID] FROM [dbo].[Department] WHERE [DepartmentName]='IT Department')