INSERT statement 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
You must have theINSERT privilege on the table.
To use ON CONFLICT, you must also have the SELECT privilege on the table.
To use ON CONFLICT DO UPDATE, you must additionally have the UPDATE privilege on the table.
Syntax
Parameters
See Common Table Expressions.
The table into which data is written.
An alias for the table name. When you provide an alias, it completely hides the actual table name.
The name of a column to populate during the insert.
A selection query. Each value must match the data type of its column. 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.To fill all columns with their default values, 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.Return values based on rows inserted, where
target_list can be specific column names from the table, * for all columns, or computations using scalar expressions.ON CONFLICT clause
Normally, when inserted values conflict with aUNIQUE 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.
To prevent the affected rows from updating while allowing new rows to be inserted, set ON CONFLICT to DO NOTHING.
INSERT ON CONFLICT vs. UPSERT
As an alternative toINSERT ... ON CONFLICT ... DO UPDATE, you can use the UPSERT statement. For example, the following statements are equivalent:
UPSERT does not let you specify columns to infer a unique constraint as an arbiter. UPSERT always uses the primary key as the arbiter.
Performance best practices
When generating and retrieving unique IDs, use theRETURNING clause with INSERT.
Bulk inserts
For existing tables:- Perform a multi-row
INSERTin one statement in an implicit transaction - Do not use large batches of 100,000 rows or more, which can lead to long-running transactions
- Experimentally determine the optimal batch size for your application
Examples
Insert a single row
Insert multiple rows
Insert from a SELECT statement
Suppose you want to create adrivers table from a subset of the users table:
Insert default values
To check the default values for columns in a table, use theSHOW CREATE TABLE 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.
Insert and return values
In this example, theRETURNING clause returns the id values of the rows inserted:
Update values ON CONFLICT
Do not update values ON CONFLICT
See also
- UPSERT
- UPDATE
- DELETE
- SELECT