RAND()

Description

The RAND() function is used to generate a Float64 type random number between 0 and 1. It does not accept any arguments and generates a random number that is unpredictable and non-repeating each time it is called.

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

  1. -- Randomly retrieve all data from the table and sort it in a random order, the order of the query results may differ each time.
  2. SELECT * FROM table ORDER BY RAND();

Syntax

  1. > RAND([seed])

Arguments

ArgumentsDescription
seedOptional argument. It is an integer value used to specify the seed when generating random numbers. If the seed parameter is not specified, the current time is used as the seed value by default. The return value type is consistent with the input type.
MatrixOne does not currently support specifying seed.

Examples

  • Example 1
  1. mysql> SELECT RAND();
  2. +---------------------+
  3. | rand() |
  4. +---------------------+
  5. | 0.25193285156620004 |
  6. +---------------------+
  7. 1 row in set (0.00 sec)
  • Example 2
  1. CREATE TABLE Users (
  2. ID INT PRIMARY KEY AUTO_INCREMENT,
  3. UserName VARCHAR(255) NOT NULL,
  4. Email VARCHAR(255));
  5. INSERT INTO Users (UserName, Email) VALUES
  6. ('John', 'john@example.com'),
  7. ('Jane', 'jane@example.com'),
  8. ('Alice', 'alice@example.com'),
  9. ('Bob', 'bob@example.com');
  10. -- Select a user's information randomly from the Users table.
  11. mysql> SELECT * FROM Users ORDER BY RAND() LIMIT 1;
  12. +------+----------+-----------------+
  13. | id | username | email |
  14. +------+----------+-----------------+
  15. | 4 | Bob | bob@example.com | -- Bob's information is randomly selected.
  16. +------+----------+-----------------+
  17. 1 row in set (0.01 sec)
  18. -- Execute the above query again, and another user may be selected.
  19. mysql> SELECT * FROM Users ORDER BY RAND() LIMIT 1;
  20. +------+----------+-------------------+
  21. | id | username | email |
  22. +------+----------+-------------------+
  23. | 3 | Alice | alice@example.com | -- Alice's information is randomly selected.
  24. +------+----------+-------------------+
  25. 1 row in set (0.01 sec)

Constraints

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