Search code examples
sqlsql-server-2008sql-server-2012query-performance

SQL IN clause in where condition causing performance issue with large data


The following query works fine in my database but it is giving huge performance issues in customer DB. I know that I am using the IN clause in the where condition which is giving me this problem. But I don't know how to fix this.

declare @AccountId int
set @AccountId =  1200
declare @IsLinkedAccountsNotes bit
set @IsLinkedAccountsNotes =1
declare @EventType varchar(100)
set @EventType = ''

SELECT
        u.loginName as InteractionLoginName,
        u.userName as InteractionUserName,
        e.*
    FROM
        lat.events e
        INNER JOIN dbo.MasterEvents me ON me.EventId = e.EventId    
        LEFT JOIN dbo.Users u ON e.UserId = u.ID 
    WHERE
        (me.AccountId = @AccountId OR
        (@IsLinkedAccountsNotes = 1 AND me.AccountId IN (SELECT DISTINCT [number] FROM dbo.Linking_LinkedAccounts WHERE linked_number = @AccountId) AND e.EventType = 'AccountNoteAdded'))

I know that the second condition in where clause is causing the problem. And I have seen in various posts that using a join will solve this problem. But I am not getting how to use join inside where condition. Or is there any other approach for the same.

Please help.


Solution

  • Your problem is likely that this is a "catch all query". You can try splitting the cases out as below

    SELECT u.loginName AS InteractionLoginName,
           u.userName  AS InteractionUserName,
           e.*
    FROM   lat.events e
           INNER JOIN dbo.MasterEvents me
                   ON me.EventId = e.EventId
           LEFT JOIN dbo.Users u
                  ON e.UserId = u.ID
    WHERE  me.AccountId = @AccountId
    UNION ALL
    SELECT u.loginName AS InteractionLoginName,
           u.userName  AS InteractionUserName,
           e.*
    FROM   lat.events e
           INNER JOIN dbo.MasterEvents me
                   ON me.EventId = e.EventId
           LEFT JOIN dbo.Users u
                  ON e.UserId = u.ID
    WHERE  @IsLinkedAccountsNotes = 1
           AND e.EventType = 'AccountNoteAdded'
           AND me.AccountId IN (SELECT [number]
                                FROM   dbo.Linking_LinkedAccounts
                                WHERE  linked_number = @AccountId
                                       AND [number] <> @AccountId)