Division remainder or modulo operator in MySQL

There is no proper modulo operator in MySQL, instead you have to use an arithmetic function called MOD.

MOD receives two parameters and returns the remainder of the division of the first by the second. For example, this statement selects all users that have an even identifier:

select * from user WHERE MOD (user_id, 2)=0

However, this function can be called in other ways, as if it were an operator.

For example, this statement updates the level field of all users with even identifier:

update user set level=2 WHERE (id_user % 2)=0

As of MySQL 4, the MOD operator can be used instead of %. For example, this statement selects all user identifiers and the remainder of the division between that identifier and 2.

select user_id, user_id mod 2 from user

See also  How and why to learn programming with Javascript
Loading Facebook Comments ...
Loading Disqus Comments ...