1

Assuming I have a table "MyTable" that contains 10'000 records; when I run the query below to obtain just 25 records: is it selecting all 10'000 records first before to return just 25 of them, or will the query be optimized automatically by the SQL parser?

SELECT *
FROM
   (
    SELECT HPE.ID, 
           HPE.EventTitle, 
           HPE.EventDate, 
           HPE.EventLocation, 
           HPE.SortOrder,
           CASE HPE.FlagShowInShop
               WHEN 1 THEN 'Yes'
               ELSE 'No'
           END AS FlagShowInShop, 
           HPE.ShowFrom, 
           HPE.ShowTo, 
           HPE.FK_Language, 
           HPE.FK_Region, 
           ISNULL (EG.Name, 'BIG EVENTS') AS EventGenre, 
           ROW_NUMBER () OVER
                              (ORDER BY HPE.FK_EventGenre_Value, 
                                        HPE.SortOrder
                              ) AS RowNum
      FROM [MyTable] AS HPE
           LEFT JOIN [MySecondTable] AS EG ON HPE.FK_EventGenre_Value=EG.Value
   ) AS HomePageEventsWithRowNumber
WHERE RowNum BETWEEN 1 AND 25
1
  • 1
    best option is to check the actual execution plan. it may depend on indexes that you have, but using rownumber would normally have to evaluate the entire table to order the data to get the relevant rows.
    – Tanner
    Oct 17, 2016 at 7:53

1 Answer 1

2

In your case the inner select must be executed to find the rows 1 to 25. But - if there is an index and this can be predicted - I'd assume, that the outer query will be taken into consideration. If the engine can predict the frist 25 rows, it will try to reduce the work.

What ever you do or check there is no sure prediction. You might check the execution plan and find out, which is executed first, but the next time (or with another version of SQL Server) this might be different.

SQL Server is not a procedural engine

You do not write kind of a program which is executed in your given order. You tell the engine what you'd like to get, and the engine finds the best way to achieve this.

A sub-select (probably) will be executed first, if its values are needed somewhere in the outer query. If the outer query allows great reduction of master rows with a given filter, the engine (probably) will bind child rows as late as possible.

This depends on many circumstances you cannot fully control.

What you could do, but really should avoid:

Well, you could force the engine to work down your order by using procedural approaches. In this case you could shuffle the result of the query you'd like to execute first into a table and then use this table in the next query.

But - almost ever - this is something one shouldn't even think of. The engine really works pretty effectively...

Come into the bright light of set-based thinking!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.