Returning Maximum value from 1-to-many association

Today I was working with two entities and i wanted to return the maximum value in the many table for each record in the parent table. There are several approaches to returning the desired data but since my tables had lots of records i wanted to explore different queries and compare which one generates a better sql and gives me better performance.

To illustrate the example i will use subset of columns. In the figure below i have a product entity which has 1-to-many association with ProductPrice entity. For each product, I wanted to return the maximum price. This is a very common scenario in ecommerce companies like ours where we have different price structures depending upon if you are buying from our website, catalog or just a retail store.

image

 

I inserted some sample data into the tables using the entities available on the model.

image

One way to write query is by starting with product entity and for each product find its maximum price. Second way is to start with ProductPrice entity and group the prices by Name in the Product entity. The two approaches are shown below.

image

The first linq query generates a co-related query meaning for each outer record in Products table, we query query the ProductPrices table that many times. However the second query is translated to a group by query with max operator. I tried capture the execution time for both to see which one performs better and i found the first linq query which starts from Product entity is a bit faster.

First Query

image

SQL Server Execution Times:
   CPU time = 78 ms,  elapsed time = 99 ms.

Second Query

image

SQL Server Execution Times:
  CPU time = 156 ms,  elapsed time = 180 ms.

I wonder if starting from primary table and for each record in the primary table, hitting the many table is always faster then querying the many table directly and then grouping the result by a column in the primary table.

No Comments