I'm using the latest versions of SQL Server and EF Core in my .NET 7 project.
I have a table Deposits
with 4 million rows. I encountered a small issue and I'd like to know how to address it.
I have a very simple query:
var deposits = await dataContext.Deposits
.Where(d => d.OwnerId == userId
&& d.DepositReason == DepositReason.Purchase)
.Select(p => p.Id)
.OrderByDescending(id => id)
.ToListAsync();
I noticed that it takes a very long time to execute (slightly over 10 seconds).
After some thinking, I swapped the conditions in the query:
Before:
d.OwnerId == userId
&& d.DepositReason == DepositReason.Purchase
After:
d.DepositReason == DepositReason.Purchase
&& d.OwnerId == userId
The query started executing in about 8 milliseconds (attached a screenshot).
Okay, I built and deployed it to production, everything was fine, and the query was executing quickly. However, after a few hours, it seems that SQL Server changed the execution plan or something similar, and the query started taking around 11 seconds to execute again.
Moreover, through SSMS it has no difference if I execute
select *
from deposits
where DepositReason = 2
and OwnerId = 1
or
select *
from deposits
where OwnerId = 1
and DepositReason = 2
It's always fast.
I would really like to know how to deal with such an anomaly. Please, if anyone understands how this works and what can be done, share your knowledge. Thank you!
The slowest query:
SELECT [d].[Id] FROM [Deposits] AS [d] WHERE [d].[OwnerId] = @__userId_0 AND [d].[DepositReason] = CAST(2 AS tinyint) ORDER BY [d].[Id] DESC