"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to extract the last row of data for each ID in PostgreSQL?

How to extract the last row of data for each ID in PostgreSQL?

Posted on 2025-04-12
Browse:871

How to Extract the Last Row for Each ID in PostgreSQL?

Extracting the Last Row for Each ID in Postgresql

Consider a dataset with columns named id, date, and another_info. The objective is to extract the last information (row) for each unique id.

To accomplish this in Postgresql, two methods are commonly used:

Distinct On Operator

Postgresql provides the distinct on operator, which allows you to specify that only distinct values of a particular column(s) be returned. In this case, the operator can be used as follows:

select distinct on (id) id, date, another_info
from the_table
order by id, date desc;

This query ensures that only the last instance of each unique id is returned, ordered in descending order by date.

Window Functions

Alternatively, you can use window functions to achieve the same result. A window function allows you to perform calculations or aggregations on a partitioned set of rows. In this case, the following query can be used:

select id, date, another_info
from (
  select id, date, another_info, 
         row_number() over (partition by id order by date desc) as rn
  from the_table
) t
where rn = 1
order by id;

This query uses the row_number() function to assign a sequential number to each row within each id partition. The where clause filters the results to include only the rows with the highest rn value (i.e., the last row for each id).

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3