INSERT
INSERT — create new rows in a table
Synopsis
[ WITH [ RECURSIVE ]with_query[, ...] ]INSERT INTOtable_name[ ASalias] [ (column_name[, ...] ) ] { DEFAULT VALUES | VALUES ( {expression| DEFAULT } [, ...] ) [, ...] |query} [ ON CONFLICT [conflict_target]conflict_action] [ RETURNING * |output_expression[ [ AS ]output_name] [, ...] ]whereconflict_targetcan be one of: ( {index_column_name| (index_expression) } [ COLLATEcollation] [opclass] [, ...] ) [ WHEREindex_predicate] ON CONSTRAINTconstraint_nameandconflict_actionis one of: DO NOTHING DO UPDATE SET {column_name= {expression| DEFAULT } | (column_name[, ...] ) = ( {expression| DEFAULT } [, ...] ) | (column_name[, ...] ) = (sub-SELECT) } [, ...] [ WHEREcondition]
Description
INSERT inserts new rows into a table. One can insert one or more rows specified by value expressions, or zero or more rows resulting from a query.
The target column names can be listed in any order. If no list of column names is given at all, the default is all the columns of the table in their declared order; or the firstN column names, if there are onlyN columns supplied by theVALUES clause orquery. The values supplied by theVALUES clause orquery are associated with the explicit or implicit column list left-to-right.
Each column not present in the explicit or implicit column list will be filled with a default value, either its declared default value or null if there is none.
If the expression for any column is not of the correct data type, automatic type conversion will be attempted.
ON CONFLICT can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (SeeON CONFLICT Clause below.)
The optionalRETURNING clause causesINSERT to compute and return value(s) based on each row actually inserted (or updated, if anON CONFLICT DO UPDATE clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed. The syntax of theRETURNING list is identical to that of the output list ofSELECT. Only rows that were successfully inserted or updated will be returned. For example, if a row was locked but not updated because anON CONFLICT DO UPDATE ... WHERE clausecondition was not satisfied, the row will not be returned.
You must haveINSERT privilege on a table in order to insert into it. IfON CONFLICT DO UPDATE is present,UPDATE privilege on the table is also required.
If a column list is specified, you only needINSERT privilege on the listed columns. Similarly, whenON CONFLICT DO UPDATE is specified, you only needUPDATE privilege on the column(s) that are listed to be updated. However,ON CONFLICT DO UPDATE also requiresSELECT privilege on any column whose values are read in theON CONFLICT DO UPDATE expressions orcondition.
Use of theRETURNING clause requiresSELECT privilege on all columns mentioned inRETURNING. If you use thequery clause to insert rows from a query, you of course need to haveSELECT privilege on any table or column used in the query.
Parameters
Inserting
This section covers parameters that may be used when only inserting new rows. Parametersexclusively used with theON CONFLICT clause are described separately.
with_queryThe
WITHclause allows you to specify one or more subqueries that can be referenced by name in theINSERTquery. SeeSection 7.8 andSELECT for details.It is possible for the
query(SELECTstatement) to also contain aWITHclause. In such a case both sets ofwith_querycan be referenced within thequery, but the second one takes precedence since it is more closely nested.table_nameThe name (optionally schema-qualified) of an existing table.
aliasA substitute name for
table_name. When an alias is provided, it completely hides the actual name of the table. This is particularly useful whenON CONFLICT DO UPDATEtargets a table named excluded, since that's also the name of the special table representing rows proposed for insertion.column_nameThe name of a column in the table named by
table_name. The column name can be qualified with a subfield name or array subscript, if needed. (Inserting into only some fields of a composite column leaves the other fields null.) When referencing a column withON CONFLICT DO UPDATE, do not include the table's name in the specification of a target column. For example,INSERT INTO table_name ... ON CONFLICT DO UPDATE SET table_name.col = 1is invalid (this follows the general behavior forUPDATE).DEFAULT VALUESAll columns will be filled with their default values.
expressionAn expression or value to assign to the corresponding column.
DEFAULTThe corresponding column will be filled with its default value.
queryA query (
SELECTstatement) that supplies the rows to be inserted. Refer to theSELECT statement for a description of the syntax.output_expressionAn expression to be computed and returned by the
INSERTcommand after each row is inserted or updated. The expression can use any column names of the table named bytable_name. Write*to return all columns of the inserted or updated row(s).output_nameA name to use for a returned column.
ON CONFLICT Clause
The optionalON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if anarbiter constraint or index specified byconflict_target is violated, the alternativeconflict_action is taken.ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action.ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.
conflict_target can performunique index inference. When performing inference, it consists of one or moreindex_column_name columns and/orindex_expression expressions, and an optionalindex_predicate. Alltable_name unique indexes that, without regard to order, contain exactly theconflict_target-specified columns/expressions are inferred (chosen) as arbiter indexes. If anindex_predicate is specified, it must, as a further requirement for inference, satisfy arbiter indexes. Note that this means a non-partial unique index (a unique index without a predicate) will be inferred (and thus used byON CONFLICT) if such an index satisfying every other criteria is available. If an attempt at inference is unsuccessful, an error is raised.
ON CONFLICT DO UPDATE guarantees an atomicINSERT orUPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known asUPSERT —“UPDATE or INSERT”.
conflict_targetSpecifies which conflicts
ON CONFLICTtakes the alternative action on by choosingarbiter indexes. Either performsunique index inference, or names a constraint explicitly. ForON CONFLICT DO NOTHING, it is optional to specify aconflict_target; when omitted, conflicts with all usable constraints (and unique indexes) are handled. ForON CONFLICT DO UPDATE, aconflict_targetmust be provided.conflict_actionconflict_actionspecifies an alternativeON CONFLICTaction. It can be eitherDO NOTHING, or aDO UPDATEclause specifying the exact details of theUPDATEaction to be performed in case of a conflict. TheSETandWHEREclauses inON CONFLICT DO UPDATEhave access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the specialexcludedtable.SELECTprivilege is required on any column in the target table where correspondingexcludedcolumns are read.Note that the effects of all per-row
BEFORE INSERTtriggers are reflected inexcludedvalues, since those effects may have contributed to the row being excluded from insertion.index_column_nameThe name of a
table_namecolumn. Used to infer arbiter indexes. FollowsCREATE INDEXformat.SELECTprivilege onindex_column_nameis required.index_expressionSimilar to
index_column_name, but used to infer expressions ontable_namecolumns appearing within index definitions (not simple columns). FollowsCREATE INDEXformat.SELECTprivilege on any column appearing withinindex_expressionis required.collationWhen specified, mandates that corresponding
index_column_nameorindex_expressionuse a particular collation in order to be matched during inference. Typically this is omitted, as collations usually do not affect whether or not a constraint violation occurs. FollowsCREATE INDEXformat.opclassWhen specified, mandates that corresponding
index_column_nameorindex_expressionuse particular operator class in order to be matched during inference. Typically this is omitted, as theequality semantics are often equivalent across a type's operator classes anyway, or because it's sufficient to trust that the defined unique indexes have the pertinent definition of equality. FollowsCREATE INDEXformat.index_predicateUsed to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows
CREATE INDEXformat.SELECTprivilege on any column appearing withinindex_predicateis required.constraint_nameExplicitly specifies an arbiterconstraint by name, rather than inferring a constraint or index.
conditionAn expression that returns a value of type
boolean. Only rows for which this expression returnstruewill be updated, although all rows will be locked when theON CONFLICT DO UPDATEaction is taken. Note thatconditionis evaluated last, after a conflict has been identified as a candidate to update.
Note that exclusion constraints are not supported as arbiters withON CONFLICT DO UPDATE. In all cases, onlyNOT DEFERRABLE constraints and unique indexes are supported as arbiters.
INSERT with anON CONFLICT DO UPDATE clause is a“deterministic” statement. This means that the command will not be allowed to affect any single existing row more than once; a cardinality violation error will be raised when this situation arises. Rows proposed for insertion should not duplicate each other in terms of attributes constrained by an arbiter index or constraint.
Tip
It is often preferable to use unique index inference rather than naming a constraint directly usingON CONFLICT ON CONSTRAINT constraint_name. Inference will continue to work correctly when the underlying index is replaced by another more or less equivalent index in an overlapping way, for example when usingCREATE UNIQUE INDEX ... CONCURRENTLY before dropping the index being replaced.
Outputs
On successful completion, anINSERT command returns a command tag of the form
INSERToidcount
The If thecount is the number of rows inserted or updated. Ifcount is exactly one, and the target table has OIDs, thenoid is theOID assigned to the inserted row. The single row must have been inserted rather than updated. Otherwiseoid is zero.INSERT command contains aRETURNING clause, the result will be similar to that of aSELECT statement containing the columns and values defined in theRETURNING list, computed over the row(s) inserted or updated by the command.
Examples
Insert a single row into tablefilms:
INSERT INTO films VALUES ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); In this example, thelen column is omitted and therefore it will have the default value:
INSERT INTO films (code, title, did, date_prod, kind) VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama'); This example uses theDEFAULT clause for the date columns rather than specifying a value:
INSERT INTO films VALUES ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes');INSERT INTO films (code, title, did, date_prod, kind) VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama');To insert a row consisting entirely of default values:
INSERT INTO films DEFAULT VALUES;
To insert multiple rows using the multirowVALUES syntax:
INSERT INTO films (code, title, did, date_prod, kind) VALUES ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'), ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy'); This example inserts some rows into tablefilms from a tabletmp_films with the same column layout asfilms:
INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';
This example inserts into array columns:
-- Create an empty 3x3 gameboard for noughts-and-crossesINSERT INTO tictactoe (game, board[1:3][1:3]) VALUES (1, '{{" "," "," "},{" "," "," "},{" "," "," "}}');-- The subscripts in the above example aren't really neededINSERT INTO tictactoe (game, board) VALUES (2, '{{X," "," "},{" ",O," "},{" ",X," "}}'); Insert a single row into tabledistributors, returning the sequence number generated by theDEFAULT clause:
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') RETURNING did;
Increment the sales count of the salesperson who manages the account for Acme Corporation, and record the whole updated row along with current time in a log table:
WITH upd AS ( UPDATE employees SET sales_count = sales_count + 1 WHERE id = (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation') RETURNING *)INSERT INTO employees_log SELECT *, current_timestamp FROM upd;
Insert or update new distributors as appropriate. Assumes a unique index has been defined that constrains values appearing in thedid column. Note that the specialexcluded table is used to reference values originally proposed for insertion:
INSERT INTO distributors (did, dname) VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc') ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;
Insert a distributor, or do nothing for rows proposed for insertion when an existing, excluded row (a row with a matching constrained column or columns after before row insert triggers fire) exists. Example assumes a unique index has been defined that constrains values appearing in thedid column:
INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH') ON CONFLICT (did) DO NOTHING;
Insert or update new distributors as appropriate. Example assumes a unique index has been defined that constrains values appearing in thedid column.WHERE clause is used to limit the rows actually updated (any existing row not updated will still be locked, though):
-- Don't update existing distributors based in a certain ZIP codeINSERT INTO distributors AS d (did, dname) VALUES (8, 'Anvil Distribution') ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname || ' (formerly ' || d.dname || ')' WHERE d.zipcode <> '21201';-- Name a constraint directly in the statement (uses associated-- index to arbitrate taking the DO NOTHING action)INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design') ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;
Insert new distributor if possible; otherwiseDO NOTHING. Example assumes a unique index has been defined that constrains values appearing in thedid column on a subset of rows where theis_active Boolean column evaluates totrue:
-- This statement could infer a partial unique index on "did"-- with a predicate of "WHERE is_active", but it could also-- just use a regular unique constraint on "did"INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International') ON CONFLICT (did) WHERE is_active DO NOTHING;
Compatibility
INSERT conforms to the SQL standard, except that theRETURNING clause is aPostgreSQL extension, as is the ability to useWITH withINSERT, and the ability to specify an alternative action withON CONFLICT. Also, the case in which a column name list is omitted, but not all the columns are filled from theVALUES clause orquery, is disallowed by the standard.
Possible limitations of thequery clause are documented underSELECT.