H2 Database – Merge

MERGE command is used to update the existing rows and insert new rows into a table. The primary key column plays an important role while using this command; it is used to find the row.

Syntax

Following is the generic syntax of the MERGE command.

MERGE INTO tableName [ ( columnName [,...] ) ] 
[ KEY ( columnName [,...] ) ] 
{ VALUES { ( { DEFAULT | expression } [,...] ) } [,...] | select } 

In the above syntax, the KEY clause is used to specify the primary key column name. Along with the VALUES clause, we can use primitive values to insert or we can retrieve and store another table values into this table using the select command.

Example

In this example, let us try to add a new record into the Customers table. Following are the details of the new record in the table.

Column NameValue
ID8
NAMELokesh
AGE32
ADDRESSHyderabad
SALARY2500

Using the following query, let us insert the given record into the H2 database query.

MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Lokesh', 32, 'Hyderabad', 2500);

The above query produces the following output.

Update count: 1 

Let us verify the records of the Customer table by executing the following query.

SELECT * FROM CUSTOMER;

The above query produces the following output.

IDNameAgeAddressSalary
1Ramesh32Ahmedabad2000
2Khilan25Delhi1500
3Kaushik23Kota2000
4Chaitali25Mumbai6500
5Hardik27Bhopal8500
6Komal22MP4500
7Muffy24Indore10000
8Lokesh32Hyderabad2500

Now let us try to update the record using the Merge command. Following are the details of the record to be updated.

Column NameValue
ID8
NAMELoki
AGE32
ADDRESSHyderabad
SALARY3000

Use the following query to insert the given record into the H2 database query.

MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Loki', 32, 'Hyderabad', 3000);

The above query produces the following output.

Update count: 1 

Let us verify the records of the Customer table by executing the following query.

SELECT * FROM CUSTOMER; 

The above query produces the following output −

IDNameAgeAddressSalary
1Ramesh32Ahmedabad2000
2Khilan25Delhi1500
3Kaushik23Kota2000
4Chaitali25Mumbai6500
5Hardik27Bhopal8500
6Komal22MP4500
7Muffy24Indore10000
8Loki32Hyderabad3000

Leave a Reply