Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did the following linq to sql query generate a subquery?

Tags:

c#

linq-to-sql

I did the following query:

var list = from book in books
          where book.price > 50
          select book;

list = list.Take(50);

I would expect the above to generate something like:

SELECT top 50 id, title, price, author
FROM Books
WHERE price > 50

but it generates:

SELECT
[Limit1].[C1] as [C1]
[Limit1].[id] as [Id], 
[Limit1].[title] as [title], 
[Limit1].[price] as [price], 
[Limit1].[author]
FROM (SELECT TOP (50) 
             [Extent1].[id] as as [Id], 
             [Extent1].[title] as [title], 
             [Extent1].[price] as [price], 
             [Extent1].[author] as [author]
      FROM Books as [Extent1]
      WHERE [Extent1].[price] > 50
     ) AS [Limit1]

Why does the above linq query generate a subquery and where does the C1 come from?

like image 579
Xaisoft Avatar asked Dec 14 '09 19:12

Xaisoft


People also ask

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

How do subqueries work?

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

What does LINQ Select Return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.


1 Answers

Disclaimer: I've never used LINQ before...

My guess would be paging support? I guess you have some sort of Take(50, 50) method that gets 50 records, starting at record 50. Take a look at the SQL that query generates and you will probably find that it uses a similar sub query structure to allow it to return any 50 rows in a query in approximately the amount of time that it returns the first 50 rows.

In any case, the nested sub query doesn't add any performance overhead as it's automagically optimised away during compilation of the execution plan.

like image 199
Justin Avatar answered Oct 22 '22 23:10

Justin