I have a table SpecialOffers and table for special offer items called SOItems
And i want to get the special offer for a specific item if i found it so first i did this :
IF EXISTS(SELECT * FROM SOTtems WHERE ItemType = 2 AND Itemid = @id)
BEGIN
INSERT INTO #SO
SELECT * FROM SpecialOffers so
INNER JOIN SOItems soi ON so.Id = soi.SpecialOfferID
WHERE soi.ItemType = 2 AND soi.Itemid = @id
END
But then to get rid of INNER JOIN because i thought it’s better for performance i did this :
DECLARE @specialOfferID INT
SET @specialOfferID = (SELECT SpecialOfferID FROM SOTtems WHERE ItemType = 2 AND Itemid = @id)
IF @specialOfferID IS NOT NULL
BEGIN
INSERT INTO #SO
SELECT * FROM SpecialOffers so
WHERE ID = @specialOfferID
END
So which is more efficient and better for performance to execute more sql queries or use join for this example and in general
Note : in the stored procedure i am writing i have to this more than 6 times that is why i asked u 🙂
thanks
This hand optimization is likely unnecessary, since the optimizer is more than capable of handling this.
You can put both into SSMS and run them together and look at relative costs in the the execution plan.
Avoiding joins is not usually a first step in optimizing.
My first step is usually to look at the indexing strategy and ensure I haven’t left out the basic indexes and then look at execution plans and see if there are any glaring problems.
Then I don’t optimize until I have an actual performance problem – and then only after understanding what’s really causing the performance issue.
I would actually simplify it down to only:
That’s it – no EXISTS check or anything else – the inner join means that the check for existence is redundant, because this won’t insert anything otherwise. This makes for more maintainable code in one sense, because you won’t need to duplicate the condition if it changes, and code in a join is not likely to be altered accidentally. On the other hand, if the join does get altered, it could have more serious repercussions.
Note, you can still write this as a WHERE version without using the EXISTS check as well.
Less code typically means less places for bugs to hide.