So, you want to use MERGE, eh?
So, you want to use MERGE, eh?
Please don't. Every time I see a question about MERGE
, I scramble for the links I post to urge people to change their minds. So I put them together here.
If you insist on using MERGE
, the biggest TL;DR is:
Please ALWAYS use HOLDLOCK
on the target.
But for a long list of details, see these resources:
- Use Caution with SQL Server's MERGE Statement
This is the one that occasionally ruffles feathers, but I talk about some real shortcomings withMERGE
and some bugs that have never been fixed. - An update on MERGE
Largely in response to that post, Hugo Kornelis recently investigated many of the issues I brought up initially (and a few others), and concluded that most are no longer issues in current versions of SQL Server. Shockingly, I left a comment. - Be Careful with the Merge Statement
Michael J. Swart initially advised you be careful withMERGE
. - What To Avoid If You Want To Use MERGE
In a follow-up post, Michael pulls no punches here, except the punchline: his now stronger opinion that you just avoidMERGE
altogether. - Please stop using this UPSERT anti-pattern
When I do succeed in weening someone away fromMERGE
, they often turn to a problematicUPSERT
approach. - SQL Server UPSERT Patterns and Antipatterns and Mythbusting: Concurrent Update/Insert Solutions
Michael also talks about how to perform concurrent updates/inserts. - UPDATE if exists else INSERT or Solutions for INSERT OR UPDATE on SQL Server
Probably the most canonical answers I have that explain why you should read all the links above. - Some MERGE bugs from Paul White
Paul goes into great detail about several bugs he's discovered withMERGE
over the years.
By: Aaron Bertrand
I am a passionate technologist with industry experience dating back to Classic ASP and SQL Server 6.5. I am a long-time Microsoft MVP, write at Simple Talk, SQLPerformance, and MSSQLTips, and have had the honor of speaking at more conferences than I can remember. In non-tech life, I am a husband, a father of two, a huge hockey and football fan, and my pronouns are he/him.