Home > Database > Mysql Tutorial > How to Efficiently Retrieve the Last Row for Each ID in PostgreSQL?

How to Efficiently Retrieve the Last Row for Each ID in PostgreSQL?

Susan Sarandon
Release: 2024-12-28 17:09:11
Original
448 people have browsed it

How to Efficiently Retrieve the Last Row for Each ID in PostgreSQL?

PostgreSQL: Retrieving the Last Row for Each ID

Problem:

Given the following data, you want to extract the last record for each unique ID:

id    date          another_info
1     2014-02-01         kjkj
1     2014-03-11         ajskj
1     2014-05-13         kgfd
2     2014-02-01         SADA
3     2014-02-01         sfdg
3     2014-06-12         fdsA
Copy after login

Desired Result:

id    date          another_info
1     2014-05-13         kgfd
2     2014-02-01         SADA
3     2014-06-12         fdsA
Copy after login

Solution:

There are two efficient methods to achieve this in PostgreSQL:

Method 1: Using the DISTINCT ON Operator

Postgres provides the DISTINCT ON operator, which enables you to select distinct rows based on one or more columns and then apply other operations. For this scenario, you can use:

SELECT DISTINCT ON (id) id, date, another_info
FROM the_table
ORDER BY id, date DESC;
Copy after login

Method 2: Using a Window Function

Window functions allow you to perform aggregations or calculations over a set of rows that can be defined dynamically. You can use a window function called ROW_NUMBER() to assign a rank to each row within each ID group and select the row with the highest rank:

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;
Copy after login

The solution using a window function is typically faster than using a subquery.

The above is the detailed content of How to Efficiently Retrieve the Last Row for Each ID in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template