SQL query record number result set a range of records _mssql

Source: Internet
Author: User
Take the first 20 to 30 in the query as an example, with the primary key named ID

Method One: Check first, then reverse check
Select Top * FROM (SELECT top * to tablename ORDER BY ID ASC) an ORDER by id DESC

Method Two: Use the LEFT Join
Select Top a.* from tablename A
Left OUTER JOIN (select the FROM tablename the ORDER by ID ASC) B
On a.id = b.ID
where b.id is null
ORDER BY a.id ASC

Method Three: Use NOT EXISTS
Select Top * FROM tablename A
where ID NOT exists
(select Top * from tablename B on a.id = b.id)

Method Four: Use Not in
Select Top * FROM tablename
where ID not in
(select Top ID from tablename ORDER by ID ASC)
ORDER BY ID ASC

Method V: Use Rank ()
Select ID from
(select Rank () over (order by ID ASC) RK, IDS from TableName) T
where RK between and 30

The fifth method seems to have no problem, check the document below, when over () for Rank/row_number, the integer column can not describe a column, so it will produce unexpected effects. Consider what you can do to change it to the desired result.

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.