Sample Header Ad - 728x90

Best way to implement Pagination in SQL Server

1 vote
0 answers
1685 views
I have a complex stored procedure that takes a customerId and some other parameters and returns thousands of rows. We want to implement pagination in this SP since the number of rows being returned is pretty huge. There is a main table that has all the product information (more than 100 million rows) and then I have to join it to other tables to get more information about the product. ProductId is the primary key in the Product table. We have a non-clustered index on date with productId in the INCLUDE section. There are two approaches that I have in mind.

First Method:
Step 1: Get all the rows for the product id and order by date and stored them in a temp table (#temp1) that will have an identity column as the primary key.
Step 2: Pick the rows based on @first and @last parameters where @first = (@page - 1) * @display and @last = (@page * @display) + 1 from the temp table created in the previous step and store them in another temp table (#temp2).
Step 3: Join the rows from #temp2 to all the other tables and get the required data.

/* @display and @page are passed in along with other input parameters */ Declare @first Int = (@page - 1) * @display Declare @last Int = (@page * @display) + 1 Create Table #temp1 (Id int identity(1,1) primary key, productId uniqueidentifier) Create Table #temp2 (productId uniqueidentifier) Insert Into #temp1 Select productId From dbo.product Order by date Insert into #temp2 Select productId From #temp1 Where id > @first And id Second Method:
Step 1: Get the rows for the product id ordered by date and have an offset and fetch by clause and store them in a temp table (#temp1).
Step 2: Join the rows from #temp1 to all the other tables and get the required data.
/* @display and @page are passed in along with other input parameters */ Declare @first Int = (@page - 1) * @display Create Table #temp1 (productId uniqueidentifier) Insert Into #temp1 Select productId From dbo.product Order by date Offset @first rows fetch next @display rows only Select * From #temp1 Join some other product tables on product id With method 1, I'll have to load all the data everytime the procedure is called and then filter the rows that I need.
With method 2, I can only fetch the rows i'm interested in but I've read stuff online that offset and fetch can actually slow the query a lot. Which is usually the best approach for pagination in SQL Server? Of the two methods I described which one would be a better option or is there a better way? Thanks!
Asked by lifeisajourney (751 rep)
Aug 31, 2022, 03:49 PM