Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 219
Ronalds Mazītis Avatar asked Sep 14 '13 18:09

Ronalds Mazītis


People also ask

How do you select even and odd rows in SQL?

SELECT * FROM table_name WHERE mod(column_name,2) = 0; This syntax will find rows where our target column has odd values: SELECT * FROM table_name WHERE mod(column_name,2) <> 0; SQL Server does not have a MOD function.

How do you determine if a value is even or odd in SQL?

Syntax. To find and return the records with the odd or even values, the most simple way is to check the remainder when we divide the column value by 2. When the remainder is 0, that's an even number, otherwise, that's an odd number.

How do I select data from a row in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do you select unique values in SQL?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.


4 Answers

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

Will return all of the odd values of num.

like image 157
Steve Homer Avatar answered Sep 18 '22 07:09

Steve Homer


for even

 where ([num]% 2) = 0

for odd

 where ([num]% 2) <>0
like image 37
Sajidur Rahman Avatar answered Sep 20 '22 07:09

Sajidur Rahman


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;
like image 28
Bikramjeet Singh Avatar answered Sep 20 '22 07:09

Bikramjeet Singh


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.

like image 34
Neha Chopra Avatar answered Sep 20 '22 07:09

Neha Chopra