H
I’m trying to figure out why two similar but slightly different SQL queries have such a large discrepancy between the time taken to run them.
I would appreciate input based on the two samples below and the times reported.
The first query is as follows and it takes approximately 115 – 154 seconds to run.
SELECT * FROM
(
SELECT a.*, ROWNUM rnum
FROM
(
SELECT ERR_ID, ERR_CREATED_BY,TO_CHAR(ERR_CREATED_DATE, 'DD/MM/YYYY H24:MI'),
ERR_SOURCE, ERR_DETAIL
FROM tdsys_errors err
WHERE ERR_SOURCE = 'Online Transaction'
ORDER BY ERR_ID DESC
) a
WHERE ROWNUM <= 25
)
WHERE rnum > 0;
The second query has a slight change in terms of the position of the “ORDER BY ERR_ID DESC ” piece and takes approximately 0.07 seconds to run
SELECT * FROM
(
SELECT a.*, ROWNUM rnum
FROM
(
SELECT ERR_ID, ERR_CREATED_BY,TO_CHAR(ERR_CREATED_DATE, 'DD/MM/YYYY H24:MI'),
ERR_SOURCE, ERR_DETAIL
FROM tdsys_errors err
WHERE ERR_SOURCE = 'Online Transaction'
) a
WHERE ROWNUM <= 25
)
WHERE rnum > 0
ORDER BY ERR_ID DESC;
I’m guessing the second query is ordered AFTER the results arrive and the first query tries to do all at once.
Is this an SQL best practice case is what I’m wondering and why is there such a difference?
Thanks
In the first case you’re selecting the first 25 rows – those with the
lowesthighesterr_id. It has to find all the results from your query and then order them all before it knows which 25 to use, which is clearly taking a while.In the second case you’re pulling the first 25 rows returned by the unordered query, which could be anything but is quick, and then ordering only those 25.
You are likely to get different results form the two queries – you certainly shouldn’t assume they’ll always be the same, even if they happen to be sometimes.