Finding Even or Odd Id Values

I was working on a query today which required me to use the following to find all odd number ID values

(ID % 2) <> 0

Can anyone tell me what this is doing? It worked, which is great, but I'd like to know why.

1

ID % 2 is checking what the remainder is if you divide ID by 2. If you divide an even number by 2 it will always have a remainder of 0. Any other number (odd) will result in a non-zero value. Which is what is checking for.

2

For finding the even number we should use

select num from table where ( num % 2 ) = 0

As Below Doc specify

dividend % divisor

Returns the remainder of one number divided by another.

For Example

13 % 2 return 1

Next part is <> which denotes Not equals.

Therefor what your statement mean is Remainder of ID when it divided by 2 not equals to 0

Be careful because this is not going to work in Oracle database. Same Expression will be like below.

MOD(ID, 2) <> 0

ID % 2 reduces all integer (monetary and numeric are allowed, too) numbers to 0 and 1 effectively.
Read about the modulo operator in the manual.

In oracle,

select num from table where MOD (num, 2) = 0;

dividend % divisor

Dividend is the numeric expression to divide. Dividend must be any expression of integer data type in sql server.

Divisor is the numeric expression to divide the dividend. Divisor must be expression of integer data type except in sql server.

SELECT 15 % 2

Output
1

Dividend = 15

Divisor = 2

Let's say you wanted to query

Query a list of CITY names from STATION with even ID numbers only.

Schema structure for STATION:

ID Number

CITY varchar

STATE varchar


select CITY from STATION as st where st.id % 2 = 0

Will fetch the even set of records 


In order to fetch the odd records with Id as odd number.

select CITY from STATION as st where st.id % 2 <> 0

% function reduces the value to either 0 or 1

1

It's taking the ID , dividing it by 2 and checking if the remainder is not zero; meaning, it's an odd ID.

<> means not equal. however, in some versions of SQL, you can write !=

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest