The MERGE syntax - syntax and performance

by Allan Svelmøe Hansen May 21, 2010 15:40

Normally when you have rows from one table you want to move over into the other, you'll have to run both an update query to get your existing rows updated with the new values and insert query to get new rows over to your target. That means you have to write two queries. With the merge, you only need one as it performs both the update and the insert.
So let's take a look at it.

First, I'll create 2 tables with dummy data; a tblSource and a tblTarget.
The scripts for creating the tables and data can be found here merge_setup_20100521.sql (3.58 kb), but basically it's just a target and source table with an ID, ValA, ValB and ValC with a clustered index on ID and some dummy data.
So to do the update/insert it would look like this:
UPDATE MyTarget SET 
   
MyTarget.ValA MySource.ValA

   
MyTarget.ValB MySource.ValB

   
MyTarget.ValC 
MySource.ValC 
FROM dbo.tblTargetInUp AS 
MyTarget  
INNER JOIN dbo.tblSourceInUp AS MySource ON MyTarget.ID 
MySource.ID 

INSERT INTO 
dbo.tblTargetInUp 
SELECT IDValAValB
ValC 
FROM dbo.tblSourceInUp AS 
MySource  
WHERE NOT EXISTS (SELECT FROM dbo.tblTargetInUp AS MyTarget WHERE MyTarget.ID MySource.ID
)  
 

If we look at the execution plan, I get an estimated cost of 9.1754 for the update and 2.48725 for the insert, meaning a combined cost of 11.66265 for 33.333 rows updated and 33.3334 rows inserted, into a target of 66.666 rows.

Now do remember, the estimated cost is just a number for how the query runs in my environment, it can't be taken as a direct number and transferred to another system - I'm only interested in the relative comparison with the merge. More data, more indexes, more variations will all affect the actual numbers. Also if looking at the execution plan, it is clear it is two queries we fire, meaning that all the overhead which goes into running one query will be doubled for this. But it was how you'd have to do merges in the past.

