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 DISTINCT ON
  • 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 :

Anvesh Patel

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz