Updating and Inserting Data by Using the MERGE INTO Statement
To add all or a large amount of data in a table to an existing table, you can run the MERGE INTO statement in openGauss to merge the two tables so that data can be quickly added to the existing table.
The MERGE INTO statement matches data in a source table with that in a target table based on a join condition. If data matches, UPDATE will be executed on the target table. Otherwise, INSERT will be executed. This statement is a convenient way to combine multiple operations and avoids multiple INSERT or UPDATE statements.
Prerequisites
You have the INSERT and UPDATE permissions for the target table and the SELECT permission for the source table.
Procedure
Create a source table named products and insert data.
openGauss=# CREATE TABLE products ( product_id INTEGER, product_name VARCHAR2(60), category VARCHAR2(60) ); openGauss=# INSERT INTO products VALUES (1502, 'olympus camera', 'electrncs'), (1601, 'lamaze', 'toys'), (1666, 'harry potter', 'toys'), (1700, 'wait interface', 'books');
Create a target table named newproducts and insert data.
openGauss=# CREATE TABLE newproducts ( product_id INTEGER, product_name VARCHAR2(60), category VARCHAR2(60) ); openGauss=# INSERT INTO newproducts VALUES (1501, 'vivitar 35mm', 'electrncs'), (1502, 'olympus ', 'electrncs'), (1600, 'play gym', 'toys'), (1601, 'lamaze', 'toys'), (1666, 'harry potter', 'dvd');
Run the MERGE INTO statement to merge data in the source table products into the target table newproducts.
openGauss=# MERGE INTO newproducts np USING products p ON (np.product_id = p.product_id ) WHEN MATCHED THEN UPDATE SET np.product_name = p.product_name, np.category = p.category WHEN NOT MATCHED THEN INSERT VALUES (p.product_id, p.product_name, p.category) ;
For details on parameters in the statement, see Table 1. For more information, see MERGE INTO.
Table 1 Parameters in the MERGE INTO statement
Query the target table newproducts after the merge.
openGauss=# SELECT * FROM newproducts;
The command output is as follows:
product_id | product_name | category ------------+----------------+----------- 1501 | vivitar 35mm | electrncs 1502 | olympus camera | electrncs 1666 | harry potter | toys 1600 | play gym | toys 1601 | lamaze | toys 1700 | wait interface | books (6 rows)