Write a SQL MERGE statement that updates records when they match, inserts new records when they don't, and deletes records that are not present in the source.
1Times asked
Jun 2026Last seen
Jun 2026First seen
💡 Model Answer
Assuming we have an employees_source table (new data) and an employees_target table (current data), the MERGE can be written as:
sql
MERGE INTO employees_target AS tgt
USING employees_source AS src
ON tgt.employee_id = src.employee_id
WHEN MATCHED THEN
UPDATE SET
tgt.first_name = src.first_name,
tgt.last_name = src.last_name,
tgt.department = src.department,
tgt.salary = src.salary
WHEN NOT MATCHED THEN
INSERT (employee_id, first_name, last_name, department, salary)
VALUES (src.employee_id, src.first_name, src.last_name, src.department, src.salary)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;Explanation:
- The
WHEN MATCHEDclause updates existing rows. - The
WHEN NOT MATCHEDclause inserts rows that are new. - The
WHEN NOT MATCHED BY SOURCEclause deletes rows that no longer exist in the source.
Complexity: The operation is O(n) relative to the number of rows in the source, with the database engine handling hashing or indexing internally. The statement is atomic, ensuring consistency without separate transaction control.
This pattern is ideal for nightly batch jobs that keep a reporting or analytics table in sync with operational data.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500