Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating only positive random numbers in SQLite

Tags:

random

sqlite

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 ?

like image 378
Fischer Avatar asked Nov 29 '11 00:11

Fischer


People also ask

How do you generate a random number between 1 and 10 in SQL?

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.

How do I select a random number in SQL query?

SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

How do you generate new random values for each row?

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.


2 Answers

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.

like image 158
NullUserException Avatar answered Sep 23 '22 03:09

NullUserException


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.

like image 27
Sanju Avatar answered Sep 21 '22 03:09

Sanju