views:

46

answers:

2

SELECT instmax,
r
FROM
(SELECT instmax,
rownum r
FROM
( SELECT instmax FROM pswlinstmax ORDER BY instmax DESC NULLS LAST
)
WHERE rownum <= 10
)
WHERE r >=6;

Output

alt text

SELECT instmax,
r
FROM
(SELECT instmax,
rownum r
FROM
( SELECT instmax FROM pswlinstmax ORDER BY instmax DESC NULLS LAST
)
)
WHERE r between 6 and 10;

Output

alt text

Is there really a definite performance gain among both the query?Can you please clarify me on this?

A: 

Hi!

That's probably because the STOPKEY optimization doesn't work anymore.

The "rownum < xx" is very special (called Top-N query) that has special optimizations. the between clause doesn't trigger that anymore.

You should compare the exeuction plans and look for "STOPKEY", if that is in, it is the optimized Top-N query.

see also:

http://blog.fatalmind.com/2010/07/30/analytic-top-n-queries/

Markus Winand
what is actually this this STOPKEY optimisation? Can you explain me in a simplified way?
Pradosh Kumar Jena
@Pradosh: this means the engine will stop the query after it fetched the `10th` record.
Quassnoi
@Quassnoi.ok so in the 1st query it will fetch only till 10th row.ok
Pradosh Kumar Jena
STOPKEY indicates that the database stops searching further values becuase the "rownum < x" expression has been reached.without STOPKEY, the database searches all values, but filters out (in the next step) the ones not needed.
Markus Winand
+1  A: 

Oracle cannot push conditions that involve aliased ROWNUM into the inline views.

This means that the second query will use a full table (or index) scan with filtering on rn, while the first one will use STOPKEY (since it uses unaliased ROWNUM < 10)

You may want to read this article:

Quassnoi
I am not able to open that link.Can you please broaden your explanation?
Pradosh Kumar Jena
@Pradosh: there is too much text there to copy it here. The link is working (just checked).
Quassnoi