In this PostgreSQL post explains how to use the PostgreSQL random function with syntax and examples.
The PostgreSQL random function can be used to return a random number or a random number within a range.
The syntax for the random function in PostgreSQL is:
There are no parameters or arguments for the random function.
To create a random decimal number between two values (range), you can use the following formula:
Where a is the smallest number and b is the largest number that you want to generate a random number for.
The formula above would generate a random decimal number >= 10 and 25. (Note: this formula will never return a value of 25 because the random function will never return 1.)
To create a random integer number between two values (inclusive range), you can use the following formula:
Where a is the smallest number and b is the largest number that you want to generate a random number for.
The formula above would generate a random integer number between 10 and 25, inclusive.
The random function can be used in the following versions of PostgreSQL:
Let's explore how to use the random function in PostgreSQL to generate a random number >= 0 and 1.
For example:
Although the random function will return a value of 0, it will never return a value of 1. It will always return a value smaller than 1.
Let's explore how to use the random function in PostgreSQL to generate a random decimal number between two numbers (ie: range).
For example, the following would generate a random decimal value that is >= 1 and 10 (Note: it will never return a value of 10):
The following example would generate a random decimal value >= 25 and 40 (Note: it will never return a value of 40):
Let's explore how to use the random function in PostgreSQL to generate a random integer number between two numbers (ie: inclusive range).
For example, the following would generate a random integer value between 1 and 10:
The following example would generate a random integer value between 25 and 40: