[Solved] How to get the first row from a table based on multiple group by
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

How to get the first row from a table based on multiple group by

Database type:

I have a PostgreSQL table and need to select the first record based on different groups of columns (each time group by a combination of different columns).

table1 (id1, id2, id3, id4, u1, u2, u3, ...)

I tried this code and it works fine.

select 
  t.*,
  row_number() over (partition by id1, id2) as rn1,
  row_number() over (partition by id1, id3) as rn2,
  row_number() over (partition by id1, id2, id4) as rn3
from table1 t

and I need only the first records from each group (rn1 = 1, rn2 = 1, rn3 = 1).

case when rn1 = 1 and u1 > 0 then 1 else 0 as res1
case when rn2 = 1 and u2 = 1 then 1 else 0 as res2
case when rn3 = 1 and u3 < 0 then 1 else 0 as res3

But this query is very slow and need to rewrite it without using any window function. Is there anyway to do it?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
SELECT
        t.*,
        row_number() OVER (PARTITION 
    BY
        id1,
        id2 ) AS rn1,
        row_number() OVER (PARTITION 
    BY
        id1,
        id3 ) AS rn2,
        row_number() OVER (PARTITION 
    BY
        id1,
        id2,
        id4 ) AS rn3 
    FROM
        table1 t

Related Articles



* original question posted on StackOverflow here.