Random number functions - Amazon Athena
Services or capabilities described in AWS documentation might vary by Region. To see the differences applicable to the AWS European Sovereign Cloud Region, see the AWS European Sovereign Cloud User Guide.

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 n - 1, use CAST(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

true

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

true

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

3

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(n) returns a random integer from 0 to n - 1, and random(m, n) returns one from m to n - 1. In DuckDB, random takes no arguments, so these calls fail. To get the same kind of result, use CAST(floor(random() * n) AS BIGINT), or m + CAST(floor(random() * (n - m)) AS BIGINT).