PL/SQL Query to List the Last 5 Rows of a Result Set
Last Updated :
17 Apr, 2024
Fetching or displaying the last five rows is a common task. Whether fetching trending topics or tracking a user's recent activity, fetching the last five rows will help in these situations. These are a few use cases we have discussed, there are many more. Product recommendation is crucial if you are maintaining an e-commerce website.
For this reason, too, we have to fetch recent rows. PL/SQL is a procedural extension of SQL which provides us the flexibility to write or modify our scripts. Through PL/SQL, we can easily achieve our said task. In this article, we will discuss briefly how to fetch the last 5 rows from a result set. We will cover all basic concepts with some clear and concise examples along with their explanations.
Setup the Environment
In this tutorial on “PL/SQL Query to List the Last 5 Rows of a Result Set “, we will use the following table for examples:
Table - geeksforgeeksCreate Table:
CREATE TABLE geeksforgeeks
(
id NUMBER ,
name VARCHAR2(50),
rank NUMBER
);
Insert Values:
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (108, 'Vishu', 1);
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (109, 'Ayush', 2);
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (110, 'Sumit', 3);
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (111, 'Neeraj', 4);
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (112, 'Vivek', 5);
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (115, 'Harsh', 6);
INSERT INTO geeksforgeeks (id, name, rank)
VALUES (116, 'Rahul', 7);
1. Using a Basic Approach
In this method, we will cover some very basic approaches to achieve our end goal of last 5 rows. We will first calculate the total number rows of our table. If the rows is less than 5, then we will display the error message. Otherwise, we will compute the nth row from where last 5 queries will be displayed (i.e. total number of rows - 5). We will maintain a row count too. If the row count exceeds the nth row of last 5 rows, we will display the row. Lets refer to the query for more clear understanding.
Query:
DECLARE
v_totalRows NUMBER;
v_last5 NUMBER := 0;
v_row_count NUMBER := 0;
BEGIN
SELECT COUNT(*) INTO v_totalRows FROM geeksforgeeks;
v_last5 := v_totalRows - 5;
IF v_totalRows < 5 THEN
DBMS_OUTPUT.PUT_LINE('Error : There are less than 5 rows in the table.');
ELSE
FOR i IN (
SELECT *
FROM (
SELECT *
FROM geeksforgeeks
ORDER BY id
)
) LOOP
IF v_row_count >= v_last5 THEN
DBMS_OUTPUT.PUT_LINE('ID: ' || i.id || ', Name: ' || i.name || ', Rank: ' || i.rank);
END IF;
v_row_count := v_row_count + 1;
END LOOP;
END IF;
END;
Output:
Basic ApproachExplanation: In the above query, we have successfully performed error handling. We have calculated total number of rows of our table. With this total number of rows we will subtract 5 which will eventually give us the starting index of the last 5 rows. Now we maintain a row count. If the row count becomes equal or grater than the starting index of last 5 rows, then we will display it. You can refer to the above displayed image for more clear understanding.
2. Using ROW_NUMBER() function
In this method, we will use ROW_NUMBER() function to achieve our task. Likewise in the previous method, we will compute total number of rows of the table. ROW_NUMBER() refers to the special id which is provided by SQL, when a row is inserted. IT usually starts with 1 and increment by 1 for the other succeeding rows.
Query:
DECLARE
v_totalRows NUMBER;
BEGIN
SELECT COUNT(*) INTO v_totalRows FROM geeksforgeeks;
IF v_totalRows < 5 THEN
DBMS_OUTPUT.PUT_LINE('Error: There are less than 5 rows in the table.');
ELSE
FOR i IN (
SELECT *
FROM (
SELECT id, name, rank,
ROW_NUMBER() OVER (ORDER BY id) AS rowNumber
FROM geeksforgeeks
)
WHERE rowNumber > v_totalRows - 5
)
LOOP
DBMS_OUTPUT.PUT_LINE('ID: ' || i.id || ', Name: ' || i.name || ', Rank: ' || i.rank );
END LOOP;
END IF;
END;
Output:
Using ROW_NUMBER() functionExplanation: In the above query, we have handled error just as we did in the previous example. We have calculated the total number of rows of our table. If the row number becomes grater than the starting row index, then we will display the row. We have followed the similar approach as we did in the previous example, just replace the manual row count with the ROW_NUMBER() function. You can refer to the image for more clear understanding of the working of the query.
Conclusion
Overall, fetching the list of last 5 rows is basic and common task. We need to fetch last 5 rows if we are dealing with application which tracks user recent activity. We also need this, if we are dealing with an Ecommerce website where product recommendation is very important. We have covered a basic and a approach which includes ROW_NUMBER() function. We have covered all the basic concepts with the clear explanation of the working of the query.
Similar Reads
PL/SQL Query to List the Last 25% Rows in a Result Set
We sometimes need to fetch some specific rows from our result set. There are many reasons to do so. When we are working on real-time analytics, focusing on recent data is then our need. This helps us in quicker decision-making as it provides us the quicker insight into the latest data. PL/SQL is a p
5 min read
PL/SQL Query to List the First 50% Rows in a Result Set
Listing the First 50% Rows in a Result Set can be considered as a normal day-to-day problem. When dealing with data analysis-related tasks, especially with large data sets, fetching all the data at once might create a problem. Getting the first 50% of rows can help in performing the initial analysis
5 min read
List the Last 5 Rows of a Result Set
SQL (Structured Query Language) is a powerful tool for managing databases and performing complex operations on data. A common requirement when working with large datasets is retrieving the last few rows of a result set. This can be especially useful for tracking recent records, sorting data, or anal
4 min read
List the Last 5 Rows of a Result Set in PostgreSQL
PostgreSQL provides several methods to retrieve data from tables. One common approach involves using the SELECT statement with ORDER BY to sort data, with the option to use DESC for descending order. By understanding these basics, we can explore techniques to list the last few rows of a result set i
4 min read
List the Last 25% Rows in a Result Set
Fetching the last 25% of rows from a result set is a common query that provides insights into the most recent trends in data. This technique is particularly useful for quick analytics or reporting, especially when dealing with large datasets. In this article, we will explore how to list the last 25%
5 min read
List the Last 25% Rows in a Result Set in PostgreSQL
In PostgreSQL, extracting specific portions of a result set can be achieved using a variety of SQL techniques. One common requirement is to retrieve the last 25% of rows from a result set. This can be useful for various purposes, such as paginating results, performing analyses on a subset of data, o
4 min read
List the First 50% Rows in a Result Set
When working with substantial quantities of data in MySQL, it's often necessary to extract just a portion of the data. For example, during data analysis or when implementing pagination, you might need to list the top 50% of rows from a query's result set. This article will guide you through the step
4 min read
PL/SQL Query to List the Second Highest Salary By Department
Fetching the highest salary or nth lowest salary can be considered a common task when we are dealing with some real case scenarios. We often face such scenarios when there is sales performance analysis, merit-based promotions, salary benchmarking, etc. These are a few use cases to fetch nth highest
5 min read
How to print the first or last rows of a data set
A data set typically means a collection of data organized in a tabular form, like a spreadsheet or a database table. Various programming languages have different techniques/methods to represent a data set in C++ we use vectors or arrays of structs/objects, In python pandas Data Frames, and Java 2D a
5 min read
How to Limit Query Results in SQL?
SQL provides powerful features like the LIMIT clause to control the number of rows returned, making it an essential tool for optimizing queries and retrieving precise results. Whether weâre managing large datasets or working on performance tuning, understanding how to limit query results is key.In t
4 min read