If you're on Oracle 12.1 you can use a Top-N query:
select g.id
from TBL1 g
left join TBL2 b on g.REF1= b.REF2
where b.id = 286
order by g.id desc
FETCH FIRST 1 ROW ONLY
Otherwise, you can get the first row using a subquery:
select * from (
select g.id
from TBL1 g
left join TBL2 b on g.REF1= b.REF2
where b.id = 286
order by g.id desc
) where ROWNUM = 1
Both of these forms allow Oracle to use top-N optimisation to avoid keeping the entire result set in temp while it sorts the results.
To optimise further, you would need to look at your tables, their indexes and the explain plan for the query. Some rough ideas/guesses:
- check that
TBL2.id
has an index
- consider an index on
TBL2 (id,REF2)
- check that
TBL1.REF1
has an index
- consider an index on
TBL1 (REF1,id)
However, before considering the above, make sure that the query you're optimising is actually the one your application will be using. It's suspicious that you have the literal value 286
hardcoded in your query - perhaps this should be a bind variable instead.
P.S. due to your WHERE clause on b.id
, this is not an outer join, so the left
keyword is redundant.