PostgreSQL - Random Number Generation
Last Updated :
16 Aug, 2024
When working with databases, there are times when you might need to generate random numbers for various use cases such as sampling data, testing, or creating unique values. PostgreSQL offers the built-in random() function, which returns a random number between 0 and 1. However, you can go beyond that by generating random numbers within a specific range or even creating a user-defined function (UDF) for more flexibility. This article will look into how to achieve this and provide practical examples.
PostgreSQL random() Function
The random() function in PostgreSQL generates a random floating-point number between 0 (inclusive) and 1 (exclusive). This can be particularly useful in a variety of scenarios.
Syntax:
Here's the basic syntax:
SELECT random();
If you try the above syntax it will lead to the following:

Generating Random Numbers Within a Range
To generate a random number between 1 and 10, you use the following statement:
SELECT random() * 10 + 1 AS RAND_1_10;
If you try the above syntax it will lead to the following:

If you want to generate the random number as an integer, you apply theĀ floor() function to the expression as follows:
SELECT floor(random() * 10 + 1)::int;
The above query results in the following:

The result will be an integer between 1 and 10.
Generating Random Numbers Between Two Custom Integers
Generally, to generate a random number between two integers l and h, you use the following statement:
SELECT floor(random() * (h-l+1) + l)::int;
For example, to generate a random number between 20 and 50:
SELECT floor(random() * (50 - 20 + 1) + 20)::int;
Creating a User-Defined Function for Random Numbers
To create a user-generated function that returns a random number between two numbers l and h:
CREATE OR REPLACE FUNCTION random_between(low INT ,high INT)
RETURNS INT AS
$$
BEGIN
RETURN floor(random()* (high-low + 1) + low);
END;
$$ LANGUAGE 'plpgsql' STRICT;
The following statement calls the random_between() function and returns a random number between 1 and 100:
SELECT random_between(1,100);
Output:

The output will be an integer between 1 and 100.
Generating Multiple Random Numbers
If you want to get multiple random numbers between two integers, you use the following statement.
SELECT random_between(1,100)
FROM generate_series(1,5);
Output:

This statement returns five random integers within the specified range.
Similar Reads
PostgreSQL - NUMERIC Data Type
In PostgreSQL, the NUMERIC data type is designed for high-precision number storage by making it ideal for financial and scientific applications where accuracy is critical. It supports a large number of digits both before and after the decimal point, minimizing rounding errors. Understanding the nuan
5 min read
PostgreSQL - MD5() Function
The PostgreSQL MD5() function is a useful tool for evaluating the MD5 hash of a given string and returning the result in hexadecimal form. This function is often used for data integrity checks and secure password storage. Let's look into the syntax, and usage of the MD5() function in PostgreSQL with
2 min read
PostgreSQL - Generate Columns
When working with databases, there are scenarios where you need a columnâs value to be automatically computed based on other columns. In PostgreSQL, this can be achieved through generated columns. These special columns are calculated based on an expression using other columns in the table. The value
3 min read
PostgreSQL - User Defined Functions
PostgreSQL, one of the most powerful open-source relational database management systems (RDBMS), provides a strong feature set for creating and utilizing user-defined functions (UDFs). By using user-defined functions, we can enhance the modularity, maintainability, and performance of our database ap
5 min read
How to Select Random Row in PostgreSQL?
Selecting random rows from a table in PostgreSQL can be a valuable feature for various applications, including data analysis, content generation, and gaming scenarios. PostgreSQL offers straightforward methods to achieve this, primarily through the RANDOM() function and the ORDER BY RANDOM() clause.
4 min read
Introduction to PostgreSQL PL/pgSQL
PostgreSQL is an open-source, strong and highly extensible object-relational database system. It combines the power of SQL with additional procedural features, making it ideal for handling complex workloads. In PostgreSQL, PL/pgSQL (Procedural Language/PostgreSQL) enhances the SQL functionality by e
4 min read
PostgreSQL - INTEGER Data Type
In PostgreSQL, the INTEGER data type is widely used for storing numerical data efficiently. It is a 4-byte data type that allows us to store whole numbers within a specified range, making it ideal for various use cases like population counts, active user statistics, and more.In this article, we will
4 min read
PostgreSQL - CREATE SEQUENCE
In database management, generating unique identifiers is vital for data integrity, and PostgreSQL provides a powerful feature called CREATE SEQUENCE to solve this. This command allows developers to create a sequence that automatically generates unique numeric values. In this article, we will explore
4 min read
PostgreSQL - FORMAT Function
The PostgreSQL format() function is a powerful tool for string formatting by allowing developers to insert variables into strings using format specifiers like %s, %I, and %L. This function is especially useful for building dynamic SQL queries and ensuring proper formatting of identifiers. It simplif
3 min read
How to Reset Auto Increment Counter in PostgreSQL?
PostgreSQL is a powerful, open-source, object-relational database management system (DBMS) developed by a vibrant community. One common requirement for database administrators is resetting the auto-increment counter for primary key sequences. In PostgreSQL, this process is crucial for ensuring the o
4 min read