The SQL statement used to query the data between the nth and NTH rows in the database in SQL SERVER.

Source: Internet
Author: User

The SQL statement used to query the data between the nth and NTH rows in the database in SQL SERVER.

When writing a program today, You need to generate an SQL statement from the start id to the end id. This function is not required now.

In SQL server, how do I write an SQL statement to query the data between the first and last entries in a database?
For example, in SQL server, how do I write SQL statements that query data between 10th and 30 in a database?


------ Solution --------------------
Select top 20 * from table where id in (select top 30 id from Table order by id) order by id desc
------ Solution --------------------
If a unique Column exists, you can use


Select identity (int, 1, 1) id, * into temp from table

Select * from temp where id between 10 and 30
------ Solution --------------------
Select top 20 * from table where Id field not in (select top 9 Id field from table)
------ Solution --------------------
1
Select top 20 * from table
Where id not in (select top 10 id from Table order by id)
Order by id

2 -- should start from 11
Select * from table where id between 11 and 30

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.