Skip to Content
MySQL Cookbook, 2nd Edition
book

MySQL Cookbook, 2nd Edition

by Paul DuBois
November 2006
Intermediate to advanced
977 pages
30h 42m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook, 2nd Edition

Generating Random Numbers

Problem

You need a source of random numbers.

Solution

Invoke MySQL’s RAND() function.

Discussion

MySQL has a RAND() function that produces random numbers between 0 and 1:

mysql>SELECT RAND(), RAND(), RAND();
+------------------+--------------------+------------------+
| RAND()           | RAND()             | RAND()           |
+------------------+--------------------+------------------+
| 0.18768198246852 | 0.0052350517411111 | 0.46312934203365 |
+------------------+--------------------+------------------+

When invoked with an integer argument, RAND() uses that value to seed the random number generator. You can use this feature to produce a repeatable series of numbers for a column of a query result. The following example shows that RAND() without an argument produces a different column of values per query, whereas RAND( N ) produces a repeatable column:

mysql>SELECT i, RAND(), RAND(10), RAND(20) FROM t;
+------+------------------+------------------+------------------+
| i    | RAND()           | RAND(10)         | RAND(20)         |
+------+------------------+------------------+------------------+
|    1 | 0.60170396939079 | 0.65705152196535 | 0.15888261251047 |
|    2 | 0.10435410784963 | 0.12820613023658 | 0.63553050033332 |
|    3 | 0.71665866180943 | 0.66987611602049 | 0.70100469486881 |
|    4 | 0.27023101623192 | 0.96476222012636 | 0.59843200407776 |
+------+------------------+------------------+------------------+
mysql> SELECT i, RAND(), RAND(10), RAND(20) FROM t; +------+------------------+------------------+------------------+ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Cookbook, 3rd Edition

MySQL Cookbook, 3rd Edition

Paul DuBois
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
MySQL Cookbook

MySQL Cookbook

Paul DuBois
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal

Publisher Resources

ISBN: 059652708XSupplemental ContentErrata Page