Alaska Cowboy
asked on
selecting first record from an ordered list in pl*sql
I have a cursor that might return 0, 1, or multiple records.
The query is ordered but I only want the first record.
So what is a good programming construct to do this ?
I have the code below but it's probably ugly to the experienced Oracle programmer . . .
The query is ordered but I only want the first record.
So what is a good programming construct to do this ?
I have the code below but it's probably ugly to the experienced Oracle programmer . . .
loop_counter := 0;
open idm_ssn_check_cur;
loop
loop_counter := loop_counter + 1;
fetch idm_ssn_check_cur into memb_id_nbr_ret;
exit when idm_ssn_check_cur%notfound;
if loop_counter = 1 then
exit;
end if;
end loop;
close idm_ssn_check_cur;
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
sdstuber,
ah, that's good too. I had this situation a while back and tried the query straight up with "where rownum = 1", but it does the "rownum = 1" before it does the order by - but your in-line table does the trick !
thanks !
ah, that's good too. I had this situation a while back and tried the query straight up with "where rownum = 1", but it does the "rownum = 1" before it does the order by - but your in-line table does the trick !
thanks !
yes, it's essential to do the ordering within a nested (in-line) query
If you generate an explain plan for the query with outer-query rownum you should hopefully see a "COUNT STOPKEY" operation, if so that means the parser recognizes your rownum restriction and will optimize your query on the basis of a fixed upper bound on the query.
If you generate an explain plan for the query with outer-query rownum you should hopefully see a "COUNT STOPKEY" operation, if so that means the parser recognizes your rownum restriction and will optimize your query on the basis of a fixed upper bound on the query.
slight correction -
... the optimizer will "attempt to" optimizer your query on the basis of a fixed upper bound ...
it's only an "attempt", not a guarantee
... the optimizer will "attempt to" optimizer your query on the basis of a fixed upper bound ...
it's only an "attempt", not a guarantee
ASKER
ok, thanks, I see the STOPKEY sort restriction
ASKER
that's cleaner, yes. thanks
Open in new window