---
title: "MERGE statement"
description: "Synchronize a table with a source query using the CoraDB MERGE statement: update, delete or insert rows, and index hints."
url: "https://www.coradb.ai/manual/sql/query/merge.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/query/merge.md"
product: "CoraDB"
version: "1.0"
keywords: "merge statement, merge into, when matched, when not matched, upsert, merge delete where, use_update_idx, use_insert_idx, coradb merge"
---

# MERGE statement

The **MERGE** statement compares the rows of a source (a table, a view or a subquery) with a target table and, in one statement, updates the target rows that have a match, optionally deletes some of them, and inserts the source rows that have none. It is the usual way to keep a summary or staging table in step with other data.

> **Try it yourself:**
> The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. They change data, so start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to leave the database as it was.


## Syntax

```text
MERGE [<merge_hint>] INTO <target> [[AS] <alias>]
USING <source> [[AS] <alias>]
ON <join_condition>
[<merge_update_clause>]
[<merge_insert_clause>]

<merge_update_clause> ::=
    WHEN MATCHED THEN UPDATE
    SET column = expr [, column = expr ...]
    [WHERE <update_condition>]
    [DELETE WHERE <delete_condition>]

<merge_insert_clause> ::=
    WHEN NOT MATCHED THEN INSERT [(column_list)] VALUES (expr_list)
    [WHERE <insert_condition>]

<merge_hint> ::=
    /*+ [USE_UPDATE_IDX (index_list)] [USE_INSERT_IDX (index_list)] */
```

- *target*: the table that is updated, deleted from or inserted into.
- *source*: where the rows come from: a table, a view or a subquery in parentheses.
- *join_condition*: how a source row is matched with a target row, usually by key.
- **WHEN MATCHED THEN UPDATE**: runs for every target row that matches a source row.
  - *expr* can use columns of the source and the target, or `DEFAULT` (not when the target is a view). Aggregate functions are not allowed here; aggregate in the source query instead.
  - *update_condition*: update only the matched rows for which it is true.
  - **DELETE WHERE** *delete_condition*: after the update, delete the updated rows for which the condition is true. The condition sees the **new** values.
- **WHEN NOT MATCHED THEN INSERT**: runs for every source row with no matching target row.
  - *insert_condition*: insert only the source rows for which it is true. It can use source columns.
- You can give either clause, or both in any order.
- *merge_hint*: index hints, described [below](https://www.coradb.ai/manual/sql/query/merge.html#index-hints).

`UPDATE`, `DELETE` and `INSERT` triggers on the target fire for the rows each clause changes. You need `SELECT` permission on the source and `UPDATE`, `DELETE` or `INSERT` permission on the target for the clauses you use.

## Example: maintaining a VIP customer list

`vip_customer` keeps, for a few customers, how many orders they placed and when they last ordered. The stored figures are out of date:

```sql
CREATE TABLE vip_customer (
    customer_id  INT PRIMARY KEY,
    orders_count INT NOT NULL,
    last_order   DATE
);
INSERT INTO vip_customer VALUES
    (5,  1, DATE'2024-01-15'),
    (15, 1, DATE'2024-01-15'),
    (42, 3, DATE'2024-05-20');
```

The `MERGE` below refreshes the list from the `orders` table:

- Customers already in the list get their current order count and last order date;
- Customers who end up with fewer than three orders are dropped;
- Customers not yet in the list are added if they placed at least 39 orders.

```sql
MERGE INTO vip_customer t
USING (SELECT customer_id, COUNT(*) AS n, MAX(order_date) AS last_order
       FROM orders
       GROUP BY customer_id) s
ON (t.customer_id = s.customer_id)
WHEN MATCHED THEN
    UPDATE SET t.orders_count = s.n, t.last_order = s.last_order
    DELETE WHERE t.orders_count < 3
WHEN NOT MATCHED THEN
    INSERT VALUES (s.customer_id, s.n, s.last_order) WHERE s.n >= 39;

SELECT * FROM vip_customer ORDER BY customer_id;
```

| customer_id | orders_count | last_order |
|---:|---:|---|
| 15 | 4 | 2025-09-03 |
| 42 | 3 | 2024-05-20 |
| 440 | 40 | 2025-12-27 |
| 444 | 39 | 2025-09-06 |
| 812 | 40 | 2025-12-10 |

What happened to each row:

- **15** matched and was updated to 4 orders, so it stays.
- **5** matched and was updated to 2 orders. `DELETE WHERE` checks the updated value, 2 is below 3, so the row was deleted.
- **42** has no orders, so there is no source row for it and it was left as it was.
- **440, 444, 812** had no row in the list and placed at least 39 orders, so they were inserted. Customers with fewer orders were skipped by the `WHERE` of the insert clause.

The statement reports 5 affected rows: two updates (one of which was then deleted) and three inserts.

## Using only one clause

Each clause is optional. Insert the most active customers without touching existing rows:

```sql
MERGE INTO vip_customer t
USING (SELECT customer_id, COUNT(*) AS n, MAX(order_date) AS last_order
       FROM orders
       GROUP BY customer_id) s
ON (t.customer_id = s.customer_id)
WHEN NOT MATCHED THEN
    INSERT (customer_id, orders_count, last_order)
    VALUES (s.customer_id, s.n, s.last_order)
    WHERE s.n >= 39;
```

## Index hints

`USE_UPDATE_IDX` names the indexes to use when matching rows for the update clause, and `USE_INSERT_IDX` the indexes to use for the insert clause. Both apply to the join condition. Use the index names of the target table; a primary key's index is named `pk_<table>_<column>`:

```sql
MERGE /*+ USE_UPDATE_IDX(pk_vip_customer_customer_id) */ INTO vip_customer t
USING (SELECT customer_id, COUNT(*) AS n, MAX(order_date) AS last_order
       FROM orders
       GROUP BY customer_id) s
ON (t.customer_id = s.customer_id)
WHEN MATCHED THEN
    UPDATE SET t.orders_count = s.n, t.last_order = s.last_order;
```

For hints in general, see [Using SQL hint](https://www.coradb.ai/manual/sql/tuning_hints.html#using-sql-hint).

## See also

- [INSERT ... ON DUPLICATE KEY UPDATE](https://www.coradb.ai/manual/sql/query/insert.html#on-duplicate-key-update): upsert from literal values
- [UPDATE](https://www.coradb.ai/manual/sql/query/update.html#updating-several-tables): update from a join
- [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html)
