In SQLite
The
random()
function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807.
You can get an random with maximum value n with Select random() % n ;
But that still generates negative numbers. How can I generate only positive random numbers in SQLite ?
SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.
SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).
In many cases, we require to generate a unique but a random number ID for each row of the table. We can generate a random number, using the NEWID() function of SQL Server. Random number generated by NEWID() method will be a 32 byte Hexadecimal number, which is unique for your whole system.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With