Optimization of one paging SQL query (based on SQL Server)

Source: Internet
Author: User

 

 

 

Assume that student has the following fields:

 

ID: The clustered index is created.

Name: corresponding name

Gender: Gender

 

There is a stored procedure that requires paging to retrieve students of a certain gender and perform paging.

 

 

The paging SQL statement in it is like this. Assume that we want to retrieve the data of 100 and 20th pages per page sorted by ID.

 

 

 

Select top 20 * from student

Where where gender = 'male' and not exists (

Select top 1900 ID from student

Where gender = 'male'

Order by ID)

Order by ID

Because it is sorted by ID, it is equivalent to knowing the largest ID of the first 1900, and then the select of the outer layer is not less than the ID of the first 1900,

 

Therefore, you can write:

 

Select top 20 * from student

Where where gender = 'male' and ID> (

Select max (ID) from (

Select top 1900 ID from student

Where gender = 'male'

Order by ID ))

Order by ID

 

Performance will be greatly improved.

 

Related Article

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.