Hi Geeks,
Welcome to Part2 of Merge Interval Operator. If you missed Part1, you can click here and read it before today’s post.
Let me modify our query from yesterday as following.
USE [AdventureWorks2012] SELECT SUM(Product.SafetyStockLevel) FROM [Production].[Product] WHERE Product.ProductID BETWEEN 1 AND 15 OR Product.ProductID BETWEEN 10 AND 20
As can be seen from execution plan, query optimizer is smart enough to recognize overlap between predicates and instead of two index seeks it created a plan that used only performs single seek operation.
Let’s change the query to use local variables and see its impact on the execution plan.
USE [AdventureWorks2012] DECLARE @Var1 Int = 1 DECLARE @Var2 Int = 15 DECLARE @Var3 Int = 10 DECLARE @Var4 Int = 20 SELECT SUM(Product.SafetyStockLevel) FROM [Production].[Product] WHERE Product.ProductID BETWEEN @Var1 AND @Var2 OR Product.ProductID BETWEEN @Var3 AND @Var4
Note: Query plan is broken into two parts in order to fit into the window.
In the example query, SQL Server has to read range 10 to 15 twice as there is an overlap between 10 to 15. First, to identify values between @Var1 and @Var2, and then between @Var3 and @Var4. After Merge interval is run, SQL Server has to read only final seek i.e. @Var1 to @Var4 directly.
See you tomorrow with a new operator here on One operator a day 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