views:

24

answers:

2

Hi, all. I have an Oracle table with two columns ID and START_DATE, I want to run a query to get the ID of the record with the most recent date, initially i wrote this:

 select id from (select * from mytable order by start_date desc) where rownum = 1

Is there a more cleaner and efficient way of doing this? I often run into this pattern in SQL and end up creating a nested query.

+1  A: 
SELECT id FROM mytable WHERE start_date = (SELECT MAX(start_date) FROM mytable)

Still a nested query, but more straightforward and also, in my experience, more standard.

froadie
Better, but I think OP wanted to avoid nested queries. I would have tried something with analytic functions... but not sure that would work... hmm...
FrustratedWithFormsDesigner
This fulfils the 'get all records with the most recent start date', which the OPs query doesn't. +1
Will A
Thanks! I'm not really trying to avoid nested queries, I'm very new to SQL so I just wanted to know if what i'm doing is common (or bad) sql coding practice.
wsb3383
A: 

This looks to be a pretty clean and efficient solution to me - I don't think you can get any better than that, of course assuming that you've an index on start_date. If you want all ids for the latest start date then froadie's solution is better.

Will A