Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance or functional difference between these two SQL statements?

Tags:

sql

sql-server

I'm maintaining someone else's SQL at the moment, and I came across this in a Stored Procedure:

    SELECT      
    Location.ID, 
    Location.Location, 
    COUNT(Person.ID) As CountAdultMales
FROM        
    Transactions INNER JOIN 
    Location ON Transactions.FKLocationID = Location.ID INNER JOIN  
    Person ON Transactions.FKPersonID = Person.ID 
     AND DATEDIFF(YEAR, Person.DateOfBirth, GETDATE()) >= 18 AND Person.Gender = 1
WHERE
    ((Transactions.Deleted = 0) AND
    (Person.Deleted = 0) AND
    (Location.Deleted = 0))

Is there any difference between the above and this (which is how I would write it)

SELECT      
    Location.ID, 
    Location.Location, 
    COUNT(Person.ID) As CountAdultMales
FROM        
    Transactions INNER JOIN 
    Location ON Transactions.FKLocationID = Location.ID INNER JOIN  
    Person ON Transactions.FKPersonID = Person.ID
WHERE
    ((Transactions.Deleted = 0) AND
    (Person.Deleted = 0) AND
    (Location.Deleted = 0) AND
    (DATEDIFF(YEAR, Person.DateOfBirth, GETDATE()) >= 18) AND
    (Person.Gender = 1))

Personally, I find putting the conditions in the WHERE clause most readable, but I wondered if there were performance or other reasons to "conditionalise" (if there is such a word) the JOIN

Thanks

like image 309
Edwardo Avatar asked Feb 01 '26 04:02

Edwardo


1 Answers

With an inner join this wont really make much of a difference as SQL has a query optimiser which will do its best to excecute the query in the most efficiant way (not perfect).

If this was an outer join it could make a difference though so its something to be aware of

like image 136
Dev N00B Avatar answered Feb 03 '26 19:02

Dev N00B