Skip to content

RAND()

Function Description

The RAND() function is used to generate a random number of type Float64 between 0 and 1. It accepts no parameters and each call produces an unpredictable and non-repetitive random number.

If you need to randomly select data from the table, you can use the RAND() function to generate a random number. You can sort the data in the table using ORDER BY according to this random number. For example:

-- Get all data randomly from the table and sort it in random order. The order of each query result may be different.
SELECT * FROM table ORDER BY RAND();

Function Syntax

> RAND([seed])

Parameter definition

Parameters Description
seed Optional parameters. Is an integer value that specifies the seed value when generating a random number. If the seed parameter is not specified, the current time is the seed value by default. The return value type is consistent with the input type.
MatrixOne does not support the specified seed value.

Example

  • Example 1
mysql> SELECT RAND();
+--------------------------+
| rand() |
+--------------------------+
| 0.25193285156620004 |
+--------------------------+
1 row in set (0.00 sec)
  • Example 2
CREATE TABLE Users (
    ID INT PRIMARY KEY AUTO_INCREMENT,
    UserName VARCHAR(255) NOT NULL,
    Email VARCHAR(255));

INSERT INTO Users (UserName, Email) VALUES
    ('John', 'john@example.com'),
    ('Jane', 'jane@example.com'),
    ('Alice', 'alice@example.com'),
    ('Bob', 'bob@example.com');

-- Randomly select a user's information from the Users table
mysql> SELECT * FROM Users ORDER BY RAND() LIMIT 1;
+------+--------------------------------------------+
| id | username | email |
+------+--------------------------------------------+
| 4 | Bob | bob@example.com | -- Bob's information is randomly selected
+------+--------------------------------------------+
1 row in set (0.01 sec)

-- Execute the above query again, and the selected user may be another user
mysql> SELECT * FROM Users ORDER BY RAND() LIMIT 1;
+------+-----------------------------------------------------------------------------------------------------------------------
| id | username | email |
+------+-----------------------------------------------------------------------------------------------------------------------
| 3 | Alice | alice@example.com | -- Alice's information is randomly selected
+------+-----------------------------------------------------------------------------------------------------------------------
1 row in set (0.01 sec)

limit

MatrixOne does not currently support specifying the seed value of the RAND(seed) function (i.e. the seed parameter).