0% found this document useful (0 votes)
31 views4 pages

Hands-On Merging of 2 Tables

The MERGE statement combines INSERT and UPDATE operations into a single statement. It allows matching source table rows to be updated in the target table, and non-matching rows to be inserted, based on a join condition between the two tables. The example shows how the MERGE statement can be used to update the count column in the target table by adding the count from the source and target tables, for rows where the id column matches between the two tables.

Uploaded by

Raghu C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views4 pages

Hands-On Merging of 2 Tables

The MERGE statement combines INSERT and UPDATE operations into a single statement. It allows matching source table rows to be updated in the target table, and non-matching rows to be inserted, based on a join condition between the two tables. The example shows how the MERGE statement can be used to update the count column in the target table by adding the count from the source and target tables, for rows where the id column matches between the two tables.

Uploaded by

Raghu C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Hands-on MERGE TWO TABLES

• The MERGE statement combines INSERT and UPDATE operations


as a single operation.

Syntax:
MERGE INTO [[db-name.]schema.]target-table
USING [[db-name.]schema.]source-table
ON ( condition )
[ WHEN MATCHED THEN UPDATE SET
column1 = value1 [, column2 = value2 ... ] ]
[ WHEN NOT MATCHED THEN INSERT
( column1 [, column2 ...]) VALUES ( value1 [, value2 ... ] ) ]
MERGE INTO target TGT
USING source SRC
ON SRC.A=TGT.A
WHEN MATCHED THEN
UPDATE SET A=TGT.A, B=TGT.B, C=TGT.C, D=TGT.D,
E=TGT.E
WHEN NOT MATCHED THEN
INSERT VALUES (SRC.A,SRC.B, SRC.C, SRC.D,
SRC.E);

2
3
Example:
• The following example shows how to merge table target_table with table source_table.
• When the id columns match, the target table’s count column is updated.

CREATE TABLE target_table


(id INT PRIMARY KEY, count INT);
CREATE TABLE source_table
(id INT, count INT);
INSERT INTO target_table (id, count) VALUES (1,1);
INSERT INTO source_table (id, count) VALUES (1,1);

MERGE INTO target_table t USING source_table s ON s.id=t.id WHEN MATCHED THEN


UPDATE SET count=s.count+t.count;

SELECT * FROM target_table;


id | count
---+-----
1 | 2

(1 row)

You might also like