MySQL RAND() Function

In MySQL, the RAND() function returns a random decimal value with a positive sign, greater than or equal to 0.0 and less than 1.0.

RAND() Syntax

Here is the syntax of MySQL RAND() function:

RAND()
RAND(seed)

Parameters

seed
Optional. A seed for generating random numbers. If provided it, the RAND(seed) function will generate a repeatable sequence of random numbers.

Return value

In MySQL, the RAND() function returns a random decimal value with a positive sign, greater than or equal to 0.0 and less than 1.0.

RAND() Examples

RAND() returns a random decimal between 0 and 1. If you want to return random numbers in other range (such as m and n), please use the following formulas:

  • A random number between m and n: RAND() * (n - m) + m
  • A random integer between m and n: FLOOR(RAND() * (n - m + 1) + m)

Get a random number between 0 and 1

SELECT
    RAND(),
    RAND(),
    RAND(),
    RAND()\G

output

*************************** 1\. row ***************************
RAND(): 0.45966783674402895
RAND(): 0.011888444434747514
RAND(): 0.6804387426752958
RAND(): 0.3665284108058814

Get a random number between 10 and 20

SELECT
    RAND() * (20 - 10) + 10,
    RAND() * (20 - 10) + 10,
    RAND() * (20 - 10) + 10,
    RAND() * (20 - 10) + 10\G

output

*************************** 1\. row ***************************
RAND() * (20 - 10) + 10: 12.783272138594903
RAND() * (20 - 10) + 10: 17.496861179821995
RAND() * (20 - 10) + 10: 19.134489790661718
RAND() * (20 - 10) + 10: 13.181865721179047

Get a random integer between 10 and 20

SELECT
    FLOOR(RAND() * (20 - 10 + 1) + 10),
    FLOOR(RAND() * (20 - 10 + 1) + 10),
    FLOOR(RAND() * (20 - 10 + 1) + 10),
    FLOOR(RAND() * (20 - 10 + 1) + 10)\G

output

*************************** 1\. row ***************************
FLOOR(RAND() * (20 - 10) + 10): 20
FLOOR(RAND() * (20 - 10) + 10): 13
FLOOR(RAND() * (20 - 10) + 10): 15
FLOOR(RAND() * (20 - 10) + 10): 16