How to use RANDOM() Function with OFFSET and LIMIT In SQL

In PostgreSQL, the RANDOM() function produces a random number between 0 and 1. Selecting a random selection of rows from a table is the main goal of using RANDOM() with OFFSET and LIMIT in a PostgreSQL query.

Syntax:

SELECT * FROM your_table
OFFSET floor(RANDOM() * (SELECT COUNT(*) FROM your_table))
LIMIT value;

Explanation:

  • 1) ‘your_table’: Replace this with the actual name of your table.
  • 2) ‘RANDOM()’: This function generates a random value between 0 and 1.
  • 3) ‘floor(random() * (SELECT COUNT(*) FROM your_table))’: This section produces a random offset by using floor() to round down after multiplying the number of rows in your table by a random amount. This aids in choosing a random starting place for the table.
  • 4) LIMIT value: change the LIMIT value to get the desired amount of random rows.

Example:

SELECT * FROM example_table 
OFFSET floor(random() * (SELECT COUNT(*)
FROM example_table)) LIMIT 5;

Output:

Output

Explanation: The query mentioned above selects 5 random rows from the example_table, starting from a dynamically determined offset within the table.

How to Select Random Row in PostgreSQL?

In PostgreSQL, selecting a random row from a table can be a useful feature in scenarios such as sampling data for analysis or displaying random content. PostgreSQL provides several techniques to achieve this, including using the RANDOM() function or the ORDER BY RANDOM() clause. In this article, we will explore these methods and demonstrate how to select a random row from a table in PostgreSQL along with examples.

Similar Reads

How to SELECT random rows?

In PostgreSQL, the SELECT statement is used to retrieve data from one or more tables in the database. It allows us to specify which columns to retrieve, as well as any filtering, sorting, or grouping criteria to apply to the data. Also, Selecting Random Row in PostgreSQL is achieved through the below method are as follow:...

1. Using ORDER BY with RANDOM() Function

In PostgreSQL, the RANDOM() function produces a random number between 0 and 1. It can be used to choose random rows by shuffle the result set when paired with ORDER BY....

2. Using RANDOM() Function with OFFSET and LIMIT

In PostgreSQL, the RANDOM() function produces a random number between 0 and 1. Selecting a random selection of rows from a table is the main goal of using RANDOM() with OFFSET and LIMIT in a PostgreSQL query....

Conclusion

In Conclusion, Use the RANDOM() method with the ORDER BY clause to retrieve random rows from a database table. Using PostgreSQL’s OFFSET and LIMIT clauses with the RANDOM() functions offers a dependable and adaptable method for choosing random rows from a table. Additionally, we can indicate the maximum number of rows we wish to collect or fetch. This article has covered the use of the RANDOM() method to extract random rows from a table, complete with real-world applications....