akonsu
akonsu

Reputation: 29536

paginating table and getting row count

The query below fetches a subset of rows from a table starting at row 10 and ending at row 20. In addition, to save a query I need to return the total number of rows in the table. This is the best solution that I could think of. Are there any more efficient/elegant ways? In particular, I do not like the partition by 1 part.

select *
from (select count(*) over (partition by 1) as [count],
             row_number() over (order by [Name],[Description]) as [row],
             *
      from [Products]) as t
where row between 10 and 20

Upvotes: 0

Views: 71

Answers (1)

RichardTheKiwi
RichardTheKiwi

Reputation: 107716

If you don't like it, remove it!

select *
from (select count(*) over () as [count],
             row_number() over (order by [Name],[Description]) as [row],
             *
      from [Products]) as t
where row between 10 and 20

However, that aside, the query isn't optimal. You should do the count the traditional way.

select *
from (select count(*) as [count]
        from [Products]) X
cross join (
    select row_number() over (order by [Name],[Description]) as [row],
           *
      from [Products]) as t
where row between 10 and 20

You can put both of these together and press Ctrl-M, then execute. The plans will look quite different.

Upvotes: 1

Related Questions