Now, with the merge syntax we can do it like this:
MERGE dbo.TblTargetMerge AS MyTarget USING 
(   
   
SELECT FROM dbo.TblSourceMerge AS 
TS 
AS 
MySource 
ON MyTarget.ID 
MySource.ID 
WHEN MATCHED 
THEN  
   UPDATE SET 
       
MyTarget.ValA MySource.ValA

       
MyTarget.ValB MySource.ValB

       
MyTarget.ValC 
MySource.ValC 
WHEN NOT MATCHED 
THEN 
   INSERT  
   
(IDValAValBValC

   
VALUES 
   
(MySource.IDMySource.ValAMySource.ValBMySource.ValC

  

Note that the syntax takes both the update and insert in the WHEN MATCHED and WHEN NOT MATCHED.
For the complete overview over the syntax, I'll refer you to the documentation by microsoft: MERGE (Transact-SQL).
But basically – you MERGE into a table using a source, and then define the ON clause (as you would a join), and then specify the WHEN MATCHED and the WHEN NOT MATCHED clauses.

One thing I'll expand on myself though, is the OUTPUT clause which can also be coupled on to the merge. I mentioned the OUTPUT clause myself recently.
The important thing is that you can couple the $action to the output clause and get information about whether you merged the data or you inserted the data, meaning whether the row was matched or not matched.
Like this:

MERGE dbo.TblTargetMerge AS MyTarget USING 
<...snipped FOR being brief...

OUTPUT $ACTION
rest_of_select_here 
;  
  

Nifty.
Anyways - once we've build this query, we can look at the execution plan, and here we clearly see it is handled as one query.
And in my case, the estimated cost is 8.407 for the same number of rows as above, meaning we’ve saved about 27.9% just by changing syntax.

Now, this structure I used to compare is very simple - with a simple matching of ID to ID and then just insert/overwrite everything so the actual result may vary (naturally), however the merge syntax does appear to be faster and with the added bonus of keeping the query combined into one syntax rather than divided into two different queries.
 
I must admit, I do like the merge syntax myself once I learned to read and write them.

Bookmark and Share DotnetKicks dotnetshoutout

UPDATE/INSERT syntax trick

by Allan Svelmøe Hansen June 08, 2008 09:17

A little trick you can use with an update or insert is an automatic assignment.
For example at times I've had to update all rows in a (temporay) table with an consecutive number and a fast way of doing this is utilizing this technique:

DECLARE @I INT
SET 
@I 0
UPDATE Table_1
SET @I MyID @I 1
 

This example instantiates an interger (I) to the value 0. Then I update a table where I set an ID column to the value of I + 1, but at the same time I set my I variable to the value of MyID. This means that the first row will get the value 1 into MyID and the second will get 2 and so forth.

And of course this example is very simple, and in such a case one might as well just use identity. However because you can make any calculations you want, and because it does not have to be an integer data type - you can use this for various situations.

It just goes to show that T-SQL syntax allows for playing around.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: ,

SQL

More table partitioning and numbers

by Allan Svelmøe Hansen April 02, 2008 12:50

Following up on my previous testing of table partitioning, I wanted to see if I could identify any notable overhead when using partitioned tables other then in selects, meaning delete, update and of course inserts. At the same time I thought I could test out with a partitioned table but where the files was located on the same physical drive.
So I created a new database, 2 partition functions and schemas and 3 new tables. TestOne was partitioned as my last time, and so was TestTwo. TestThree table was partitioned exactly like TestOne except it utilized file groups located on the same physical drive, whereas TestOne had its filegroups split across two physical drives.
I found out that selects provided no noticeable performance difference between TestOne and TestThree tables. I would think the main area where one would see performance differences here is dependent on hardware and load on the drives, and less so with the SQL Server performance.  So further testing into this will be outside the scope of at least this blog entry.

So – onwards to testing other SQL then selects. The first I tested was ordinary inserts for each of my 3 tables.

INSERT INTO <TABLE>
VALUES (1'test')
GO

When running this it provided me with this execution plan:

(click to enlarge)
Estimated Execution Plan For Insert

Not surprisingly there is an overhead visible when it comes to inserting into a partitioned table compared to a non-partitioned one.  Plus the plans do not look the same. I would simply attribute the overhead to the fact that SQL Server needs to look up which file group to locate the data in based on the partition function.
The difference in this instance does however look relative small. The entire subtree cost for inserting into a partitioned table (TestOne and TestThree) were 0.010471 whereas for TestTwo it was 0.01.
So while the specific numbers might differ from system to system etc, it does show an overhead, albeit a small one.
When it came to both delete and updates, I found that the same issues as with select statements were in effect.
When I only needed to delete or update on a specific "grouping" of data, the partitioned tables were actually faster than the non-partitioned one. When I had to update across "groups" then the non-partitioned one was fastest.
For example:

UPDATE TestOne
SET MyValue='Test2'
WHERE MyID 1
GO
 

was faster then

UPDATE TestTwo
SET MyValue='Test2'
WHERE MyID 1
GO
 

by a factor around 20%, whereas

UPDATE TestOne
SET MyValue='Test2'
WHERE MyID OR MyID  2
 

was about 10% slower then

UPDATE TestTwo
SET MyValue='Test2'
WHERE MyID OR MyID  2
 

This leads back to my conclusion in the last piece that if you in fact can group your data in a manner which makes sense and avoids “cross-grouping data”, then it is faster performance wise to do so. The only time it looks to be noticeable slower to have partitioned data is with inserts.
This of course is not an ever valid conclusion, and I’m sure more concrete and scientifically gathered data could present cases against. But if your data abides to some rules which makes a grouping possible and the main focus on the data is reading versus inserting; then there looks to be mainly advantages when it comes to performance with table partitioning. And especially this can run transparent for normal users and database developers it is definitely something worth a thought.

 

 

Bookmark and Share DotnetKicks dotnetshoutout

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant

About:
Allan Svelmøe Hansen

My real name is Allan Svelmøe Hansen.
I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004.
My primary fields of expertise is back-end data integration, database design and optimization.


       View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer

The opinions expressed herein are my own personal opinions and thoughts and does not represent my employers view in any way, nor are my results guaranteed for all situations.
Content is presented "as is", with no warranty.