Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

postgresql
communitycreator
random

How to generate random numbers in postgreSQL

Ravi

Overview

The random() function of postgreSQL is used to return a random number between 0 and 1. This function can be used to generate a random number within a range.

Syntax

random()

Parameters

This function doesn’t take any parameters.

Example 1

select random() as random_number;
Random number between 0 and 1

Example 2

To generate a random number between two integers, the following SQL can be used.

We’re assuming the integer range to be low and high where low indicates the lowest possible integer and high indicates the highest possible integer in the range.

SELECT floor(random() * (high - low + 1) + low)::int;

Example 3

SELECT floor(random() * (1000 - 1 + 1) + 1)::int as random_number;
Random number between 1 and 1000.

In the code above, we generate a random integer between 1 and 1000 where 1 is low and 1000 is high.

RELATED TAGS

postgresql
communitycreator
random
RELATED COURSES

View all Courses

Keep Exploring