Special attention when using order by and RowNum

Source: Internet
Author: User

When using order by with RowNum, make sure that the order by has a column that is guaranteed to be unique

For example select t.* from the person T order by t.age,t.id; ID primary key, age may repeat

If you do not write this, you will have the following problems:

1, first create the table:

Create Table int VARchar2 (tenint)

2. Insert Data:

Insert  intoA_LXZ (Id,name,age)Values(1,'a',3);Insert  intoA_LXZ (Id,name,age)Values(2,'b',4);Insert  intoA_LXZ (Id,name,age)Values(3,'C',5);Insert  intoA_LXZ (Id,name,age)Values(4,'D',6);Insert  intoA_LXZ (Id,name,age)Values(8,'h',7);Insert  intoA_LXZ (Id,name,age)Values(9,'I',7);Insert  intoA_LXZ (Id,name,age)Values(6,'F',7);Insert  intoA_LXZ (Id,name,age)Values(5,'e',7);Insert  intoA_LXZ (Id,name,age)Values(7,'g',7);Insert  intoA_LXZ (Id,name,age)Values(Ten,'J',8);Insert  intoA_LXZ (Id,name,age)Values( One,'k',9);

3, query Result:

4, using ORDER by age query results

5, when using order by + RowNum to get the previous n results, the result is as follows

Here, the question comes out, where does the data with ID 7 go? The result set you would like to get is this:

and got this.

The reasons are:

When the order by sort encounters the same data, the rownum is determined to be unordered (unstable sort),

For example, print out the value of rownum:

You can see that id=7 's rownum is 9, so when we get rownum<=8, we get no id=7 data, so what we see and what we really get is probably inconsistent.

This concludes that when we use order by and rownum, ensure that at least one column after the order by has a unique value.

For example:

The data will ensure that the query is consistent with the acquisition.

Usage scenarios:

Resolves the full display of the query list, with pagination displayed with inconsistent data.

Special attention when using order by and RowNum

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.