How to select odd or even items from a row in SQL?
Asked Answered
S

4

11

I need only even or odd items, so I find modulus operation and this doesn't works

SELECT  * FROM table ORDER BY id WHERE MOD (num, 2) = 1 ASC;

Please help me, I'm noob in sql, as I haven't done much in it.

Susurrous answered 14/9, 2013 at 18:30 Comment(0)
H
21
SELECT * 
FROM table 
WHERE MOD (num, 2) = 1 
ORDER BY id ASC;

Will return all of the odd values of num.

Huss answered 14/9, 2013 at 18:35 Comment(1)
If you have duplicate values you should add the DISTINCT option.Voight
B
6

for even

 where ([num]% 2) = 0

for odd

 where ([num]% 2) <>0
Beaston answered 1/12, 2015 at 11:15 Comment(0)
R
4

For even, query:

SELECT 
  * 
FROM 
  table_name 
WHERE 
  MOD(NUM, 2) = 0 
ORDER BY 
  ID ASC;

For odd, query:

SELECT 
  * 
FROM 
  table_name 
WHERE 
  MOD(NUM, 2) != 0 
ORDER BY 
  ID ASC;
Raymundorayna answered 3/3, 2019 at 12:29 Comment(0)
E
3
SELECT * FROM table WHERE MOD(num, 2) = 1 ORDER BY id ASC;

After fetching the final resultSet for the sql server based on where condition then only we can apply any ordering either ASC and DESC.

Emeliaemelin answered 1/8, 2017 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.