Generate Random Integers, Including Negative Numbers
[Deleted User]
Administrator
Jim Knicely authored this tip.
The RANDOMINT(n) function returns one of the n integers from 0 through n – 1. Those are all positive integers. What if I want to include negative integers? That’s easy with a simple multiplication.
Example:
dbadmin=> SELECT DECODE(randomint(2), 1, 1, -1) * randomint(11) "Random INT from -10 to 10"; Random INT from -10 to 10 --------------------------- -1 (1 row) dbadmin=> SELECT DECODE(randomint(2), 1, 1, -1) * randomint(11) "Random INT from -10 to 10"; Random INT from -10 to 10 --------------------------- 3 (1 row) dbadmin=> SELECT DECODE(randomint(2), 1, 1, -1) * randomint(11) "Random INT from -10 to 10"; Random INT from -10 to 10 --------------------------- -7 (1 row) dbadmin=> SELECT DECODE(randomint(2), 1, 1, -1) * randomint(11) "Random INT from -10 to 10"; Random INT from -10 to 10 --------------------------- 9 (1 row)
Have fun!
0