I have been looking at this statement for the last day but I've been unable to work out the best way to improve it. So, I thought I would reach out to the wider community for some advise.
SELECT [FLD6]
FROM (
SELECT TOP (25) [EVENTS].[EV_SEQ] AS [FLD6]
FROM [EVENTS] WITH (NOLOCK)
LEFT OUTER JOIN [TASKS] AS [Pe2da3fbc7e676e2b21201605598f3] WITH (NOLOCK) ON [EVENTS].[EV_FKEY_TA_SEQ] = [Pe2da3fbc7e676e2b21201605598f3].[TA_SEQ]
LEFT OUTER JOIN [TASKS] AS [Pd361fcc2673fdd885d288ab24f6f5] WITH (NOLOCK) ON [EVENTS].[EV_FKEY_TA_SEQ] = [Pd361fcc2673fdd885d288ab24f6f5].[TA_SEQ]
WHERE (
(
[EVENTS].[EV_SEQ] > 0
OR [EVENTS].[EV_SEQ] IS NULL
)
)
AND (
[Pd361fcc2673fdd885d288ab24f6f5].[TA_FKEY_CTR_SEQ] = 0
OR [Pd361fcc2673fdd885d288ab24f6f5].[TA_FKEY_CTR_SEQ] IS NULL
OR [Pd361fcc2673fdd885d288ab24f6f5].[TA_FKEY_CTR_SEQ] = ''
OR [Pd361fcc2673fdd885d288ab24f6f5].[TA_FKEY_CTR_SEQ] IN (
SELECT [ContractGroupsContract].[CTR_SEQ]
FROM [ContractGroupsContract]
INNER JOIN [AccountContractGroups] ON [AccountContractGroups].[ContractGroupId] = [ContractGroupsContract].[ContractGroupId]
WHERE [AccountContractGroups].[AccountId] = 2536
AND [AccountContractGroups].[Deleted] = 0
AND [ContractGroupsContract].[Deleted] = 0
)
)
ORDER BY [EVENTS].[EV_SEQ] ASC
) [EVENTS]
Here is the Execution Plan: https://www.brentozar.com/pastetheplan/?id=H1zF0Dpqi
I have made sure that all statistics are up to date and all indexes are not massively fragmented. I also don't know why the application generates two LEFT JOINS
on the TASKS
table, that's something that I'm liaising with the Development team about.
The query originally took around 8 minutes to execute, until I added an index on the EVENTS
table, key value EV_SEQ
, EV_FKEY_TA_SEQ
. Now it completes in around 5 minutes, but it's still not acceptable.
The database itself has LEGACY_CARDINALITY_ESTIMATOR
switched on. I disabled this option on the database and it doesn't seem to have effected the performance at all, so I have rolled it back for now.
SQL Edition: SQL Server 2016 Standard
Index Definitions in Use
Events = [2 KEYS] EV_SEQ {int 4}, EV_FKEY_TA_SEQ {int 4}
Tasks = [3 KEYS] TA_SEQ {int 4}, TA_FKEY_CTR_SEQ {int 4}, TA_DATE {datetime 8}
ContractGroupsContract = [3 KEYS] CTR_SEQ {int 4}, ContractGroupId {bigint 8}, Deleted {tinyint 1}
AccountContractGroups = [4 KEYS] AccountId {bigint 8}, Deleted {tinyint 1}, ContractGroupId {bigint 8}, AccountContractGroupId {bigint 8}
Any thoughts on what could be done here to improve this further?
Thanks!