Generate a Random Integer

In YSQL there is the familiar built-in function named RANDOM which generates a random value between 0 (inclusive) and 1 (exclusive).

Although there isn’t a built-in function to generate a random integer, we can easily create our own function for that purpose!

				
					CREATE OR REPLACE FUNCTION randomint(low INT, high INT)
  RETURNS INT AS
$$
  SELECT (floor(random() * (high - low + 1) + low))::INT;
$$ LANGUAGE 'sql';
				
			

Example:

				
					yugabyte=> SELECT random();

      random
-------------------
 0.604278428480029
(1 row)
				
			
				
					yugabyte=# CREATE OR REPLACE FUNCTION randomint(low INT, high INT)
yugabyte-#   RETURNS INT AS
yugabyte-# $$
yugabyte$#   SELECT (floor(random() * (high - low + 1) + low))::INT;
yugabyte$# $$ LANGUAGE 'sql';
CREATE FUNCTION

yugabyte=# SELECT randomint(10, 1000);
 randomint
-----------
       617
(1 row)

yugabyte=# SELECT randomint(10, 1000);
 randomint
-----------
       365
(1 row)
				
			

Have Fun!