Skip to content

Instantly share code, notes, and snippets.

@dunhamjared
Last active November 8, 2022 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dunhamjared/cb40bbf294ed6f8e48bd60010a31b4f3 to your computer and use it in GitHub Desktop.
Save dunhamjared/cb40bbf294ed6f8e48bd60010a31b4f3 to your computer and use it in GitHub Desktop.
SQL Server No Order By Proposed Update and Benchmarks

SQL Server 2012 introduced the fetch and offset feature.

Laravel started using FETCH and OFFSET in 2021 -- but only when you include an order by: laravel/framework#39863

Laravel also only officially supports 2017 and up: https://laravel.com/docs/9.x/database#introduction

This PR updates the query builder to also use FETCH and OFFSET for queries that do not include an order by: laravel/framework#44458

Benchmarks

Reduces average query time by 33%:

image

Lower is better, see: https://github.com/dunhamjared/laravel-benchmarks

Improves the actual execution plan:

Current method:

select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num between 9991 and 10000 order by row_num;

image

Proposed method:

select * from [users] order by (SELECT 0) offset 9990 rows fetch next 10 rows only;

image

sql avg max min median total
CURRENT 0.003505183 0.066704035 0.001147032 0.003000021 3.505183458
CURRENT 0.003534113 0.069150925 0.001194 0.002942562 3.534113169
CURRENT 0.0036104 0.074589014 0.000999928 0.003091335 3.610399723
CURRENT 0.003870097 0.08541894 0.001240015 0.003027081 3.870097399
PROPOSAL 0.00234483 0.056790113 0.001209021 0.002015948 2.344829559
PROPOSAL 0.002432414 0.070445061 0.001087904 0.001985431 2.432413578
PROPOSAL 0.003140342 0.05231595 0.001179218 0.002126932 3.140341759
PROPOSAL 0.002395779 0.069509983 0.001082897 0.002120018 2.395778894
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment