0

I use ORDER BY in the below query but it takes the almost 20 sec to fetch the data.

SELECT id, 
       name, 
       o.map.subject, 
       o.map.xyz 
FROM   student o 
WHERE  test = 3553 
       AND o.map.identifier = 'Abhay' 
ORDER  BY o.id desc 
FETCH first 15 ROWS only; 

When do not use ORDER BY, as shown below, it takes only the 0.2 sec response time which is what I want. The problem is - it is fetching the older data, I need to get the last 15 records inserted into the table student.

Is there any way to sort the data without using ORDER BY? If not, how can I speed up the query?

SELECT id, 
       name, 
       o.map.subject, 
       o.map.xyz 
FROM   student o 
WHERE  test = 3553 
       AND o.map.identifier = 'Abhay' 
FETCH first 15 ROWS only; 
10
  • Check out Indexes and Index-Organized Tables
    – Brien Foss
    Feb 27, 2018 at 5:27
  • @Brien is this a only way ? Feb 27, 2018 at 5:39
  • It seems strange to me that Students would have so many records (tens of millions) in the first place to warrant this performance. Take a look at that link and maybe someone else will provide a real answer to you. I am just pointing out indexes in case you are inexperienced and hadn’t worked with them.
    – Brien Foss
    Feb 27, 2018 at 5:44
  • Try to use WHERE ROWNUM <= 15 instead to FETCH first 15 ROWS only; your query will be something like : SELECT id, name, o.map.subject, o.map.xyz FROM student o WHERE ROWNUM <= 15 AND test = 3553 AND o.map.identifier = 'Abhay' ORDER BY o.id desc; Feb 27, 2018 at 6:07
  • 1
    @KortebyFarouk Simple demonstration here connor-mcdonald.com/2018/02/28/rownum-and-order-by Feb 28, 2018 at 5:08

1 Answer 1

1

The query

SELECT id, 
       name, 
       o.map.subject, 
       o.map.xyz 
FROM   student o 
WHERE  test = 3553 
       AND o.map.identifier = 'Abhay' 
ORDER  BY o.id desc 
FETCH first 15 ROWS only; 

only runs slowly if either it is expensive to find the rows, or we get a huge number of rows and hence it is expensive to sort them.

If it is expensive to find then, then you probably need to consider indexing on TEST,MAP_IDENTIFIER. If, even with that index, the sorting cost is large, that is, you have a huge amount of rows that match the criteria, then you might want to consider adding ID to the index so that you can scan the index in a descending fashion and hence avoid the sorting cost.

Even if you do that, you must always have the ORDER BY clause. Without out, the results are always indeterminate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.