Hi Geeks,
Welcome to the Part3 of SQL Server query hints execution plan. You can read last two posts by clicking Part1 and Part2. Today we are going to see how we can control union operations in execution plan.
USE [AdventureWorks2012] SELECT PR1.Name, PR1.Class, PR1.ModifiedDate FROM Production.Product PR1 UNION SELECT PR2.Name, PR2.Class, PR2.ModifiedDate FROM Production.Product PR2
From above figures, though Concatenation operation (read here Part1, Part2, Part3) is cheap but Sort (read here Part1, Part2) is not and slightly expensive. What if we want to force HASH JOIN instead of query optimizer’s default choice? Let’s try that out.
USE [AdventureWorks2012] SELECT PR1.Name, PR1.Class, PR1.ModifiedDate FROM Production.Product PR1 UNION SELECT PR2.Name, PR2.Class, PR2.ModifiedDate FROM Production.Product PR2 OPTION (HASH UNION)
We are able to remove SORT operations but Hash Union is bit costlier than query optimizers default choice. Now, let us try MERGE UNION and see if this adds any benefit over default choice.
USE [AdventureWorks2012] SELECT PR1.Name, PR1.Class, PR1.ModifiedDate FROM Production.Product PR1 UNION SELECT PR2.Name, PR2.Class, PR2.ModifiedDate FROM Production.Product PR2 OPTION (MERGE UNION)
From above plan and ToolTip, SORT is back but Merge Union is still costly than optimizers default choice of Concatenation and Sort. So, we can say though we are able to control the way query works, but this does not help us to improve query performance.
You can find index to the execution plan series here and click on One operator a day to visit exclusive page for this 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