Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 488
Phoenix Avatar asked Nov 11 '11 22:11

Phoenix


People also ask

How do you know if a value is even or odd?

If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using num % 2 == 1 .

How do you find even and odd in SQL?

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.

How do you find odd value?

To identify an odd number we can directly divide it by 2. If the number is exactly divisible by 2 it is not an odd number. For example, 4 is not an odd number as it is exactly divisible by 2.


2 Answers

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.

like image 108
Dair Avatar answered Sep 30 '22 17:09

Dair


For finding the even number we should use

select num from table where ( num % 2 ) = 0 
like image 37
anandharshan Avatar answered Sep 30 '22 18:09

anandharshan