How to Select Random Record From Table in PL/SQL?
Last Updated :
03 Nov, 2024
In Oracle PL/SQL, selecting random records from a table is a common yet essential operation, used for a variety of purposes like data sampling, random selection for testing, or picking winners in contests.
In this article, we will explore different methods to select random records from a table in PL/SQL, Oracle's procedural language extension for SQL. By the end of this article, you will understand how to use different approaches to achieve this task effectively.
Methods to Select Random Records in Oracle PL/SQL
When working with large datasets, selecting random records can be challenging due to the need for efficient and reliable methods. We will select random records from the table in PL/SQL using the below method are as follow:
Setting Up the Environment for Random Record Selection
To understand How to select random records from a table in PL/SQL we need a table on which we will perform various operations and queries. Here we will consider a table called test which contains id, val1 and val2 as Columns.
Query:
PL/SQL
CREATE TABLE test
(
id INT PRIMARY KEY,
val1 VARCHAR(20),
val2 VARCHAR(20)
);
tablesfoo', 'zoo');
INSERT INTO test VALUES (2, 'bar', 'cage');
INSERT INTO test VALUES (3, 'tmp', 'jungle');
INSERT INTO test VALUES (4, 'cnt', 'pet');
INSERT INTO test VALUES (5, 'ctr', 'eat');
SELECT * FROM test;
Output:
test tableExplanation: Our table has been created.
Method 1: Using DBMS_RANDOM Package
The DBMS_RANDOM package provides random generation capabilities. It has several functions but we are going to make use of the RANDOM function from the package.
The RANDOM function generates integers in the range [-2^31, 2^^31).
Syntax:
DBMS_RANDOM.RANDOM
Example: Selecting a Single Random Record
The following query uses the RANDOM function
Query:
SELECT DBMS_RANDOM.RANDOM FROM DUAL;
Output:
Random valueExplanation: In this above query, DBMS_RANDOM.RANDOM
is used to generate a random number between 0 and 1. FROM
DUAL
is a special construct in Oracle used to select a single row from a dummy table. The query returns a single random number.
We can use the DBMS_RANDOM.RANDOM function to select a random record from the table. We will make use of the function in the ORDER BY clause and then use row_number to filter the records. The following query implements the above logic.
Query:
SELECT * FROM (
SELECT * FROM test
ORDER BY DBMS_RANDOM.RANDOM
)
WHERE rownum<2;
Output:
OutputExplanation: In the above query, we have selects a single random record from the test
table. It does this by first ordering the records randomly using DBMS_RANDOM
.
RANDOM
in the inner query and then limiting the result to one row using rownum<2
in the outer query.
Method 2: Using SAMPLE Clause
Oracle’s SAMPLE clause is a simpler way to retrieve random rows. It allows you to specify a percentage of rows to retrieve from the table. The sampling is performed on disk blocks, so it’s efficient even on large datasets.
Syntax:
SELECT cols FROM table SAMPLE(percentage)
....
Explanation:
- cols: The columns to select.
- percentage: The percentage of records to sample.
Example: Sampling 50% of the Records
The following query samples 50% record from the table
Query:
SELECT * FROM test SAMPLE(50);
Output:
Sampled dataExplanation: In the above query, we selects approximately 50% of the rows from the "test" table using the SAMPLE
clause. The SAMPLE
clause is used to sample a percentage of rows from a table.
We can make use of the sample clause to first sample some amount of data from the table and then later use the row_number to filter out just the specified number of records as we did in method 1.
Query:
SELECT * FROM test SAMPLE(40)
WHERE rownum<2;
Output:
OutputExplanation: In the above query, first samples approximately 40% of the rows from the "test" table using the SAMPLE
clause. Then, it filters the result to return only the first row using the rownum<2
condition. Here, we sampled 40% of the data from the table.
Advanced Example: Selecting Lottery Winners
Let's create the table and insert some data inside it. The following query creates a lottery table and inserts three records in it.
Query:
PL/SQL
CREATE TABLE lottery(
id INT PRIMARY KEY,
name VARCHAR(20),
age INT
);
INSERT INTO lottery VALUES (1, 'Aayush', 90);
INSERT INTO lottery VALUES (2, 'Sid', 22);
INSERT INTO lottery VALUES (3, 'Ronnie', 24);
INSERT INTO lottery VALUES (4, 'Ankit', 44);
INSERT INTO lottery VALUES (5, 'Yash', 19);
INSERT INTO lottery VALUES (6, 'Yuvraj', 50);
INSERT INTO lottery VALUES (7, 'Utkarsh', 20);
INSERT INTO lottery VALUES (8, 'Satyam', 32);
INSERT INTO lottery VALUES (9, 'Shashwat', 22);
INSERT INTO lottery VALUES (10, 'Akash', 17);
INSERT INTO lottery VALUES (11, 'Aswat', 45);
INSERT INTO lottery VALUES (12, 'Dhruv', 60);
Output:
Initial lottery dataExplanation: Our table has been created.
Now suppose that we now need to select two lottery winners. We can implement some complex logic for this or we could just simply select two records at random from the table. We will look at both the methods to implement this just for completion sense.
Query:
SELECT * FROM (
SELECT * FROM lottery
ORDER BY DBMS_RANDOM.RANDOM
)
WHERE rownum<3;
Output:
OutputExplanation: In the above query, we selects two random records from the "lottery" table. It first orders the table randomly using DBMS_RANDOM
.
RANDOM
in the inner query and then limits the output to the first two rows using rownum<3
in the outer query.
Query:
SELECT * FROM lottery SAMPLE(50)
WHERE rownum<3;
Output:
OutputExplanation: In the above query, it selects a random 50% sample of records from the "lottery" table and then limits the output to the first two rows using rownum<3
.
Key Points and Considerations
- The SAMPLE clause may not provide exact control over the number of rows, especially for smaller tables. Use DBMS_RANDOM.RANDOM for precise control.
- DBMS_RANDOM.RANDOM can be slower for large datasets because it requires sorting. The SAMPLE clause is more efficient for big tables.
- For testing purposes, try using different sample percentages or ROWNUM limits to observe results.
Conclusion
Overall, After reading this article now you have good understanding of How to select random record from table in PL/SQL. In this article, we saw two different methods to randomly select records from a table. First we saw DBMS_RANDOM.RANDOM function and then later made use of SAMPLE clause of SELECT statement to select random records. Finally, we went through a technical example to solidify our understanding of the concepts.
Similar Reads
How to SELECT FROM Stored Procedure in SQL
Stored procedures are precompiled SQL queries stored in the database that encapsulate logic and can accept parameters, perform operations and return results. They are widely used in SQL for encapsulating reusable logic, improving performance and enhancing security. In this article, weâll explore how
4 min read
How to Select Random Row in MySQL
In database operations, selecting random rows from a table is a common requirement for various applications, such as gaming, content recommendation, and statistical sampling. In this article, we learn different methods for selecting random rows in MySQL. We'll understand various approaches, includin
5 min read
How to Retrieve Data from Multiple Tables in PL/SQL
PL/SQL is âProcedural Language extensions to the Structured Query Languageâ. SQL is a popular language for both querying and updating data in relational database management systems (RDBMS). PL/SQL adds many procedural constructs to SQL language to overcome some limitations of SQL. In addition, PL/SQ
5 min read
How to Select Random Rows from a Matrix in MATLAB?
A matrix is an n x n array that stores integers, floating point numbers or alphanumeric data in MATLAB. Indexing a matrix is the same as indexing an array.  Syntax:matrix_name(i,j)where, i is the row number, and  J is the column number which is to be indexed. Example 1: [GFGTABS] Matlab % MATLAB co
2 min read
How to Repeat a Random Sample in R
In statistical analysis and data science, it is often important to understand the behavior of a dataset by taking random samples. Repeating a random sample allows researchers to observe how consistent their results are across different iterations. In R, this can be achieved using various functions.
4 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
How to Select the Top 10 Rows From a Table in MariaDB
In the data managing systems, MariaDB stands as a robust and adaptable MariaDB stands as a robust and adaptable choice in data managing systems. It's known for efficiently retrieving data with lots of tools and instructions. We're looking at the SELECT TOP clause, a key part of fetching data from
5 min read
How to Request a Random Row in SQLite?
SQLite is a database engine that provides a relational database management system and is a C language library with features like self-contained, serverless, and high reliability. SQLite is different from other traditional SQL database engines like MySQL, Oracle, PostgreSQL, etc. Traditional database
4 min read
How to Select 10 Random Rows from 600K Rows Fast in MySQL?
Selecting random rows simultaneously from a database is a common task in SQL especially when handling large datasets. Selecting multiple rows is useful for sampling data or generating random subsets for analysis. In MySQL, this can be achieved using various methods, each has its advantages. In this
4 min read
How to Select Row With Max Value in in SQLite
In SQLite, retrieving rows with the maximum value for a specific column, grouped by another column's distinct values can be a challenging task. Whether you're analyzing data trends or identifying top performers, this operation can provide valuable output. In this beginner-friendly guide, we will exp
4 min read