Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get just the first row in a result set AFTER ordering?

Tags:

This gives me just one row (the first one):

SELECT BLA FROM BLA WHERE BLA AND ROWNUM < 2 

However, I want the most recent date val; I can make that the first row this way:

SELECT BLA FROM BLA WHERE BLA ORDER BY FINALDATE DESC 

When I try to mix the two partial victories, though, it doesn't work - apparently the "Select the first row only" logic fires before the order by, and then the order by is subsequently ignored.

like image 254
B. Clay Shannon-B. Crow Raven Avatar asked Aug 15 '12 22:08

B. Clay Shannon-B. Crow Raven


People also ask

How do you select the first row of a group?

First, you need to write a CTE in which you assign a number to each row within each group. To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).


2 Answers

In 12c, here's the new way:

select bla   from bla  where bla  order by finaldate desc  fetch first 1 rows only;  

How nice is that!

like image 57
Brian McGinity Avatar answered Oct 10 '22 22:10

Brian McGinity


This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select * from     ( select *    from emp    order by sal desc )    where ROWNUM <= 5; 
like image 28
user1593858 Avatar answered Oct 10 '22 22:10

user1593858