ORDER BY OFFSET FETCH子句中NEXT与FIRST的区别及适用时机
Great question! Let's break this down clearly since it's a common point of confusion given how similar the two keywords behave.
First, the core truth
In SQL Server (including the version used with AdventureWorks2016), FETCH FIRST n ROWS ONLY and FETCH NEXT n ROWS ONLY are functionally identical. That’s exactly why your two test queries returned the same results—they do the exact same thing: skip the number of rows specified by OFFSET, then return the next n rows from the ordered result set.
Why do both exist?
The dual keywords exist for SQL standard and cross-database compatibility:
FETCH FIRSTaligns with the SQL:2008 standard, which is supported by many databases like PostgreSQL, Oracle, and later versions of DB2.FETCH NEXTwas originally popularized by older DB2 versions, and SQL Server added support to make it easier for developers migrating from that ecosystem to adapt smoothly.
When to use which?
Since their functionality is identical, the choice mostly comes down to context and personal/team preference:
- SQL Server-only code: Use whichever you or your team prefers. Many teams pick one to maintain consistency across their codebase.
- Cross-database compatibility: If you might need to run your query on other databases, lean into
FETCH FIRST—it’s more widely adopted across standard-compliant systems. - Readability preference:
- When
OFFSET 0 ROWS(i.e., you’re just taking the top N rows),FETCH FIRSTreads more naturally: "Fetch the first 10 rows". - When
OFFSETis greater than 0,FETCH NEXTcan feel more intuitive: "Skip 10 rows, then fetch the next 10".
- When
For example:
-- Intuitive for "top 10" scenario SELECT LastName + ' ' + FirstName FROM Person.Person ORDER BY LastName ASC OFFSET 0 ROWS FETCH FIRST 10 ROWS ONLY; -- Intuitive for "skip then take" scenario SELECT LastName + ' ' + FirstName FROM Person.Person ORDER BY LastName ASC OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
At the end of the day, there’s no functional difference—pick the one that makes your code clearer for whoever will read it.
内容的提问来源于stack exchange,提问作者helpME1986

