I have an oracle database populated with million records. I am trying to write a SQL query that returns the first 'N" sorted records ( say 100 records) from the database based on certain condition.
SELECT *
FROM myTable
Where SIZE > 2000
ORDER BY NAME DESC
Then programmatically select first N records.
The problem with this approach is :
- The query results into half million records and "ORDER BY NAME" causes all the records to be sorted on NAME in the descending order. This sorting is taking lot of time. (nearly 30-40 seconds. If I omit ORDER BY, it takes only 1 second).
- After the sort I am interested in only first N (100) records. So the sorting of complete records is not useful.
My questions are:
- Is it possible to specify the 'N' in query itself? ( so that sort applies to only N records and query becomes faster).
- Any better way in SQL to improve the query to sort only N elements and return in quick time.