PostgreSQL: Select a Random Number in a Range (Between Two Numbers)
This is quick tip howto select a random number in a range. Example random number between 1-100 (>= 1 and random() function, which returns random value between 0-1. Following example selects 5 random values using generate_series() function:
SELECT random() FROM generate_series(1,5);
random
-------------------
0.595817462075502
0.350072300527245
0.989073566626757
0.700899163261056
0.940509075298905
(5 rows)
Next thing to todo is convert random function values to real float values in a range 1-100:
SELECT random() * 99 + 1 FROM generate_series(1,5);
?column?
------------------
45.0829070857726
96.3123500789516
30.1867960244417
63.0484761050902
44.2645903658122
(5 rows)
And finally truncate floats to integers with trunc function:
SELECT trunc(random() * 99 + 1) FROM generate_series(1,5);
trunc
-------
21
6
2
57
58
(5 rows)
Then this select is easy to convert simple function to get random numbers between two values:
CREATE OR REPLACE FUNCTION get_random_number(INTEGER, INTEGER) RETURNS INTEGER AS $$
DECLARE
start_int ALIAS FOR $1;
end_int ALIAS FOR $2;
BEGIN
RETURN trunc(random() * (end_int-start_int) + start_int);
END;
$$ LANGUAGE 'plpgsql' STRICT;
Function usage:
SELECT get_random_number(1, 100);
get_random_number
-------------------
11
(1 row)
SELECT get_random_number(45, 46);
get_random_number
-------------------
45
(1 row)
SELECT get_random_number(300, 400);
get_random_number
-------------------
372
(1 row)
SELECT min(get_random_number(100, 1000)), max(get_random_number(100, 1000)) FROM generate_series(1,100000);
min | max
-----+-----
100 | 999
(1 row)