


How to Efficiently Retrieve the Last Row for Each Unique Identifier in PostgreSQL?
Dec 17, 2024 pm 02:59 PMPostgresql: Extracting the Last Row for Each Unique Identifier
In PostgreSQL, you may encounter situations where you need to extract the information from the last row associated with each distinct identifier within a dataset. Consider the following data:
<pre> 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
</pre>
To retrieve the last row of information for each unique id in the dataset, you can employ Postgres' efficient distinct on operator:
select distinct on (id) id, date, another_info from the_table order by id, date desc;
This query will return the following output:
<pre> id date another_info
1 2014-05-13 kgfd
2 2014-02-01 SADA
3 2014-06-12 fdsA
</pre>
If you prefer a cross-database solution that may sacrifice slight performance, you can use a window function:
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;
In most cases, the solution involving a window function is faster than using a sub-query.
The above is the detailed content of How to Efficiently Retrieve the Last Row for Each Unique Identifier in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

What is SQLite? Comprehensive overview

Run MySQl in Linux (with/without podman container with phpmyadmin)

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?

Running multiple MySQL versions on MacOS: A step-by-step guide

How do I configure SSL/TLS encryption for MySQL connections?
