Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select top 1 and ordered by date in Oracle SQL? [duplicate]

Tags:

sql

oracle

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?

like image 624
Ivan Gerasimenko Avatar asked Jun 08 '17 08:06

Ivan Gerasimenko


People also ask

What is ORDER BY 1 in Oracle SQL?

it means order by the very first column from the select list.

How do you get only one record for each duplicate rows of the ID in SQL?

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.

What is select * from dual in Oracle?

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.


2 Answers

Modern Oracle versions have FETCH FIRST:

select * from table_name order by trans_date desc
fetch first 1 row only
like image 151
jarlh Avatar answered Sep 28 '22 04:09

jarlh


... 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 = 1in 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;
like image 24
Thorsten Kettner Avatar answered Sep 28 '22 03:09

Thorsten Kettner