Row Number with CTE

Basically this is the simplest approach because in that we will give the index or id to the whole data set and we will get only the result set which is required. Which means using this we can also first 25% rows.

WITH total_count AS (
SELECT COUNT(*) AS cnt
FROM employees
),
last_25_percent AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY employee_id) AS row_num
FROM employees
)
SELECT *
FROM last_25_percent, total_count
WHERE row_num > (cnt* 3.0 / 4.0)

Output:

CTE with Row Number

Explanation: In first CTE we just take the total count of rows. While in second CTE we have given row number to all the rows and then in main query applied where condition in which only the rows more than 3/4th will be shown.

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, or optimizing queries for performance.

Similar Reads

List the Last 25% Rows in a Result Set in PostgreSQL

This article will guide you through different methods to list the last 25% of rows in a result set in PostgreSQL, including:...

Set Up an Environment

For that first, we will create a table in pgAdmin. For the demo, we will make an employee table....

1. Row Number with CTE

Basically this is the simplest approach because in that we will give the index or id to the whole data set and we will get only the result set which is required. Which means using this we can also first 25% rows....

2. Subquery with Row Number

Now we will try to make the above query with subquery rather than CTE for that we will replace the CTE with subquery while all the other steps would be same....

3. Subquery with offset and limit

Now we can also achieve this thing with Subquery without using Row Number but in that we will be using offset and limit. In which offset will be used to mark the row from which the reading of data will be started and Fetch will take the next and return it to the result set....

4. Dense Function with CTE

Dense function is nothing but a Dense_Rank() function is used to give the same rank to the rows if it contains the same value in result set. We will replace the Rank() from the approach 1....

Conclusion

These are some commonly used approaches to list the last 25% of rows in a result set in PostgreSQL. By using techniques such as CTEs, subqueries, and window functions like ROW_NUMBER() and DENSE_RANK(), you can efficiently fetch specific portions of your data for analysis or other purposes. Experiment with these methods to find the one that best fits your use case and performance requirements....