Search code examples
sqlgreatest-n-per-groupdistinct-values

Select only n rows in an SQL for an element


I have a table with a lot of columns for each table2_id I would like to have only the 5 rows with the largest id

id | table_2_id | name
----------------------
1  | 1          |A
2  | 1          |B
3  | 1          |C
4  | 1          |D
5  | 1          |E
6  | 1          |F 
7  | 1          |F 
8  | 2          |G
9  | 3          |H 
10 | 3          |I

There are 7 elements that have 1 in table_2_id, and I would like to have 5

So I would like to have

id | table_2_id | name
----------------------
3  | 1          |C
4  | 1          |D
5  | 1          |E
6  | 1          |F 
7  | 1          |F 
8  | 2          |G
9  | 3          |H 
10 | 3          |I

Solution

  • You can use row_number()

    select * from
    (
    select *, row_number() over(partition by table_2_id order by id desc) as rn
    from tablename
    )A where rn<=5