Pergunta

I'm using a left join to check if certain types of information have been stored in the database.

I'm wondering if a lot of resources will be wasted if the joined table contains a lot of rows which matches the JOIN clause.

i.e.:

SELECT Applications.*
FROM Applications
LEFT JOIN SomeFeatureRows ON (SomeFeatureRows.ApplicationId = Applications.Id)
WHERE SomeFeatureRows.Id IS NULL;

Do the DB scan through all rows in SomeFeatureRows to see if there is a row where Id is NULL?

I just want to check if there is a row or not in that table (with the specified application id).

Edit, might as well include the real SQL statement:

SELECT organizations.id AS OrganizationId, 
       organizations.Name, 
       Application.Id as ApplicationId,
       Application.Name as ApplicationName,
       Account.id       AS AccountId, 
       Account.Email, 
       Account.Username ,
       SentEmails. SentAtUtc 
FROM   organizations 
       INNER JOIN applications ON ( organizations.id = applications.organizationid ) 
       LEFT JOIN Incidents ON ( organizations.id = Incidents.organizationid ) 
       LEFT JOIN SentEmails ON ( organizations.id = SentEmails.organizationid AND EmailTypeName = 'IncidentsReminder') 
       CROSS apply (SELECT accounts.id, 
                           accounts.email, 
                           accounts.username 
                    FROM   accounts, 
                           organizationmembers 
                    WHERE  accounts.id = organizationmembers.accountid 
                           AND organizationmembers.organizationid = 
                               organizations.id) 
       Account 
WHERE  Incidents.id IS NULL
Foi útil?

Solução

Here is a very good article explaining the different techniques and performance benefits of using: Not Exists vs. Not In vs. Left join / Is null

To summarize:
LEFT JOIN / IS NULL is less efficient, since it makes no attempt to skip the already matched values in the right table, returning all results and filtering them out instead. Use Not Exists for best performance as it will create a LEFT ANTI SEMI JOIN in the execution plan.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top