PostgreSQL: Optimized way to get first Record per each GROUP (using DISTINCT ON, LATERAL)

Dont you think, this is a very common requirement for most of the Database Developer.

Yes, MySQL Developer can visit this article.

Find top N records for each group in MySQL

In PostgreSQL, We can get a first record for each GROUP using different options like:

  • Using LATERAL
  • CTE with ROW_NUMBER()
  • CTE with LATERAL
  • Subquery with ROW_NUMBER()
  • Using array_agg()

In this demonstration, I am going to give two optimized solutions to get one record per each GROUP.

Create a table with Sample records:

First Solution using DISTINCT ON:
As per the Postgres official document,

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.

Second Solution using LATERAL:
A LATERAL allows sub-queries to reference columns provided by preceding FROM items.

The Result of both the solution :

Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from

Leave a Reply

Be the First to Comment!

Notify of