List the Last 5 Rows of a Result Set in PostgreSQL
Last Updated :
16 May, 2024
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 in PostgreSQL.
In this article, We will learn about various methods along with the examples and output for better understanding.
Understanding the Basics
- PostgreSQL offers several ways to retrieve data from a table. One common method involves using the SELECT statement coupled with ORDER BY to sort the data in a desired order.
- By default, this sorts the data in ascending order, but by adding the DESC keyword, we can arrange it in descending order.
Set Up an Environment
let's consider a sample table named sample_table with 3 columns (id, name, and age) and 8 rows of sample data. Here's the structure of the table:
| id | name | age |
|----|----------|-----|
| 1 | John | 25 |
| 2 | Alice | 30 |
| 3 | Bob | 22 |
| 4 | Emma | 28 |
| 5 | Michael | 35 |
| 6 | Sarah | 27 |
| 7 | David | 40 |
| 8 | Lily | 32 |
1. Using ORDER BY and LIMIT Clause
This method uses the ORDER BY clause along with the LIMIT clause to retrieve the last few rows of a result set.
SELECT *
FROM sample_table
ORDER BY id DESC
LIMIT 5;
Output
| id | name | age |
|----|----------|-----|
| 8 | Lily | 32 |
| 7 | David | 40 |
| 6 | Sarah | 27 |
| 5 | Michael | 35 |
| 4 | Emma | 28 |
Explanation: This query fetches all rows from the sample_table, orders them based on the id column in descending order, and limits the result set to the last 5 rows.
2. Using OFFSET
This method calculates the offset (number of rows to skip) by subtracting 5 from the total row count of sample_table and then fetches the last 5 rows.
SELECT *
FROM sample_table
ORDER BY id DESC
OFFSET (SELECT COUNT(*) - 5 FROM sample_table)
LIMIT 5;
Output:
| id | name | age |
|----|----------|-----|
| 8 | Lily | 32 |
| 7 | David | 40 |
| 6 | Sarah | 27 |
| 5 | Michael | 35 |
| 4 | Emma | 28 |
Explanation: This query calculates the offset (number of rows to skip) by subtracting 5 from the total row count of sample_table. Then, it fetches the last 5 rows.
3. Using Window Functions
This method uses the ROW_NUMBER() window function to assign row numbers to each row based on the id column's descending order. It then filters the rows based on their row numbers to retrieve the last 5 rows.
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY id DESC) AS row_num
FROM sample_table
) AS sub
WHERE row_num BETWEEN (SELECT COUNT(*) FROM sample_table) - 4 AND (SELECT COUNT(*) FROM sample_table);
Output
| id | name | age | row_num |
|----|----------|-----|---------|
| 4 | Emma | 28 | 5 |
| 5 | Michael | 35 | 6 |
| 6 | Sarah | 27 | 7 |
| 7 | David | 40 | 8 |
| 8 | Lily | 32 | 9 |
Explanation: This query assigns row numbers to each row based on the id column's descending order. Then, it filters the rows based on their row numbers to retrieve the last 5 rows.
Conclusion
Overall, Efficiently retrieving data is a crucial aspect of database management and application development. In PostgreSQL, listing the last few rows of a result set can be solved using various techniques, including ORDER BY and LIMIT, OFFSET, and window functions like ROW_NUMBER(). By understanding and using these methods, you can easy your data retrieval processes and enhance the performance of your PostgreSQL queries
Similar Reads
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 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 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
PL/SQL Query to List the Last 5 Rows of a Result Set
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
5 min read
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
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 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
PostgreSQL - LIMIT with OFFSET clause
The PostgreSQL LIMIT clause is a powerful feature that allows users to retrieve a specific subset of rows from query results. This optional clause can be paired with the OFFSET clause to skip a specified number of rows before returning the desired results. Such functionality is particularly benefici
4 min read
How to Restrict Results to Top N Rows per Group in PostgreSQL?
In data analysis, understanding how to extract meaningful insights from grouped data is crucial. PostgreSQL, a powerful open-source relational database management system, provides robust features to handle such scenarios effectively. One common analytical task is limiting results to the top N rows w
4 min read
How to Write a Normal Select Procedure in PostgreSQL?
PostgreSQL is an open-source relational database management system with a variety of features that allow users to operate database operations and improve the speed of queries. One of these options is the ability to write stored procedures, the SQL code that logically embeds logic for a more organize
4 min read