Performance difference between left join and SQL subquery

159 views Asked by At

The question might be trivial but still, what's the differences in SQL Server queries like this:

 SELECT t1.*, t2.Value
 FROM [User] t1
 LEFT JOIN [UserStory] t2 ON t1.Id = t2.Id

vs

 SELECT 
     t1.*, 
     (SELECT Value FROM [UserStory] t2 WHERE t1.Id = t2.Id) 
 FROM User t1

First of all from performance POV.

I see no cases when the second option will be suitable since as I can see for each record in t1, the server should call a separate query against t2 and I guess it's hard to optimize anything here.

Can someone comment on whether there are any cases where the second option with subquery might be preferable against adding a new table to join.

Added execution plan: enter image description here

Update: If I'm reading executing plan correctly, the performance in both cases will be the same? (put aside possible error in case if subquery returns more than 1 record)

1

There are 1 answers

6
David Browne - Microsoft On

any cases where the second option with subquery might be preferable against adding a new table to join

The scalar subquery will fail if more than one row is returned. So, that query contains additional information for the query optimizer and for a future developer who is trying to understand how the query works.

So, if you know that only one row will be returned, but that's not obvious from the table structure, the scalar subquery is preferable.