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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

WordPress.com.

Up ↑

%d bloggers like this: