Search code examples
sqlpostgresqlgreatest-n-per-group

Select last Modified data record from the Table


denter image description here

This is the table what looks like. I want to select only the record that Last Modified Date is Max. EX: Will Only select 2nd record in above Table. Is it possible?


Solution

  • If you only want a single row even if the max value appears more than once, use LIMIT:

    select amount, created_date, last_mod_date
    from the_table
    order by last_mod_date desc
    limit 1;
    

    If you want multiple rows if the max value appears more than once, you can use a window function:

    select amount, created_date, last_mod_date
    from (
        select amount, created_date, last_mod_date, 
               dense_rank() over (order by last_mod_date desc) as rn
        from the_table
    ) t 
    where rn = 1;