Skip to main content
The INSERT inserts one or more rows into a table. In cases where inserted values conflict with uniqueness constraints, the ON CONFLICT clause can be used to update rather than insert rows.

Required privileges

The user must have the INSERT on the table. To use ON CONFLICT, the user must also have the SELECT privilege on the table. To use ON CONFLICT DO UPDATE, the user must additionally have the UPDATE privilege on the table.

Synopsis

insert syntax diagram

Parameters

ParameterDescription
common_table_exprSee .
table_nameThe table into which data is written.
AS table_alias_nameAn alias for the table name. When you provide an alias, it completely hides the actual table name.
column_nameThe name of a column to populate during the insert.
select_stmtA . Each value must match the of its column. Also, if column names are listed after INTO, values must be in corresponding order; otherwise, they must follow the declared order of the columns in the table.
DEFAULT VALUESTo fill all columns with their , use DEFAULT VALUES in place of select_stmt. To fill a specific column with its default value, leave the value out of the select_stmt or use DEFAULT at the appropriate position. See the Insert Default Values examples below.
RETURNING target_listReturn values based on rows inserted, where target_list can be specific column names from the table, * for all columns, or computations using . See the Insert and Return Values example below.

ON CONFLICT clause

on_conflict syntax diagram Normally, when inserted values conflict with a UNIQUE constraint on one or more columns, CockroachDB returns an error. To update the affected rows instead, use an ON CONFLICT clause containing the column(s) with the unique constraint and the DO UPDATE SET expression set to the column(s) to be updated (any SET expression supported by the statement is also supported here, including those with WHERE clauses). To prevent the affected rows from updating while allowing new rows to be inserted, set ON CONFLICT to DO NOTHING. See the Update values ON CONFLICT and Do not update values ON CONFLICT examples. If the values in the SET expression cause uniqueness conflicts, CockroachDB will return an error. ON CONSTRAINT allows you to explicitly specify an index or unique constraint for INSERT ON CONFLICT, rather than inferring one using a column list, which is the default behavior.

INSERT ON CONFLICT vs. UPSERT

As an alternative to INSERT ... ON CONFLICT ... DO UPDATE, you can use the statement. For example, the following statements are equivalent:
However, UPSERT does not let you specify columns to infer a unique constraint as an arbiter. An arbiter is a constraint used to check for conflicts during execution of INSERT ... ON CONFLICT. UPSERT always uses the primary key as the arbiter. You must therefore use INSERT ... ON CONFLICT ... DO UPDATE if your statement considers uniqueness for columns other than primary key columns. For an example, see . When inserting or updating columns on a table that does not have , Cockroach Labs recommends using an UPSERT statement instead of INSERT ON CONFLICT DO UPDATE. Whereas INSERT ON CONFLICT always performs a read, the UPSERT statement writes without reading, making it faster. This may be useful if you are using a simple SQL table of two columns to . If the table has a secondary index, there is no performance difference between UPSERT and INSERT ON CONFLICT. However, INSERT without an ON CONFLICT clause may not scan the table for existing values. This can provide a performance improvement over UPSERT.

Performance best practices

When generating and retrieving unique IDs, use the RETURNING clause with INSERT. See Insert and Return Values for details. In traditional SQL databases, you would do this using INSERT with SELECT, which is less performant.

Bulk inserts

  • Existing table
    • Perform a multi-row INSERT in one statement in an .
    • Do not use large batches of 100,000 rows or more, which can lead to long-running transactions that result in . If a multi-row INSERT results in an error code , Cockroach Labs recommends that you break up the INSERT into smaller batches. Experimentally determine the optimal batch size for your application by monitoring the performance for different batch sizes (1, 10, 100, 1000) rows in an implicit transaction. In some cases, for example, when a table has no secondary indexes, single row INSERTs may perform best in terms of total system throughput.
    • You can also use the statement to bulk-insert CSV data.

Examples

Setup

To follow along, run to start a temporary, in-memory cluster with the sample dataset preloaded:

Insert a single row

If you do not list column names, the statement will use the columns of the table in their declared order:

Insert multiple rows into an existing table

See bulk inserts for best practices.

Insert from a SELECT statement

Suppose that you want MovR to offer ride-sharing services, in addition to vehicle-sharing services. You can create a drivers table from a subset of the users table.

Insert default values

To check the for columns in a table, use the statement:
If the DEFAULT value constraint is not specified and an explicit value is not given, a value of NULL is assigned to the column.
To create a new row with only default values, use INSERT INTO DEFAULT VALUES. Running this command on the drivers table results in an error because the city column in drivers cannot be NULL, and has no default value specified.

Insert and return values

In this example, the RETURNING clause returns the id values of the rows inserted, which are generated server-side by the gen_random_uuid() function. The language-specific versions assume that you have installed the relevant .

Update values ON CONFLICT

When a uniqueness conflict on columns (city, user_id, code) is detected, CockroachDB stores the rows proposed for insertion in a temporary table called excluded. This example demonstrates how you use the columns in the temporary excluded table to apply updates on conflict.
You can also update the row using an existing value:
You can also use a WHERE clause to apply the DO UPDATE SET expression conditionally:
This example uses the ON CONSTRAINT clause to explicitly specify the index user_promo_codes_pkey on which there is a conflict:

Do not update values ON CONFLICT

In this example, we get an error from a uniqueness conflict.
This example uses ON CONFLICT DO NOTHING to ignore the uniqueness error and prevent the affected row from being updated:
In this example, ON CONFLICT DO NOTHING prevents the first row from updating while allowing the second row to be inserted:

Import data containing duplicate rows using ON CONFLICT and DISTINCT ON

If the input data for INSERT ON CONFLICT contains duplicate rows, you must use to remove these duplicates. For example:
The DISTINCT ON clause does not guarantee which of the duplicates is considered. To force the selection of a particular duplicate, use an ORDER BY clause:
Using DISTINCT ON incurs a performance cost to search and eliminate duplicates. For best performance, avoid using it when the input is known to not contain duplicates.

See also