"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to generate random values ​​in range in MySQL?

How to generate random values ​​in range in MySQL?

Posted on 2025-04-12
Browse:282

How to Generate Random Values Within a Range in MySQL?

Obtaining a Random Value Within a Range in MySQL

Introduction

When working with MySQL, there may be instances where you need to generate a random value that falls within a specified range. While the RAND() function exists, it does not fulfill this requirement. This article delves into the best approach for achieving this in MySQL.

Solution:

The optimal method in MySQL to generate a random value within a specified range is:

ROUND((RAND() * (max-min)) min)
  • RAND(): Generates a random number between 0 and 1.
  • max: Maximum value of the desired range.
  • min: Minimum value of the desired range.

This formula multiplies RAND() by the difference between max and min, adding min to the result. ROUND() is applied to obtain an integer value.

Comparison with PHP Implementation:

The PHP equivalent of the MySQL solution is:

rand($min, $max)

However, benchmarks have shown that the MySQL solution is slightly faster when dealing with a large number of values. The choice between PHP and MySQL depends on the number of rows being processed and whether only the random value is needed or additional columns will be returned.

Example Query

To obtain a random value between 10 and 200:

SELECT ROUND((RAND() * (200-10)) 10) AS `foo`

Addendum: Performance Comparison

To further illustrate the performance differences, the following PHP script was run:

// MySQL
$start = microtime(1);
for( $i = 0; $i 

The results show that MySQL is faster for generating random values if only the random value is needed, but slower if additional columns are returned.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3