Merge Interval Operator – Part2

Merge Interval Operator – Part2

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.

Transact-SQL

1

2

3

4

5

6

USE[AdventureWorks2012]

SELECTSUM(Product.SafetyStockLevel)

FROM[Production].[Product]

WHEREProduct.ProductIDBETWEEN1AND15

ORProduct.ProductIDBETWEEN10AND20

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.

Transact-SQL

1

2

3

4

5

6

7

8

9

10

11

USE[AdventureWorks2012]

DECLARE@Var1Int=1

DECLARE@Var2Int=15

DECLARE@Var3Int=10

DECLARE@Var4Int=20

SELECTSUM(Product.SafetyStockLevel)

FROM[Production].[Product]

WHEREProduct.ProductIDBETWEEN@Var1AND@Var2

ORProduct.ProductIDBETWEEN@Var3AND@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.

Share This Story, Choose Your Platform!

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.