Sqlserver query records in a certain range

Source: Internet
Author: User

Take the first 20 to 30 queries as an example. The primary key name is ID.

Method 1: perform a regular check first and then perform a reverse check.
Select top 10 * from (select top 30 * From tablename order by id asc) A order by ID DESC

Method 2: Use left join
Select top 10 a. * From tablename
Left Outer Join (select top 20 * From tablename order by id asc) B
On a. ID = B. ID
Where B. ID is null
Order by A. ID ASC

Method 3: Use not exists
Select top 10 * From tablename
Where id not exists
(Select top 20 * From tablename B on A. ID = B. ID)

Method 4: Use not in
Select top 10 * From tablename
Where id not in
(Select top 20 ID from tablename order by id asc)
Order by ID ASC

Method 5: Use rank ()
Select ID from
(Select rank () over (order by id asc) rk, ID from tablename) T
Where rk between 20 and 30

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.