Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Even or odd in SQL

This is table structure

id
1
2
3
4
5
6

I need result like this

id  even  odd
1   0     1
2   1     0
3   0     1
4   1     0
5   0     1
6   1     0

I tried

select id %2=0 then 1 else 0 end or id%2 <>0 then 1 else 0 odd 
from table

2 Answers

How about

select 
  id, 
  ~id & 1, 
  id & 1 
from t
like image 80
Alex K. Avatar answered Dec 07 '25 21:12

Alex K.


Take a look at the CASE keyword. It works very similarly to what you're trying to do in your SELECT statement. In addition, if you want to select multiple columns, separate them with a comma. The OR keyword is used for combining logical conditions in your query, not for specifying multiple columns.

An example of how you could use CASE in your query would be as follows:

SELECT id,
       CASE WHEN id %2=0 THEN 1 ELSE 0 END AS Even,
       [column2]
FROM   [TableName]
like image 38
Jon Senchyna Avatar answered Dec 07 '25 21:12

Jon Senchyna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!