Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a better way to sort this query?
    primarykey
    data
    text
    <p>We generate a lot of SQL procedurally and SQL Server is killing us. Because of some issues documented <a href="http://sqladvice.com/forums/permalink/18496/22931/ShowThread.aspx#22931" rel="nofollow noreferrer">elsewhere</a> we basically do SELECT TOP 2 ** 32 instead of TOP 100 PERCENT.</p> <p>Note: we <em>must</em> use the subqueries.</p> <p>Here's our query:</p> <pre><code>SELECT * FROM ( SELECT [me].*, ROW_NUMBER() OVER( ORDER BY (SELECT(1)) ) AS rno__row__index FROM ( SELECT [me].[id], [me].[status] FROM ( SELECT TOP 4294967296 [me].[id], [me].[status] FROM [PurchaseOrders] [me] LEFT JOIN [POLineItems] [line_items] ON [line_items].[id] = [me].[id] WHERE ( [line_items].[part_id] = ? ) ORDER BY [me].[id] ASC ) [me] ) [me] ) rno_subq WHERE rno__row__index BETWEEN 1 AND 25 </code></pre> <p>Are there better ways to do this that anyone can see?</p> <p><strong>UPDATE</strong>: here is some clarification on the whole subquery issue:</p> <p>The key word of my question is "procedurally". I need the ability to reliably encapsulate resultsets so that they can be stacked together like building blocks. For example I want to get the first 10 cds ordered by the name of the artist who produced them and also get the related artist for each cd.. What I do is assemble a monolithic subselect representing the cds ordered by the joined artist names, then apply a limit to it, and then join the nested subselects to the artist table and only then execute the resulting query. The isolation is necessary because the code that requests the ordered cds is unrelated and oblivious to the code selecting the top 10 cds which in turn is unrelated and oblivious to the code that requests the related artists.</p> <p>Now you may say that I could move the inner ORDER BY into the OVER() clause, but then I break the encapsulation, as I would have to SELECT the columns of the joined table, so I can order by them later. An additional problem would be the merging of two tables under one alias; if I have identically named columns in both tables, the select me.* would stop right there with an ambiguous column name error.</p> <p>I am willing to sacrifice a bit of the optimizer performance, but the 2**32 seems like too much of a hack to me. So I am looking for middle ground.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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