There is a clear answer how to select top 1:
select * from table_name where rownum = 1
and how to order by date in descending order:
select * from table_name order by trans_date desc
but they does not work togeather (rownum
is not generated according to trans_date
):
... where rownum = 1 order by trans_date desc
The question is how to select top 1 also ordered by date?
it means order by the very first column from the select list.
Using the GROUP BY clause to group all rows by the target column(s) – i.e. the column(s) you want to check for duplicate values on. Using the COUNT function in the HAVING clause to check if any of the groups have more than 1 entry; those would be the duplicate values.
DUAL table has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X. Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once.
Modern Oracle versions have FETCH FIRST
:
select * from table_name order by trans_date desc
fetch first 1 row only
... where rownum = 1 order by trans_date desc
This selects one record arbitrarily chosen (where rownum = 1
) and then sorts this one record (order by trans_date desc
).
As shown by Ivan you can use a subquery where you order the records and then keep the first record with where rownum = 1
in the outer query. This, however, is extremely Oracle-specific and violates the SQL standard where a subquery result is considered unordered (i.e. the order by clause can be ignored by the DBMS).
So better go with the standard solution. As of Oracle 12c:
select *
from table_name
order by trans_date desc
fetch first 1 row only;
In older versions:
select *
from
(
select t.*, row_number() over (order by trans_date desc) as rn
from table_name t
)
where rn = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With