Explain Codes LogoExplain Codes Logo

Row Offset in SQL Server

sql
performance
best-practices
pagination
Anton ShumikhinbyAnton Shumikhin·Jan 17, 2025
TLDR

To skip and fetch rows in SQL Server, use OFFSET and FETCH NEXT. As an instance, to bypass the first 10 rows and obtain the next 5:

SELECT your_columns FROM your_table ORDER BY your_order_column OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;

To guarantee consistent output, it's crucial to ORDER BY the data. This approach works from SQL Server 2012 onwards.

Using select statement smartly

Avoid SELECT * like the plague. Instead, specify the particular columns you need. It reduces the amount of data SQL Server needs to process, boosting performance, especially with large datasets.

Overcoming Paging obstacles in SQL Server 2005-2008

If you're dealing with SQL Server versions before 2012, ROW_NUMBER() comes to the rescue. Couple that with BETWEEN for efficient pagination:

-- Some say aging like a fine wine -- Let's row-number the heck out of this! WITH RowNumberedData AS ( SELECT ROW_NUMBER() OVER (ORDER BY ID) AS RowNum, your_columns FROM your_actual_table_name ) SELECT your_columns FROM RowNumberedData WHERE RowNum BETWEEN @Offset AND (@Offset + @Fetch - 1);

A smarter approach for initial fetch

Use the TOP keyword to swiftly grab the initial set of rows. This way, we can decrease the load:

-- Top o' the morning to ya SELECT TOP (25) your_columns FROM your_actual_table_name ORDER BY your_key_column;

Remember, a good index is your best friend when working with arbitrary page access and combined ROW_NUMBER() + BETWEEN in SQL Server 2005-2008 R2.

Offset-Fetch: A double-edged sword

While OFFSET-FETCH is an efficient method for row offsetting, it's vital to perform regular performance tests. As with any powerful tool, it requires careful handling to avoid possible pitfalls.

Ancient warriors of SQL Server 2000

When neither OFFSET-FETCH nor ROW_NUMBER() work well, dust off SQL Server 2000 and its techniques for navigating large result sets. In such cases, SQL cursors might be your weapon of choice.

Offset-fetch Vs. API pagination

Who wins depends on your server's workload and the frequency of queries. Make sure you have configured your indexing properly for maximum pagination performance.

Tips for old SQL servers

Users with SQL Server 2000 can use tools such as temp tables, cursors, and dynamic SQL for pagination. These ancient warriors might still save your day when dealing with legacy systems.