tags:

views:

24

answers:

2

Hi all, i am investigating into the way LINQ gets mapped to SQL, and I have some troubles getting a simple thing.

There is a table sessions that holds one row per user login. Consider the following SQL


SELECT COUNT(*) AS c
FROM sessions
GROUP BY sessions.user_id
ORDER BY c DESC

I am using LINQPad to test LINQ-to-SQL transformations.

The strait-forward


    from s in Sessions group s by s.User_id into logins 
    orderby logins.Count() descending
    select new { c = logins.Count() }

gives me


SELECT [t1].[value2] AS [c]
FROM (
    SELECT COUNT(*) AS [value], COUNT(*) AS [value2]
    FROM [sessions] AS [t0]
    GROUP BY [t0].[user_id]
    ) AS [t1]
ORDER BY [t1].[value] DESC

The modified


    (from s in Sessions group s by s.User_id into logins 
    select new { c = logins.Count() }).OrderByDescending(v => v.c)

gets mapped to


SELECT [t1].[value2] AS [c]
FROM (
    SELECT COUNT(*) AS [value], COUNT(*) AS [value2]
    FROM [sessions] AS [t0]
    GROUP BY [t0].[user_id]
    ) AS [t1]
ORDER BY [t1].[value] DESC

I just can't get this optimal output. Is there a way?
Or, maybe, I shouldn't be concerned as the SQL will get optimized anyway?

A: 

There is "nothing" wrong with that query, it wont COUNT the rows twice if thats what you are worried about.

Fabian
yes, and what about the cascaded selects?
ULysses
Thats the way LINQ does ordering. The actual query builder will optimize that. Im quite sure that if you optimize that query by hand that it will give the exact same query execution plan.
Fabian
A: 

Or, maybe, I shouldn't be concerned as the SQL will get optimized anyway?

Compare the execution plans of the "optimal" sql and the generated sql. (Sql Studio - click on "display estimated execution plan")


By inspection and drawing upon my years of clicking that button - the generated subquery presents no concern at all.

Even this query should be fine (meaning: costs no additional io)

SELECT [t1].[value2] AS [c] 
FROM ( 
    SELECT COUNT(*) AS [value], COUNT(*) AS [value2] 
    FROM [sessions] AS [t0] 
    GROUP BY [t0].[user_id] 
    ) AS [t1] 
ORDER BY [t1].[value] DESC 
David B