Random number functions
Use this function to generate a pseudo-random number that is at least 0 and less than 1, for example to shuffle rows or to pick rows at random. The function returns a new value on every call, so its results vary from one query to the next.
random function
Returns a pseudo-random DOUBLE value that is greater than or equal to 0 and less than 1. The function takes no arguments. Each call returns a new value, so every row gets its own value, and two calls in the same row return two different values.
To get a random whole number from 0 to , use n - 1CAST(floor(random() * .n) AS BIGINT)
Syntax
random()
Return type
DOUBLE
Examples
The following SQL query shows that the result is at least 0 and less than 1. The value varies from run to run, so the query tests its range instead of showing it.
SELECT r >= 0 AND r < 1 AS in_range FROM (SELECT random() AS r)
The query returns the following result.
| in_range |
|---|
|
The following SQL query builds a random whole number from 1 to 6, like the roll of a die, and checks that it is in that range.
SELECT CAST(floor(random() * 6) AS INTEGER) + 1 BETWEEN 1 AND 6 AS in_range
The query returns the following result.
| in_range |
|---|
|
The following SQL query shows that each row gets its own value. The three rows return three different values.
SELECT count(DISTINCT r) AS distinct_values FROM ( SELECT random() AS r FROM (VALUES (1), (2), (3) ) AS v(x) )
The query returns the following result.
| distinct_values |
|---|
|
Considerations
The result varies from run to run. To use the same random value more than once in a row, select it once in a subquery and refer to its column. Writing random() twice gives two different values.
Differences from Athena engine version 3
Athena engine version 3 also accepts rand() as another name for random(). DuckDB has no rand function, so use random().
In Athena engine version 3, random( returns a random integer from n)0 to , and n - 1random( returns one from m, n) to m. In DuckDB, n - 1random takes no arguments, so these calls fail. To get the same kind of result, use CAST(floor(random() * , or n) AS BIGINT).m + CAST(floor(random() * (n - m)) AS BIGINT)