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

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.

This question is related to sql oracle sql-order-by

The answer is


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!


You can nest your queries:

select * from (
    select bla
    from bla
    where bla
    order by finaldate desc
)
where rownum < 2

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to oracle

concat yesterdays date with a specific time ORA-28001: The password has expired how to modify the size of a column How to create a blank/empty column with SELECT query in oracle? Find the number of employees in each department - SQL Oracle Query to display all tablespaces in a database and datafiles When or Why to use a "SET DEFINE OFF" in Oracle Database How to insert date values into table error: ORA-65096: invalid common user or role name in oracle In Oracle SQL: How do you insert the current date + time into a table?

Examples related to sql-order-by

Laravel Eloquent: Ordering results of all() SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12 SQL ORDER BY multiple columns How to use Oracle ORDER BY and ROWNUM correctly? MySQL order by before group by Ordering by specific field value first MySQL ORDER BY multiple column ASC and DESC How can I get just the first row in a result set AFTER ordering? SQL order string as number Order by multiple columns with Doctrine