Selecting Only EVEN or ODD Records from Tables – MS SQL SERVER

Introduction

In this article, we will learn to Select only EVEN or ODD records from the MS SQL Server database table🤔. The efficient way to find the record belongs to even or odd is determining by the table’s ID column.

Select EVEN Records

By applying the modulo operator by 2 for the ID column, we can find the record is even or odd. If the modulo operation’s results equal to Zero or 0, then that record is EVEN. Else ODD record.

Syntax

SELECT * FROM TableName WHERE ColumnName % 2= 0;
Fig 1. Full Student Details Record from the table

Example

From the above table results, lets select EVEN Records

SELECT [StudentId]
,[FirstName]
,[LastName]
,[RegistrationNumber]
,[Degree]
,[CreatedDate]
,[CreatedBy]
FROM [Details].[StudentDetails] WHERE StudentId % 2=0;
Fig 2. Even Records from the Student Details Table

Select ODD Records

If the modulo operation result is not equal to Zero or 0, then its ODD record.

Syntax

SELECT * FROM TableName WHERE ColumnName % 2!=0;

Example

SELECT [StudentId]
,[FirstName]
,[LastName]
,[RegistrationNumber]
,[Degree]
,[CreatedDate]
,[CreatedBy]
FROM [Details].[StudentDetails] WHERE StudentId % 2!=0;
Fig 3. ODD Records from the Student Details Table

Conclusion

Thus applying Modulo operation by 2 we can determine that record is even or odd. I hope, you all found this article useful. Please share your feedback in the comment section.

Responses

  1. […] Selecting Only EVEN or ODD Records from Tables – MS SQL SERVER […]

    Liked by 1 person

  2. […] Selecting Only EVEN or ODD Records from Tables – MS SQL SERVER […]

    Liked by 1 person

  3. Rakesh Kumar Avatar

    Below query would also returns same result:

    SELECT [StudentId],[FirstName],[LastName],[RegistrationNumber],[Degree],[CreatedDate],
    [CreatedBy]

    FROM [Details].[StudentDetails]

    WHERE StudentId LIKE ‘%[0,2]’

    Liked by 1 person

  4. Sundaram Subramanian Avatar

    I do not think the logic which you said is correct, because this will give results of student whose ID has 0 and 2.

    Liked by 1 person

Leave a reply to Sundaram Subramanian Cancel reply