Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all even id's from a Table?

I want to select all even posts id's from a table in my MySQL db and then display them. I also want to get all posts with odd id's and display them somewhere else.

I want to do this with PHP since that is the server-side language I am using.

Alternatively, would I have to select all posts and then check if they are even/odd with JavaScript? I would prefer PHP, but if it works with JavaScript that would be fine too.

Example of what I want:

table:

==================================================
id | text
==================================================
==================================================
| 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. |
================================================== 
| 2 | turpis quis aliquet commodo, urna quam viverra justo, in |
==================================================
| 3 | Etiam in lectus sem. Nullam molestie nisl vel nunc consectetur |
==================================================
| 4 | Vestibulum eu molestie sapien. Ut luctus nulla vel libero sagittis |
==================================================

my failed attempt at a table in stackoverflow ^^

I want to display the even ones first, and the odd ones second:

Even Rows:


turpis quis aliquet commodo, urna quam viverra justo, in

Vestibulum eu molestie sapien. Ut luctus nulla vel libero sagittis


Odd Rows:

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Etiam in lectus sem. Nullam molestie nisl vel nunc consectetur

like image 443
nitrous Avatar asked Feb 01 '14 23:02

nitrous


People also ask

How can you select all the even number records from a table?

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 you select an even number ID in SQL?

You are not using Oracle, so you should be using the modulus operator: SELECT * FROM Orders where OrderID % 2 = 0; The MOD() function exists in Oracle, which is the source of your confusion.


2 Answers

To select even or odd IDs from a MySQL table, you would use the modulo operator (like in PHP):

SELECT * FROM table WHERE (id % 2) = 0; # even SELECT * FROM table WHERE (id % 2) > 0; # odd 
like image 140
Sam Avatar answered Sep 22 '22 02:09

Sam


In order to select even or odd IDs from a MySQL table, you would use the 'MOD', this easy way to select the Odd and Even numbers.

Select Odd number

select column_name from table_name where mod(column_name,2)=1;

Select Even number

select column_name from table_name where mod(column_name,2)=0;

if you need an Odd number, put 1.

if you need an Even number, put 0.

like image 37
Gunabalan.S Avatar answered Sep 23 '22 02:09

Gunabalan.S