Relationship between rownum and Order by queries in Oracle queries (the first few records of data)

Source: Internet
Author: User

During application development, it is common to sort data according to certain rules and then retrieve the first few data records. In Oracle, order by is commonly used to obtain data smaller than rownum. However, if you are not familiar with Oracle, you may find that the value retrieved from the SQL statement you wrote is incorrect. Why.

This is because Oracle first Retrieves all the data and then sorts the data in the sorting segment (that is, it first has the rownum value before order by sorting ). Assume that you have an SQL statement as follows.

Select emp_no from emp where rownum <10 order by emp_no;

During retrieval, the data is first retrieved, that is, the EMP table data is retrieved, and then the Order by operation is performed. Because ROWNUM data is retrieved before sorting, ROWNUM cannot be used to obtain the first 10 operations after sorting. So how should we operate it. In fact, it is very easy to use subqueries, first sort and then get ROWNUM. As shown below

Select emp_no from (select emp_no from emp order by emp_no) where rownum <10;

In this way, you will find that you can finally retrieve the results you need, but the disadvantage of this write is that it is slower than the previous execution, and the performance may not be very good.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.