CodexBloom - Programming Q&A Platform

Trouble with OFFSET-FETCH clause not returning expected results in T-SQL queries

👀 Views: 1629 💬 Answers: 1 📅 Created: 2025-06-13
sql-server t-sql pagination T-SQL

I'm building a feature where I'm not sure how to approach I've been banging my head against this for hours... I'm working with an scenario with the `OFFSET-FETCH` clause in my T-SQL queries. I am trying to implement pagination on a large dataset in SQL Server 2019, but the results don't seem to be returning the correct rows. Here's the query I'm using: ```sql SELECT ProductID, ProductName, Price FROM Products ORDER BY ProductID OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY; ``` I've set `@Offset` to 20 and `@PageSize` to 10, expecting to get rows 21 to 30. However, when I run the query, I'm getting rows 1 to 10 instead. I checked the values of `@Offset` and `@PageSize`, and they're correct. I ensured that the `ORDER BY` clause is present, which is required for pagination to work correctly. I also verified that the `ProductID` column is unique and indexed. Based on the output, it seems like the pagination is being skipped entirely. In my previous attempts, I even tried running the query without the parameters to see if there were any hardcoded values affecting the results, but that didn’t change anything. I also looked into the compatibility level of the database. It is set to 150, which supports `OFFSET-FETCH`. I'm at a loss here, and I need to find any documentation indicating what could be wrong. Has anyone else experienced this, or does anyone have insights into what I might be doing wrong with the `OFFSET-FETCH` implementation? I'm working on a web app that needs to handle this. What's the best practice here? Has anyone dealt with something similar? For context: I'm using T-Sql on Linux. I appreciate any insights!