
Meet Rahul, a data engineer at an e-learning platform. Every night, he receives a spreadsheet from the marketing team with updates to customer data—some are new signups, some are updates to old customers, and a few need to be removed.
His challenge?
“How do I keep the master Customers table in the database in sync with this daily file—without running three separate queries?”
Chapter 1: The Old Way – Multiple Queries
Rahul used to write:
- UPDATE existing records
- INSERT new ones
- DELETE obsolete ones
Each with its own logic and filters.
It worked, but was messy and error-prone.
Chapter 2: The Discovery – Enter MERGE
One day, his senior Dev said:
“Why not use the MERGE command?
It lets you update, insert, or delete in one go, based on matching conditions.”
Rahul tried it.
And it worked like magic.
Chapter 3: What MERGE Does (In Simple Words)
MERGE is like a smart negotiator between two tables (or datasets):
- The target: where you want to apply changes (e.g., Customers)
- The source: the incoming changes (e.g., UpdatedCustomerList)
It checks each row in the source and decides:
- If it matches a record in the target → UPDATE it
- If it doesn’t match → INSERT it as new
- If something in the target is missing from the source → optionally DELETE it
Chapter 4: Rahul’s New SQL Superpower
MERGE INTO Customers AS Target
USING UpdatedCustomerList AS Source
ON Target.CustomerID = Source.CustomerID
WHEN MATCHED THEN
UPDATE SET Target.Email = Source.Email, Target.Name = Source.Name
WHEN NOT MATCHED BY TARGET THEN
INSERT (CustomerID, Name, Email)
VALUES (Source.CustomerID, Source.Name, Source.Email)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
In one clean command, Rahul could sync the tables.
Chapter 5: Why It Matters
- Faster development: fewer lines, less maintenance
- Cleaner logic: easier to understand and review
- Data consistency: fewer mistakes across INSERTs/UPDATEs
- Real-world need: syncing CRM systems, inventory lists, or user accounts
Conclusion:
Rahul no longer dreads the daily data sync.
He tells his team:
“MERGE is like hiring a smart assistant that looks at both lists and says,
‘I’ll update this, add that, and remove the rest—don’t worry.’”
Leave a Reply