rand()
The rand() function returns a random integer that is greater than or equal to 0 and less than a specified bound.
Syntax
rand(BOUND[, SEED])
Parameters
BOUND- A positive integer specifying the upper bound of the return value. Must be greater than 0. The function returns an integer in the range [0, BOUND).
SEED- The seed value for the random number generator. When specified, the same seed always produces the same sequence of values. Use this when you need to validate query behavior or produce reproducible results.
Description
The rand() function uses Java's Random class to return a random integer in the range [0, BOUND).
BOUND must be a positive integer. Specifying a non-integer or negative value raises an error at query parse time. SEED must be an integer; specifying a non-integer raises an error at parse time.
If BOUND is specified as a dynamic expression, and the value at runtime is not a positive integer, null is returned.
Caution
When `SEED` is specified, the function always returns the same sequence of values. Do not use this function for security-sensitive random number generation.
Error codes
| Error code | Description |
|---|---|
| 90750 | An invalid BOUND value was specified. |
| 90751 | A value of 0 or less was specified for BOUND. |
| 90752 | A non-integer value was specified for SEED. |
Usage examples
-
Generate a random integer in the range 0–999
json "{}" | eval r = rand(1000) | # r: (a random integer in the range [0, 1000)) -
Generate a reproducible value by specifying a seed
json "{}" | eval r = rand(1000, 42) | # r: (a random integer in the range [0, 1000)) -
Specify
BOUNDas a dynamic expressionjson "{'n': 100}" | eval r = rand(n) | # r: (a random integer in the range [0, 100))
Compatibility
The rand() function has been available since before Sonar 4.0.