---
title: "INSERT statement"
description: "Add rows with the CoraDB INSERT statement: VALUES, SET, SELECT, ON DUPLICATE KEY UPDATE, and inserting vertices and edges."
url: "https://www.coradb.ai/manual/sql/query/insert.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/query/insert.md"
product: "CoraDB"
version: "1.0"
keywords: "insert statement, insert values, insert set, insert select, on duplicate key update, odku, insert vertex, insert edge, undirected edge, last_insert_id, coradb insert"
---

# INSERT statement

The **INSERT** statement adds new rows to a table. CoraDB supports three ways to supply the values, plus two forms for graph data:

- **INSERT ... VALUES** and **INSERT ... SET** insert values you write in the statement.
- **INSERT ... SELECT** inserts the result of a query.
- **INSERT VERTEX** adds rows to a vertex table and **INSERT EDGE** connects two vertices through an edge table.

Any of the relational forms can end with **ON DUPLICATE KEY UPDATE** to update the existing row instead of failing when the new row would duplicate a primary key or unique value. To replace the existing row instead, see [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html).

> **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
INSERT [INTO] table_name [(column_name, ...)]
    {VALUES | VALUE} ({expr | DEFAULT}, ...) [, ({expr | DEFAULT}, ...) ...]
    [ON DUPLICATE KEY UPDATE column_name = expr, ...]

INSERT [INTO] table_name DEFAULT [VALUES]

INSERT [INTO] table_name
    SET column_name = {expr | DEFAULT} [, column_name = {expr | DEFAULT} ...]
    [ON DUPLICATE KEY UPDATE column_name = expr, ...]

INSERT [INTO] table_name [(column_name, ...)]
    <select_statement>
    [ON DUPLICATE KEY UPDATE column_name = expr, ...]

INSERT VERTEX [INTO] table_name [(column_name, ...)]
    {VALUES | VALUE} ({expr | DEFAULT}, ...) [, ({expr | DEFAULT}, ...) ...]

INSERT [DIRECTED | UNDIRECTED] EDGE
    FROM (<subquery>)
    TO (<subquery>)
    [INTO] table_name [(column_name, ...)]
    VALUES ({expr | DEFAULT}, ...)
```

- *table_name*: the table to insert into.
- *column_name*: the columns that receive values. If you omit the list, you must give a value for every column, in the order the columns were defined. Columns left out of the list get their default value, or `NULL` if they have none.
- *expr* | **DEFAULT**: the value for each column, in the order of the column list. An expression can be a subquery that returns one value. `DEFAULT` stores the column's default value.
- **DEFAULT VALUES**: insert one row made only of default values.
- *select_statement*: a query whose rows are inserted; its columns must match the column list.

## INSERT ... VALUES

Insert one row, with a value for every column:

```sql
INSERT INTO countries VALUES ('ROU', 'Romania');
```

Name the columns explicitly and insert several rows at once:

```sql
INSERT INTO countries (code, name) VALUES ('BGR', 'Bulgaria'), ('HUN', 'Hungary');
```

```text
2 rows affected.
```

## INSERT ... SET

`SET` names each column next to its value, which reads well for single rows:

```sql
INSERT INTO countries SET code = 'GRC', name = 'Greece';

SELECT code, name FROM countries
WHERE code IN ('BGR', 'GRC', 'HUN', 'ROU')
ORDER BY code;
```

| code | name |
|---|---|
| BGR | Bulgaria |
| GRC | Greece |
| HUN | Hungary |
| ROU | Romania |

## Default values and AUTO_INCREMENT

The next examples use a small table for customer support tickets. `id` is generated automatically, and `status` and `priority` have defaults:

```sql
CREATE TABLE support_ticket (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT NOT NULL,
    subject     VARCHAR(100) NOT NULL,
    status      VARCHAR(10) DEFAULT 'open',
    priority    INT DEFAULT 3
);
```

Leave out the columns you want filled in for you, pass `NULL` to an `AUTO_INCREMENT` column, or write `DEFAULT` explicitly:

```sql
INSERT INTO support_ticket (customer_id, subject) VALUES (5, 'Wrong size delivered');
INSERT INTO support_ticket (customer_id, subject, priority) VALUES (15, 'Refund request', 1);
INSERT INTO support_ticket VALUES (NULL, 42, 'Damaged parcel', 'pending', DEFAULT);
INSERT INTO support_ticket SET customer_id = 5, subject = 'Invoice copy', priority = priority + 1;

