Junior — Middle
Explain the working principle of the MERGE operation in SQL and in what scenarios it is used?
sobes.tech AI
Answer from AI
The MERGE operation in SQL is used to combine data from one table (source) into another (target) with the possibility of inserting new records, updating existing ones, or deleting.
Working principle:
- Matches rows from the source and target based on a specified condition (e.g., by key).
- If a match is found, it performs an update or delete.
- If no match is found, it inserts a new row.
This is useful for implementing "upsert" scenarios (update + insert), when data needs to be synchronized.
Example:
MERGE INTO target_table AS t
USING source_table AS s
ON t.id = s.id
WHEN MATCHED THEN
UPDATE SET t.value = s.value
WHEN NOT MATCHED THEN
INSERT (id, value) VALUES (s.id, s.value);
Use cases:
- Updating data from external sources.
- Synchronizing tables.
- Importing data with the ability to update existing records.