When filtering through the Where Clause during data reading from the database, the IN operator can check whether the column is within certain values.
Let’s make an example for a better understanding of the subject.
First, we create a table as below and add a few records to the table.
CREATE TABLE [dbo].[MyTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Age] int NOT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[MyTable] VALUES ('Nurullah',34),('Faruk',27),('Hakan',36),('Ogun',27)
Find people whose age is one of the values “25,26,27,28,29,30” :
SELECT * FROM [dbo].[MyTable] WHERE Age IN(25,26,27,28,29,30)
We can write the same query above with a subquery in the IN operator:
SELECT * FROM [dbo].[MyTable] WHERE Age IN(SELECT AGE FROM [dbo].[MyTable] Where Age <=30 AND Age>=25)