return first row entered based on date column
temApr 2 2012 — edited Apr 2 2012I'm trying to select the first entered row in a table, as judged by the datetime column. If more than one row has the same date and time, then only one row should be returned (any row having that datetime is fine). Some processing will occur on that row and then it will be deleted. The select statement is used thereafter to select the next (first) entered row in the table, etc. This way, the rows are processed first-in first-out (FIFO) style. Here's my example table:
create table my_table
(
datetime date,
firstname varchar2(50)
)
insert into my_table(datetime, firstname) values(to_date('2012-04-02 11:00:00', 'YYYY-MM-DD HH24:MI:SS'),'ken');
insert into my_table(datetime, firstname) values(to_date('2012-04-02 11:00:00', 'YYYY-MM-DD HH24:MI:SS'),'john');
insert into my_table(datetime, firstname) values(to_date('2012-04-02 11:00:00', 'YYYY-MM-DD HH24:MI:SS'),'sue');
commit;
Here's my example select statement, which returns simply one row of the above, since all are the same date and time:
SELECT *
FROM my_table
WHERE datetime = ( select min(datetime) from my_table )
AND rownum = 1;
My question is, if I use the following
SELECT *
FROM my_table
WHERE datetime = ( select min(datetime) from my_table );
It returns all 3 rows:
DATETIME FIRSTNAME
02-APR-12 11:00:00 ken
02-APR-12 11:00:00 john
02-APR-12 11:00:00 sue
So, wouldn't setting rownum = 2 return john, and rownum = 3 return sue? For example,
SELECT *
FROM my_table
WHERE datetime = ( select min(datetime) from my_table )
AND rownum = 2;
return no rows. I just want to make sure I'm understanding how the select statement above works. It seems to work fine for returning one row having the minimum date and time. If this is always the case, then everything is fine. But I wouldn't have expected it not to return one of the other rows when rownum is 2 or 3, which makes me question why? Maybe I can learn something here. Any comments much appreciated.
Edited by: tem on Apr 2, 2012 2:06 PM