The MERGE statement was introduced in Oracle 9i to conditionally insert or update data depending on its presence, a process also known as an "upsert". This is typically the case when you have to synchronize a table periodically with data from another source (table/view/query). In place of 3 separate unwieldy INSERT, UPDATE and DELETE statements with conditional sub-queries, the all-in-one MERGE does the job in one shot.
The
MERGE
statement reduces table scans and can perform the operation in parallel if required. MERGE INTO employees e
USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
The MERGE statement is optimized for merging sets of data, rather than single rows, as shown in the example below. It is the fastest method also simple to understand and code.
MERGE Restrictions :
1. cannot update any of the columns you are merging on.
2. MERGE is a deterministic statement – that is, you cannot update a row of the target table multiple times in the same MERGE statement.
3. MERGE tells you the total number of rows processed in the upsert, it does not tell you the individual counts of rows inserted/updated/deleted.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.