Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich is faster a select sub-query or a left outer join in a paginated result set
    primarykey
    data
    text
    <p>When querying with MSSQL what is the most efficient way to grab a single column from a computed table and connect it to a result set.</p> <p>Tables: <code>mytable</code> = 20k rows index on <code>mytable.col1</code>, <code>othertable</code> = 30k rows, no index on <code>othertable.col1</code></p> <p><strong>Inline Query</strong> - Runs an query in the select statement</p> <pre><code>SELECT * FROM ( SELECT col1, col2, col3, col4 = (SELECT min(col5) FROM othertable o WHERE m.col1 = o.col1) row = ROW_NUMBER() OVER(ORDER BY somerow) FROM mytable m ) as paged WHERE row BETWEEN 1 AND 25 </code></pre> <p><strong>Join Query</strong> - Joins our table onto the computed table</p> <pre><code>SELECT * FROM ( SELECT col1, col2, col3, o2.col5again row = ROW_NUMBER() OVER(ORDER BY somerow) FROM mytable m JOIN (SELECT col1, min(col5) as col5again FROM othertable o GROUP BY col1) as o2 ON o2.col1 = m.col1 ) as paged WHERE row BETWEEN 1 AND 25 </code></pre> <p>My gut instinct was the <code>JOIN</code> was faster. Yet, upon testing the inline query would finish in an average of 7 seconds while the other query would take >30 seconds when executed in MSSQL studio. </p> <ol> <li>Is using an inline select query really the best way to inject the single column?</li> <li>Does the query optimized wait to run the inline <code>SELECT()</code> statement until after the results have been paged, would that explain the different in running time?</li> </ol> <p>FYI: In my specific example we added an index to <code>othertable.col1</code> and it reduced the query time to 0s, but this question focuses more on whether the JOIN versus SELECT() is better.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload