Is there a way to make the faster ordered SQL TOP 1 query as Entity Framework query?

entity-framework entity-framework-core sql sql-server

Question

Here is two ways to get the top 1 row from a table ordered

Slower:

select top 1 * 
from movies m
where m.Distributor = 'any'
order by m.IMDB_Rating desc

Faster:

select top 1 m.* 
from movies m
left join movies m2 on m.Distributor = m2.Distributor 
                    and m2.IMDB_Rating > m.IMDB_Rating
where m.Distributor = 'any' 
  and m.IMDB_Rating is not null 
  and m2.id is null 

The first one is simpler, but the second one is faster.

So, is there a way to make the second query using Entity Framework?

If there is no way to make this query in EF or EF Core, could you give me another query as fast as the second one if it is possible?

I'm sorry if it is duplicated, I can't find any answer to my question

Thanks a lot!

1
0
2/8/2020 4:36:22 PM

Popular Answer

For this query:

select top (1) m.*
from movies m
where m.Distributor = 'any'
order by m.IMDB_Rating desc;

You want an index on movies(Distributor, IMDB_Rating desc).

I cannot speak to why the second version would be faster.

1
2/8/2020 4:08:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow