Explain Codes LogoExplain Codes Logo

How to skip the first n rows in sql query

sql
sql-performance
sql-tuning
sql-execution-plans
Nikita BarsukovbyNikita Barsukov·Nov 1, 2024
TLDR

To skip the top n rows, use the following templates:

  • PostgreSQL/MySQL using the OFFSET clause:
    SELECT * FROM table LIMIT 10 OFFSET n; -- Replace 'n' with the count of runners faster than you
  • SQL Server/Azure using OFFSET-FETCH:
    SELECT * FROM table ORDER BY column OFFSET n ROWS FETCH NEXT 10 ROWS ONLY; -- You're not first, but you're next after 'n'

These SQL statements allow you to effectively bypass the first n records in your database.

Battle-tested techniques

The use of ROW_NUMBER() with SQL Server

For row-specific tasks, the ROW_NUMBER() function provides granular control:

WITH NumberedRows AS ( SELECT ROW_NUMBER() OVER (ORDER BY column) AS 'Row', * FROM table ) SELECT * FROM NumberedRows WHERE Row > n; -- Chuck Norris starts at row 'n+1'

In this setup, ORDER BY ensures the consistent arrangement of rows — it sets the official ranking for the SQL Olympics!

SQL Server (pre-2012): Subquery and TOP keyword

For older SQL Server versions (pre-2012), OFFSET-FETCH isn't available, but we've got a plan B:

SELECT * FROM table WHERE ID NOT IN ( SELECT TOP n ID FROM table ORDER BY column ); -- 'Back to the Future' SQL style

For Oracle 12.1 and later, OFFSET makes life easier:

SELECT * FROM table ORDER BY column OFFSET n ROWS FETCH FIRST 10 ROWS ONLY; -- Oracle style, machiavellian edition

Handling large datasets: Tuning for performance

Performance is key when processing large datasets. Make sure that your query tuning game is strong and your execution plans aren't plotting against you!

In-depth discussion and essential considerations

User requirements, the twists and turns of SQL

Match your SQL strategy to the specific requirements of the task. Dynamic parameters can turn your WHERE clause into an agility course:

-- User-interactive row skipping SELECT * FROM table WHERE condition = @UserInput OFFSET n ROWS; -- User-controlled 'avoid the first n'

Uncharted territory, unordered rows

Understand that SQL tables are unordered sets without an explicit ORDER BY clause. The phrase "first n rows" is a myth unless we make an ordering rule—the SQL equivalent of "The first rule of Fight Club is..."

Natural order, making peace with chaos

By adding a 'Num' (number) column, you can introduce a sense of natural and predictable ordering into the chaos. Consider it a brand-new race track for all your rows.