Note that there are some explanatory texts on larger screens.

plurals
  1. PO"Order By" in LINQ-to-SQL Causes performance issues
    primarykey
    data
    text
    <p>I've set out to write a method in my C# application which can return an ordered subset of names from a table containing about 2000 names starting at the 100th name and returning the next 20 names. </p> <p>I'm doing this so I can populate a WPF <code>DataGrid</code> in my UI and do some custom paging. I've been using LINQ to SQL but hit a snag with this long executing query so I'm examining the SQL the LINQ query is using (Query B below).</p> <p>Query A runs well:</p> <pre><code>SELECT TOP (20) [t0].[subject_id] AS [Subject_id], [t0].[session_id] AS [Session_id], [t0].[name] AS [Name] FROM [Subjects] AS [t0] WHERE (NOT (EXISTS( SELECT NULL AS [EMPTY] FROM ( SELECT TOP (100) [t1].[subject_id] FROM [Subjects] AS [t1] WHERE [t1].[session_id] = 1 ORDER BY [t1].[name] ) AS [t2] WHERE [t0].[subject_id] = [t2].[subject_id] ))) AND ([t0].[session_id] = 1) </code></pre> <p>Query B takes 40 seconds:</p> <pre><code>SELECT TOP (20) [t0].[subject_id] AS [Subject_id], [t0].[session_id] AS [Session_id], [t0].[name] AS [Name] FROM [Subjects] AS [t0] WHERE (NOT (EXISTS( SELECT NULL AS [EMPTY] FROM ( SELECT TOP (100) [t1].[subject_id] FROM [Subjects] AS [t1] WHERE [t1].[session_id] = 1 ORDER BY [t1].[name] ) AS [t2] WHERE [t0].[subject_id] = [t2].[subject_id] ))) AND ([t0].[session_id] = 1) ORDER BY [t0].[name] </code></pre> <p>When I add the <strong>ORDER BY [t0].[name]</strong> to the outer query it slows down the query.</p> <p>How can I improve the second query?</p> <hr> <p>This was my LINQ stuff Nick</p> <pre><code>int sessionId = 1; int start = 100; int count = 20; // Query subjects with the shoot's session id var subjects = cldb.Subjects.Where&lt;Subject&gt;(s =&gt; s.Session_id == sessionId); // Filter as per params var orderedSubjects = subjects .OrderBy&lt;Subject, string&gt;( s =&gt; s.Col_zero ); var filteredSubjects = orderedSubjects .Skip&lt;Subject&gt;(start) .Take&lt;Subject&gt;(count); </code></pre>
    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