Vítor Norton
Vítor Norton

Reputation: 478

How to select top 5 after 20 rows

I have this query:

select top 5 * from tbl_post ORDER BY Id DESC

I want to select the first 5 rows after the 20th row. How I can do this?

Upvotes: 2

Views: 3236

Answers (3)

Use OFFSET and LIMIT

SELECT   * 
FROM     tbl_post 
ORDER BY id DESC offset 100 limit 5;

Upvotes: 0

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

with x as (select row_number() over(order by id desc) as rn, * from tbl_post)
select t.* 
from x join tbl_post t on x.id = t.id
where x.rn between 20 and 25

This is the easiest way to assign row numbers and selecting the rows you need later on.

Upvotes: 2

tomsv
tomsv

Reputation: 7277

Use OFFSET and FETCH MSDN OFFSET FETCH Clause:

SELECT * FROM tbl_post ORDER BY whatever OFFSET 20 ROWS FETCH NEXT 5 ROWS ONLY;

Note that you have to order by something for this to work, and you cannot use top at the same time

Upvotes: 5

Related Questions