Merge Interval Operator – Part2

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!



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


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.