SQL
LINQ
Pagination
Database
Query Optimization

How do I write LINQ's .Skip1000.Take100 in pure SQL?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Writing equivalent SQL for LINQ's `.Skip(1000).Take(100)` involves understanding how pagination or filtering a subset is handled in SQL. The goal of this SQL operation is to skip a certain number of rows and then take a specified number of rows from the results, starting from a certain row in an ordered list of records.

Introduction

In LINQ, `.Skip(n)` is used to skip the first `n` records, and `.Take(m)` is used to take the next `m` records from the resulting set. In a SQL context, we'll convert this to achieve the same pagination effect.

SQL Pagination Strategies

SQL Server offers the following primary ways to paginate:

  1. Using OFFSET-FETCH (Standard SQL since SQL Server 2012).
  2. Using the ROW_NUMBER() function (Older SQL versions).

Method 1: OFFSET-FETCH

This method applies to SQL databases that support the ANSI SQL standard OFFSET-FETCH clause (e.g., SQL Server 2012+, PostgreSQL, etc.).

Here is how you can write pure SQL for LINQ's `.Skip(1000).Take(100)`:

  • ORDER BY some_column: To ensure the consistency and predictability of results, an `ORDER BY` clause is necessary. Without it, the SQL standard does not guarantee which records will be skipped or fetched.
  • OFFSET 1000 ROWS: Skips the first 1000 rows.
  • FETCH NEXT 100 ROWS ONLY: Fetches the next 100 rows after skipping.
  • ROW_NUMBER() OVER (ORDER BY some_column): Assigns a unique row number to each row based on the `ORDER BY` clause.
  • WHERE RowNum > 1000 AND RowNum <= 1100: Skips the first 1000 rows and limits the selection to 100 rows (resulting set is from row 1001 to 1100).
  • Performance: Always assess the impact of pagination on query performance, especially with large datasets.
  • Indexing: Ensure indexed columns are used in `ORDER BY` to optimize query speed.
  • Data Consistency: Be aware of changes in the dataset between queries which can affect consistency when paginating across sessions.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.