1

I see there are some similar questions, but I was unable to find an answer that I understood as I am not a SQL query expert.

This currently works to get the page of records:

WITH PAGE AS 
(
   SELECT 
       ROW_NUMBER() OVER (ORDER BY SEQUENCE_NO ASC) AS _ROW_, * 
   FROM mytable
) 
SELECT * 
FROM PAGE 
WHERE _ROW_ BETWEEN 0 AND 25

But how can I modify this so that it also returns the total number of records that matched the first query ?

WITH PAGE AS 
(
   SELECT 
       ROW_NUMBER(), COUNT(*) OVER (ORDER BY SEQUENCE_NO ASC) AS _ROW_, _TOTAL_, * 
   FROM mytable
) 
SELECT * 
FROM PAGE 
WHERE _ROW_ BETWEEN 0 AND 25

I get the following error:

Incorrect syntax near 'ROW_NUMBER', expected 'OVER'

3
  • 1
    Consider using OFFSET-FETCH if SQL version is 2012+ Commented Jan 16, 2016 at 11:59
  • Thanks, I should have mentioned it is 2008. Commented Jan 16, 2016 at 12:00
  • Is SEQUENCE_NO unique? Commented Jan 16, 2016 at 12:02

2 Answers 2

3

That is not the right syntax, You need to use another Over clause for count

Try this

;WITH PAGE AS 
(
SELECT ROW_NUMBER() OVER(ORDER BY SEQUENCE_NO ASC) AS _ROW_,
       COUNT(*) OVER() AS _TOTAL_, * 
FROM mytable
) 
SELECT * FROM PAGE WHERE _ROW_ BETWEEN 0 AND 25
Sign up to request clarification or add additional context in comments.

Comments

0

version using offset and Fetch

select 
 * from 
test1
order by id 
offset 0 rows fetch first 10 rows only;

Above query orders by id column and doesn't skip(offset) any rows and gives me first 10 rows.

select 
 * from 
test1
order by id 
offset 10  rows fetch next 10 rows only;

Above query skips first 10 rows and gives me next 10 rows based on id column order

we also can use variables

declare @offset int
declare @fetch int

Set @offset=10
set @fetch =10

    select 
     * from 
    test1
    order by id 
offset (@offset)  rows fetch first (@fetch) rows only;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.