Open In App

PostgreSQL MERGE Statement

Last Updated : 01 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The MERGE statement in PostgreSQL is a powerful data manipulation tool introduced in PostgreSQL 15, enabling conditional INSERT, UPDATE, and DELETE operations in a single command. This feature streamlines data synchronization between tables, making it ideal for tasks such as upserts and handling table synchronization.

In this article, we will explain the PostgreSQL MERGE statement in depth, covering its syntax and practical examples to demonstrate its functionality.

PostgreSQL MERGE Statement

The MERGE statement can combine the INSERT, UPDATE, and DELETE operations into a single statement, making it easier to manage the records. It can allow the users to conditionally execute these operations based on the results of the JOIN between the target table and the source data.

syntax:

MERGE INTO target_table USING source_table 
ON merge_condition
WHEN MATCHED THEN
UPDATE SET column1 = value1, column2 = value2, ...
WHEN NOT MATCHED THEN
INSERT (column1, column2, ...) VALUES (value1, value2, ...);

Key Terms

  • target_table: The table you want to modify.
  • source_table: The table containing the new or updated the data.
  • merge_condition: The condition can be used to match the rows from the target_table with rows in the source_table.
  • WHEN MATCHED: It can specifies the action to take when the match is found.
  • WHEN NOT MATCHED: It can specifies the action to take when no match is found.

Examples of Using the MERGE Statement in PostgreSQL

To illustrate the MERGE statement’s flexibility, let us go through a few practical examples that highlight common scenarios for data synchronization and updates.

Example 1: Merging Data with Update and Insert

This example demonstrates how to use the MERGE statement to update existing records and insert new records if they do not exist.

Step 1: Create employee table and insert Data

CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
name VARCHAR(100),
salary NUMERIC(10, 2)
);

INSERT INTO employees (name, salary) VALUES
('John Doe', 50000),
('Jane Smith', 60000),
('Alice Johnson', 70000);

select * from employees;

Output

emp3
PostgreSQL MERGE Statement Example1 step1

Step 2: Create employees_updates Table and Insert Data

CREATE TABLE employees_updates (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
salary NUMERIC(10, 2)
);

INSERT INTO employees_updates (employee_id, name, salary) VALUES
(1, 'John Doe', 52000), -- Updates the salary of John Doe
(4, 'Bob Brown', 55000); -- New employee Bob Brown

select * from employees_updates;

Output

emp4
PostgreSQL MERGE Statement Example1 step2

Step 3: Execute MERGE Statement

In this example, we have the two tables, employees and employees_updates. We want to update the salary in the employees table if there is match on the employee_id and insert the new record if there is no match.

MERGE INTO employees AS e
USING employees_updates AS u
ON e.employee_id = u.employee_id
WHEN MATCHED THEN
UPDATE SET salary = u.salary
WHEN NOT MATCHED THEN
INSERT (employee_id, name, salary)
VALUES (u.employee_id, u.name, u.salary);

select * from employees;

Output

empresult
PostgreSQL MERGE Statement Example1 step3

Explanation:

This statement will update the salary of matching the employees in the employees table and insert the new employees from employees_updates if they don't exist.

Example 2: Using MERGE for Deletion of Stale Data

This example demonstrates how to use MERGE for removing stable or inactive records from an old customer table based on the status in an active customer table.

Step 1: Create old_customers Table and Insert data

CREATE TABLE old_customers (
customer_id SERIAL PRIMARY KEY,
name VARCHAR(100)
);

INSERT INTO old_customers (name) VALUES
('Customer A'),
('Customer B'),
('Customer C');

select * from old_customers;

Output

cus1
PostgreSQL MERGE Statement Example2 step 1

Step 2: Create active_customers Table and Insert data

CREATE TABLE active_customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);

INSERT INTO active_customers (customer_id, name) VALUES
(1, 'Customer A'), -- Customer A is still active
(2, 'Customer D'); -- New active customer

select * from active_customer;

Output

cus2
PostgreSQL MERGE Statement Example2 step 2

Step 3: Execute MERGE Statement

We can use the MERGE statement to remove the stale records from the old_customers table if they no longer exist in the active_cusomers table.

MERGE INTO old_customers AS oc
USING active_customers AS ac
ON oc.customer_id = ac.customer_id
WHEN MATCHED THEN
UPDATE SET is_active = TRUE
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET is_active = FALSE;
select * from old_cusomters;

Output

cus3
PostgreSQL MERGE Statement Example2 step 3

Explanation:

The MERGE statement will delete entries in the old_customers that are not present in the active_customers table and it can ensuring the table only contains active records.

Conclusion

The MERGE statement in PostgreSQL is an essential tool for efficient data management, allowing INSERT, UPDATE, and DELETE operations to be combined within a single conditional statement. By understanding and using the MERGE statement effectively, we can streamline data synchronization, ensure accurate upserts, and handle complex transformations with ease. Using MERGE in PostgreSQL 15 and above can significantly optimize database operations, especially in large and dynamic environments.


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg