MySQL random function

db, development, mysql Add comments

MySQL RAND() function returns values between 0 and 1. At times you need a random value between A and B, then you can use this function:

DELIMITER //
DROP  FUNCTION IF EXISTS RANDOM;//
CREATE FUNCTION RANDOM(minimum INT, maximum INT)
    RETURNS INT NO SQL NOT DETERMINISTIC
    COMMENT 'integer random value in the bounds given'
RETURN minimum + 
  ROUND(1000000 * RAND() % (maximum-minimum) );//
DELIMITER ;

You can call it like this to get a random integer value between 0 and 100:

SELECT RANDOM(0, 100);

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in