SELECT * FROM support_ticket ORDER BY id;
```

| id | customer_id | subject | status | priority |
|---:|---:|---|---|---:|
| 1 | 5 | Wrong size delivered | open | 3 |
| 2 | 15 | Refund request | open | 1 |
| 3 | 42 | Damaged parcel | pending | 3 |
| 4 | 5 | Invoice copy | open | 4 |

In the last statement, `priority + 1` uses the default value 3, because `priority` had not been assigned yet. [LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id) returns the value generated for the last row inserted in your session:

```sql
SELECT LAST_INSERT_ID();
```

```text
4
```

A table where every column has a default can take a row with no values at all:

```sql
CREATE TABLE visit_log (visited_at DATETIME DEFAULT SYSDATETIME, page VARCHAR(64) DEFAULT 'home');
INSERT INTO visit_log DEFAULT VALUES;
```

### Evaluation order in SET

The assignments of `INSERT ... SET` are evaluated from left to right. An expression can use a column assigned earlier in the same statement; a column not assigned yet has its default value, or `NULL` if it has no default:

```sql
INSERT INTO support_ticket SET customer_id = 9, subject = 'Late delivery', priority = customer_id - 7;
INSERT INTO support_ticket SET priority = customer_id + 1, customer_id = 12, subject = 'Address change';

SELECT id, customer_id, priority FROM support_ticket WHERE id > 4 ORDER BY id;
```

| id | customer_id | priority |
|---:|---:|---:|
| 5 | 9 | 2 |
| 6 | 12 | NULL |

In the second statement `customer_id` was still unassigned (and has no default) when `priority` was computed, so `priority` is `NULL`.

### Subqueries in VALUES

A value can be a subquery that returns a single value:

```sql
INSERT INTO support_ticket (customer_id, subject)
VALUES ((SELECT customer_id FROM orders WHERE id = 455), 'Order 455 not shipped');

SELECT id, customer_id, subject FROM support_ticket WHERE id = 7;
```

| id | customer_id | subject |
|---:|---:|---|
| 7 | 458 | Order 455 not shipped |

## INSERT ... SELECT

Use a query instead of `VALUES` to insert many rows at once. Copy all 2021 orders into an archive table with the same structure as `orders`:

```sql
CREATE TABLE order_archive LIKE orders;

INSERT INTO order_archive
SELECT * FROM orders WHERE order_date < DATE'2022-01-01';

SELECT COUNT(*), MIN(order_date), MAX(order_date) FROM order_archive;
```

| count(*) | min(order_date) | max(order_date) |
|---:|---|---|
| 416 | 2021-01-01 | 2021-12-31 |

The query can be any `SELECT`, including joins, aggregates and [common table expressions](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements).


## ON DUPLICATE KEY UPDATE

Inserting a row whose primary key or unique value already exists fails:

```sql
INSERT INTO countries VALUES ('FRA', 'France');
```

```text
ERROR: Operation would have caused one or more unique constraint violations. INDEX pk_countries_code ... key: 'FRA'
```

With **ON DUPLICATE KEY UPDATE**, CoraDB updates the existing row instead:

```sql
INSERT INTO countries VALUES ('FRA', 'French Republic')
ON DUPLICATE KEY UPDATE name = 'French Republic';

SELECT code, name FROM countries WHERE code = 'FRA';
```

| code | name |
|---|---|
| FRA | French Republic |

The affected-row count tells you what happened: 1 for each row inserted and 2 for each existing row updated. The statement above reports 2.

The clause works with `SET` and `SELECT` as well:

```sql
INSERT INTO countries SET code = 'ESP', name = 'Spain'
ON DUPLICATE KEY UPDATE name = 'Kingdom of Spain';

INSERT INTO countries (code, name)
SELECT 'ITA', 'Italy' FROM db_root
ON DUPLICATE KEY UPDATE name = 'Italian Republic';

