Generating only positive random numbers in SQLite Generating only positive random numbers in SQLite sqlite sqlite

Generating only positive random numbers in SQLite


Use the ABS() (absolute value) function:

SELECT ABS(RANDOM() % N)

Note that:

If X is the integer -9223372036854775808 then abs(X) throws an integer overflow error since there is no equivalent positive 64-bit two's complement value.


For generating positive(including zero) random number with only upper bound, use

SELECT ABS(RANDOM() % N)

For generating positive and non-zero random number, use

SELECT ABS(RANDOM()) % (HIGH - LOW) + LOW

HIGH - represents upper bound

LOW - represents lower bound.


Your method random() % n for getting a random number within a certain range is flawed, as it will give an uneven distribution. The number zero will come up twice as often as any other number.

Incidentally, using ABS to make the numbers positive is flawed in the exact opposite way, making the number zero turn up half as often as any other number, so they cancel each other out.

abs(random() % n)