Mecanismo eficiente para recuperar rownum

A quick one here. So I read about rownum around the web and am trying to see
which way to call it is best since based on SQL Optimizer both approach shows
ninguna diferencia.

select count(distinct BCC || '~' || BN) BCCN 
from LINK_TBL 
where AN = 'abcdefg' 
and BR = 1 
and rownum <= 5;

or

select count(distinct BCCN)
from (
select BCC||'~'|| BN BCCN 
from LINK_TBL 
where AN = 'abcdefg' and BR = '1'
)
where rownum <= 5;

preguntado el 08 de noviembre de 11 a las 10:11

2 Respuestas

The optimizer can choose to solve / reorganise your query as it sees fit, as long as it provides the right results. If you check the explain plan, you may find them identical.

respondido 08 nov., 11:14

Thanks for the answer. As I analyzed this more last night and input from @Allan, they're indeed identical. I'm new to this stuff, hence the confusion. - cr8ivecodesmith

I suspect what you're missing is the significance of using order by cuando se utiliza rownum. The two queries you posted are functionally equivalent. However, the following two queries are not:

select count(distinct BCC || '~' || BN) BCCN 
from LINK_TBL 
where AN = 'abcdefg' 
and BR = 1 
and rownum <= 5
order by BCC || '~' || BN;

select count(distinct BCCN)
from (
select BCC||'~'|| BN BCCN 
from LINK_TBL 
where AN = 'abcdefg' and BR = '1'
order by BCC || '~' || BN
)
where rownum <= 5;

The difference is that the first query gets all of the rows in the specified order, then takes the first 5 rows and the second query any gets 5 rows then sorts only those 5.

respondido 08 nov., 11:18

Thanks for the input. This helps a lot but the order by isn't necessary for my usage on this one. But this adds up to my learning a lot. - cr8ivecodesmith

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.