SQL Server Join hints execution plan

Hi Friends,

We can control SQL Server query optimizer’s decision by forcing any T-SQL queries to use a specific join type. In today’s post we will explore SQL Server Join hints and their impact on execution plans.

Let us begin with following sql query and see what the default choice of query optimizer is.

USE [AdventureWorks2012]

SELECT PR.FirstName,PR.LastName
FROM Person.Person AS PR
JOIN Person.BusinessEntityAddress BE
ON PR.BusinessEntityID = BE.BusinessEntityID

HashJoinQueryPlan

 

HashJoinToolTip

Hash Match join is the optimum and efficient plan operator for the statement(s) used in our example according to SQL Server query optimizer. We can force optimizer to use any of the available join algorithms i.e. Hash Joins, Merge Joins (read here Part1, Part2) or Nested Loop (read here Part1, Part2) Joins at query level or at join level using Join Hints. Let’s do that now.

USE [AdventureWorks2012]

SELECT PR.FirstName,PR.LastName
	FROM Person.Person AS PR
	JOIN Person.BusinessEntityAddress BE
	ON PR.BusinessEntityID = BE.BusinessEntityID
OPTION (LOOP JOIN)

NestedLoopJQueryPlan

NestedLoopToolTip

In the example query optimizer decided to choose Hash Join in the normal circumstances but we forced optimizer to exclude Hash Join and to use Nested Loop Join. This operation reduced Estimated Operator Cost from 66% (in Hash Join Operator) to 2% and Estimated Subtree Cost has changed from 0.47 to 3.6. Estimated Operator Cost and Estimated Subtree Cost values may change when we run statement(s) used in this example on different systems running on different configurations.

Note: This is just an illustration and you should never ever try this method in your live systems.

You can read all blogs in One operator a day series by clicking here and here is the Index for my execution plan series.

Happy Learning!

Regards,

Kanchan

Like us on FaceBook | Join the fastest growing SQL Server group on FaceBook | Follow me on Twitter | Follow me on FaceBook

Avatar

About Kanchan Bhattacharyya

Kanchan is an astute IT professional, a seasoned SQL Database Administrator with 13+ years of industry experience. A calculated risk taker with deep technical knowledge and has gained proficiency in database consulting and solutions across different environments. Kanchan holds MBA degree in IT and an International Executive MBA in Project Management. He is very passionate about SQL Server and holds MCSE (Data Platform), MCSA – SQL 2012, MCITP – SQL 2008 certifications. Currently he is focusing on cloud and latest releases of SQL Server. When not working, Kanchan likes to spend his time reading on new technical developments specifically on SQL Server and other related technologies.

View all posts by Kanchan Bhattacharyya →

Leave a Reply

Your email address will not be published. Required fields are marked *