PostgreSQL: Select a Random Number in a Range (Between Two Numbers) - Comment Page: 1

This is quick tip howto select a random number in a range. Example random number between 1-100 (>= 1 and < 100). This is actually very easy job with PostgreSQL own 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? ------------------ ...

2 comments on “PostgreSQL: Select a Random Number in a Range (Between Two Numbers) - Comment Page: 1

    1. Really helpful…Thanks! :)

      Reply
    2. Nice one!
      But why MAX is 999 while MIN is 100, that is the range is [100, 999)
      You can make it inclusive [100, 1000] by using

      select max(trunc((100 + random()* (700-99)))) from generate_series(1, 100000);

      generally
      select max(trunc((start + random()* (end- (start – 1))))) from generate_series(1, 100000);

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close