0

In terms of performance and translation to SQL query is there any difference between these two queries?

var query1 = 
    from customer in db.Customers.Where(x => x.CustomerName == "Max")
    join order in db.Orders on customer.Id equal order.CustomerId
    select customer


var query2 = 
    from customer in db.Customers
    join order in db.Orders on customer.Id equal order.CustomerId
    where customer.CustomerName == "Max"
    select customer
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
brk
  • 427
  • 4
  • 10
  • 2
    Nice question. You could compare the generated SQL and profile it :-) – Stefan Mar 31 '22 at 13:53
  • As I know, it should be no difference. But it depends on quality of LINQ Translator. EF Core should generate two identical queries. – Svyatoslav Danyliv Mar 31 '22 at 13:56
  • 1
    Using joins on top of an ORM like EF Core means your entities are missing relations. You shouldn't need either query. Your `Customer` class should have an `Orders` collection. You only need `db.Customers.Where(c=>c.CusomerName==...)` to load all matching customers and then lazily access their orders. If you want to eagerly load all orders too, add `Include(c=>c.Orders)`, eg `db.Customers.Include(c=>c.Orders).Where(...)` – Panagiotis Kanavos Mar 31 '22 at 14:12
  • 1
    TL;DR; For an inner join (without `DefaultIfEmpty`) the results are exactly the same, and SQL Server (as any good RDBMS) is capable of transforming to the most efficient version. If you check the query plans you will see this is the case. – Charlieface Mar 31 '22 at 14:36
  • @Charlieface, bad duplicate. LINQ != SQL – Svyatoslav Danyliv Mar 31 '22 at 15:27
  • @SvyatoslavDanyliv Linq2Objects But OP is using Linq to SQL Server, so yes that is definitely applicable. The above queries will almost perfectly translate into the equivalent SQL, so the first will be a `WHERE` then `JOIN`, and the second will be the opposite – Charlieface Mar 31 '22 at 15:32

0 Answers0