RANDOM

RANDOM in SQL is a function that generates a floating-point pseudorandom number in the range 0 <= x < 1.0. It is used when random, non-repetitive data is needed. Since the data generated is pseudorandom, it should not be used for cryptographic purposes.

Example

CREATE TABLE numbers (num INTEGER);
INSERT INTO numbers (num)
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
SELECT *
FROM numbers
ORDER BY RANDOM()
LIMIT 1;

Output

num
---
4

Explanation

In the example provided, a table named ‘numbers’ is being created and populated with integers 1 through 10. The ‘SELECT’ statement is being used to retrieve all records from this table. The ‘ORDER BY RANDOM()’ function randomizes the order of the records, and the ‘LIMIT 1’ clause picks just one record from this random output, effectively picking a random number from 1 to 10. The output shown is an example where ‘4’ was the randomly selected number.

Example

SELECT RANDOM() as RNG;

Output

RNG
-------------------
0.758550199121237

Explanation

In the given example, the RANDOM() function is used, which generates a random number greater than or equal to 0 and less than 1. The number is generated each time the function is called. The generated random number is then aliased as ‘RNG’.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.