The IN clause in SQL Server allows us to specify multiple values in a WHERE clause. This can be useful when we want to filter data based on a set of predefined values or when we need to retrieve data from a subquery.
Let’s consider an example using the following tables:
CREATE TABLE [dbo].[Employee]( [Empid] [Int] IDENTITY (1, 1) NOT NULL Primary key, [EmpNumber] [nvarchar](50) NOT NULL, [EmpFirstName] [nvarchar](150) NOT NULL, [EmpLastName] [nvarchar](150) NULL, [EmpEmail] [nvarchar](150) NULL, [Salary] [int] NULL ) CREATE TABLE [dbo].[EmpProjects]( [EmpProjectId] [int] IDENTITY (1, 1) NOT NULL Primary key, [EmpNumber] [nvarchar](50) NOT NULL, [ProjectCode] [nvarchar](50) NOT NULL )
Suppose we want to retrieve the records of employees associated with the projects having project codes “Proj002” or “Proj005”. We can achieve this using the following query:
SELECT * FROM Employee WHERE EmpNumber IN ( SELECT EmpNumber FROM EmpProjects WHERE ProjectCode = 'Proj002' OR ProjectCode = 'Proj005' )
In the above query, we use a subquery to fetch the multiple values in the IN clause. The subquery selects the employee numbers from the EmpProjects table where the project code is either “Proj002” or “Proj005”. The main query then retrieves the records from the Employee table where the employee number is in the result of the subquery.
Now, let’s consider another scenario where we want to retrieve the records of employees who worked on the first project with the code ‘Proj001’. We can use a subquery for this as well, but let’s assume that this project was completed years ago and only three employees with employee numbers “A001”, “A002”, and “A003” worked on it. In this case, we can pass these employee numbers as predefined values in the IN clause, as shown in the following query:
SELECT * FROM Employee WHERE EmpNumber IN ('A001', 'A002', 'A003')
This query retrieves the records from the Employee table where the employee number is either “A001”, “A002”, or “A003”.
The IN clause is a powerful tool in SQL Server that allows us to filter data based on multiple values. Whether we use a subquery or predefined values, the IN clause provides flexibility in querying and retrieving the desired results.