How to select or update MySQL table rows by even or odd number field value

In this simple tutorial I will show to select or update rows in your mysql table based on a stored even or add number in a specific field of your table. Your result might look like this:

How to select or update MySQL table rows by even or odd number field value

For example you have a users table with a field name field_name.

Here is the method to do it. To select all rows whose specific field’s value is an even number:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
SELECT * FROM `users` where MOD(field_name, 2) = 0;
SELECT * FROM `users` where MOD(field_name, 2) = 0;
SELECT * FROM `users` where MOD(field_name, 2) = 0;

For testing with different status types I want to update my table field statud_id to either 1 or 0 based on even or odd value of field_name. To update all records field value of which is even:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
UPDATE `users` set `status_id` = 1 where MOD(field_name, 2) = 0;
UPDATE `users` set `status_id` = 1 where MOD(field_name, 2) = 0;
UPDATE `users` set `status_id` = 1 where MOD(field_name, 2) = 0;

To select all rows which has a field value an odd number:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
SELECT * FROM `users` where MOD(field_name, 2) <> 0;
SELECT * FROM `users` where MOD(field_name, 2) <> 0;
SELECT * FROM `users` where MOD(field_name, 2) <> 0;

To update all rows ID of which is odd:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
UPDATE `users` set `status_id` = 1 where MOD(field_name, 2) <> 0;
UPDATE `users` set `status_id` = 1 where MOD(field_name, 2) <> 0;
UPDATE `users` set `status_id` = 1 where MOD(field_name, 2) <> 0;

Similarly you apply different criteria to select or update records. For another example, to update records which are divisible by 3.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
UPDATE `users` set `status_id` = 1 where MOD(field_name, 3) = 0;
UPDATE `users` set `status_id` = 1 where MOD(field_name, 3) = 0;
UPDATE `users` set `status_id` = 1 where MOD(field_name, 3) = 0;

I hope this example to select or update MySQL table rows by even or odd number field value help you.

Leave a Reply