Generate a Random Decimal Number between Two Values 

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 more specific random decimal number (i.e. one >= low value and < high value), we can easily create our own function for that purpose!

				
					CREATE OR REPLACE FUNCTION randomdec(low INT, high INT)
  RETURNS NUMERIC AS
$$
BEGIN
  RETURN random()*(high - low) + low;
  
END;
$$ language 'plpgsql' STRICT;
				
			

Example:

				
					yugabyte=> CREATE OR REPLACE FUNCTION randomdec(low INT, high INT)
yugabyte->   RETURNS NUMERIC AS
yugabyte-> $$
yugabyte$> BEGIN
yugabyte$>   RETURN random()*(high - low) + low;
yugabyte$>
yugabyte$> END;
yugabyte$> $$ language 'plpgsql' STRICT;
CREATE FUNCTION
				
			

Generate a random decimal number >= 0 and < 100:

				
					yugabyte=> SELECT randomdec(0, 100);
    randomdec
------------------
 40.6772271264344
(1 row)
				
			

Generate a random decimal number >= 1000 and < 5000:

				
					yugabyte=> SELECT randomdec(1000, 5000);
    randomdec
------------------
 4264.89903964102
(1 row)
				
			

Have Fun!

Siesta Key Beach - Sarasota, FL