Search code examples
sqloracle-sqldeveloper

Select 2 most recent dates from the table - SQL


I have a table like below

ID_NUMBER SALEDATA SALEAMOUNT
1 2020-09-07 47,000
2 2020-03-25 51,470
3 2021-06-12 32,000
4 2018-10-12 37,560

I want to select the rows with the 2 most recent dates only. So my desired output would be like below

ID_NUMBER SALEDATA SALEAMOUNT
1 2020-09-07 47,000
3 2021-06-12 32,000

Can someone please guide me on where would i start with this in SQL? I tried using MAX() but it is only giving me the most recent.

Thank you!


Solution

  • In Standard SQL, you would use:

    select t.*
    from t
    order by saledata desc
    offset 0 row fetch first 2 row only;
    

    Not all databases support fetch first. It might be spelled limit or select top or something else, depending on your database.