SELECT code, name FROM countries WHERE code IN ('ESP', 'ITA') ORDER BY code;
```

| code | name |
|---|---|
| ESP | Kingdom of Spain |
| ITA | Italian Republic |

> **Note:**
> - If a table has several unique constraints (a primary key and a unique index, or several unique indexes), a new row can collide with different rows through different constraints. Avoid `ON DUPLICATE KEY UPDATE` on such tables.
> - When the insert turns into an update, an `AUTO_INCREMENT` value that was already generated for the attempted insert is not given back.


## INSERT VERTEX

Rows of a [vertex table](https://www.coradb.ai/manual/graph/graph_getting_started.html) are inserted like any other row. `INSERT VERTEX` makes the intent explicit; a plain `INSERT` works the same way. In the e-commerce database, `product` is a vertex table:

```sql
INSERT VERTEX INTO product (id, name, description, unit_price, units_in_stock)
VALUES (3001, 'Speedgoat Trail Shoe', 'Size 42, Blue', 155.00, 12);

INSERT INTO product (id, name, description, unit_price, units_in_stock)
VALUES (3002, 'Speedgoat Trail Shoe', 'Size 43, Blue', 155.00, 8);
```

## INSERT EDGE

An edge connects two existing vertices. Edges are inserted only with `INSERT EDGE`: the `FROM` and `TO` subqueries each select **one** vertex, and `VALUES` gives the edge's own columns. A subquery selects a vertex by naming the vertex table in its select list, as in `SELECT brand FROM brand WHERE ...`.

Connect the new shoe to its brand and to a category:

```sql
INSERT EDGE
    FROM (SELECT brand FROM brand WHERE name = 'Hoka')
    TO (SELECT product FROM product WHERE id = 3001)
    INTO manufactures VALUES (SYSDATETIME);

INSERT EDGE
    FROM (SELECT product FROM product WHERE id = 3001)
    TO (SELECT category FROM category WHERE name = 'Gear')
    INTO part_of VALUES (SYSDATETIME);
```

The new vertex and edges can be read back with [MATCH](https://www.coradb.ai/manual/graph/match.html):

```sql
SELECT b.name AS brand, p.name AS product, c.name AS category
FROM MATCH (b:brand)-[:manufactures]->(p:product),
           (p:product)-[:part_of]->(c:category)
WHERE p.id = 3001;
```

| brand | product | category |
|---|---|---|
| Hoka | Speedgoat Trail Shoe | Gear |

### Directed and undirected edges

An edge is directed by default (`INSERT EDGE` and `INSERT DIRECTED EDGE` are the same). `INSERT UNDIRECTED EDGE` creates a connection that is followed in both directions. In the e-commerce schema, `follows` connects customers:

```sql
INSERT UNDIRECTED EDGE
    FROM (SELECT customer FROM customer WHERE id = 5)
    TO (SELECT customer FROM customer WHERE id = 15)
    INTO follows VALUES (DATETIME'2026-01-10 09:30:00');

SELECT a.id, b.id, f.since
FROM MATCH (a:customer)-[f:follows]->(b:customer);
```

| a.id | b.id | f.since |
|---:|---:|---|
| 5 | 15 | 2026-01-10 09:30:00.000 |
| 15 | 5 | 2026-01-10 09:30:00.000 |

One edge was inserted, and it is matched from either end.

### Errors to expect

- A plain `INSERT` into an edge table is rejected with `From/to edges must be specified when inserting into an edge table`.
- If the `FROM` or `TO` subquery returns more than one row, the statement fails with `Query result contains more than a single tuple`. There are several *Erika Running Short* products (one per size and color), so this fails:

  ```sql
  INSERT EDGE
      FROM (SELECT customer FROM customer WHERE id = 5)
      TO (SELECT product FROM product WHERE name = 'Erika Running Short')
      INTO likes VALUES (SYSDATETIME);
  ```

- If a subquery returns no row (for example, a category name that does not exist), the statement fails because there is no vertex to connect.

## See also

- [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html): replace a row that has the same key
- [MERGE](https://www.coradb.ai/manual/sql/query/merge.html): insert or update rows from another table
- [Graph getting started](https://www.coradb.ai/manual/graph/graph_getting_started.html) and [MATCH](https://www.coradb.ai/manual/graph/match.html)
- [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#create-table): defaults, `AUTO_INCREMENT` and constraints
