SQLite | SQLite Functions | Generating Random Numbers (random Function)
The random function generates random numbers. This article explains how to use it.
Using the random Function
The random function generates a random number. Its syntax is as follows.
random()
It returns a random integer between -9223372036854775808 and +9223372036854775807.
To use only positive values, obtain the absolute value with Calculating an Absolute Value (abs Function). To generate a random number within a particular range, use the % operator.
–
As an example, use the random function to generate random numbers from -9 through 9 and from 0 through 9.
select random() % 10, abs(random()) % 10;
sqlite> select random() % 10, abs(random()) % 10;
random() % 10 abs(random()) % 10
------------- ------------------
8 1
sqlite> select random() % 10, abs(random()) % 10;
random() % 10 abs(random()) % 10
------------- ------------------
-1 7
sqlite> select random() % 10, abs(random()) % 10;
random() % 10 abs(random()) % 10
------------- ------------------
-7 9
sqlite> select random() % 10, abs(random()) % 10;
random() % 10 abs(random()) % 10
------------- ------------------
6 3
sqlite>
Each execution of the SELECT statement displayed a random number from -9 through 9 and another from 0 through 9.