INSERT(7)
π NAME π
Hey bestie, this is INSERT(7) from the PostgreSQL 16.15 Documentation β the page for INSERT, and its whole job is create new rows in a table. πβ¨
β¨ SYNOPSIS β¨
[ WITH [ RECURSIVE ] with_query [, ...] ]
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
[ OVERRIDING { SYSTEM | USER } VALUE ]
{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
[ ON CONFLICT [ conflict_target ] conflict_action ]
[ RETURNING { * | output_expression [ [ AS ] output_name ] } [, ...] ]
where conflict_target can be one of:
( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
ON CONSTRAINT constraint_name
and conflict_action is one of:
DO NOTHING
DO UPDATE SET { column_name = { expression | DEFAULT } |
( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
( column_name [, ...] ) = ( sub-SELECT )
} [, ...]
[ WHERE condition ]
π¦ DESCRIPTION π¦
INSERT inserts new rows into a table. π
You can insert one or more rows specified by value expressions, or zero or more rows resulting from a query. Both are valid, no cap.
The target column names can be listed in any order β iconic. 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 first N column names, if there are only N columns supplied by the VALUES clause or query. The values supplied by the VALUES clause or query are associated with the explicit or implicit column list left-to-right. Periodt.
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. π«Ά
Now the concurrency tea: INSERT into tables that lack unique indexes will not be blocked by concurrent activity. Tables with unique indexes might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted; the details are covered in Section 64.5. π ON CONFLICT can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See ON CONFLICT Clause below.)
The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON 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 the RETURNING list is identical to that of the output list of SELECT. Only rows that were successfully inserted or updated will be returned. For example, if a row was locked but not updated because an ON CONFLICT DO UPDATE ... WHERE clause condition was not satisfied, the row will not be returned. π
Privilege check, bestie: you must have INSERT privilege on a table in order to insert into it. If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is also required. π
If a column list is specified, you only need INSERT privilege on the listed columns. Similarly, when ON CONFLICT DO UPDATE is specified, you only need UPDATE privilege on the column(s) that are listed to be updated. However, all forms of ON CONFLICT also require SELECT privilege on any column whose values are read. This includes any column mentioned in conflict_target (including columns referred to by the arbiter constraint), and any column mentioned in an ON CONFLICT DO UPDATE expression, or a WHERE clause condition. β¨
Use of the RETURNING clause requires SELECT privilege on all columns mentioned in RETURNING. If you use the query clause to insert rows from a query, you of course need to have SELECT privilege on any table or column used in the query. π¦
π PARAMETERS π
okay so this section covers parameters that may be used when only inserting new rows. Parameters exclusively used with the ON CONFLICT clause are described separately. slay, we love a clean separation. β¨
πΈ Inserting πΈ
with_queryβ theWITHclause lets you specify one or more subqueries that can be referenced by name in theINSERTquery. See Section 7.8 andSELECT(7)for details. iykyk
It is possible for the query (SELECT statement) to also contain a WITH clause. In such a case both sets of with_query can be referenced within the query, but the second one takes precedence since it is more closely nested. nesting drama, but make it SQL.
table_nameβ the name (optionally schema-qualified) of an existing table. literally the main character table. πaliasβ a substitute name fortable_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 namedexcluded, since that will otherwise be taken as the name of the special table representing the row proposed for insertion. ngl this alias trick is lowkey iconic. πcolumn_nameβ the name of a column in the table named bytable_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). fr fr, do not do that.OVERRIDING SYSTEM VALUEβ if this clause is specified, then any values supplied for identity columns will override the default sequence-generated values. periodt, the system value gets overridden.
For an identity column defined as GENERATED ALWAYS, it is an error to insert an explicit value (other than DEFAULT) without specifying either OVERRIDING SYSTEM VALUE or OVERRIDING USER VALUE. (For an identity column defined as GENERATED BY DEFAULT, OVERRIDING SYSTEM VALUE is the normal behavior and specifying it does nothing, but PostgreSQL allows it as an extension.) Postgres being chill as an extension? we love to see it.
OVERRIDING USER VALUEβ if this clause is specified, then any values supplied for identity columns are ignored and the default sequence-generated values are applied. ignored, bestie. not even looked at.
This clause is useful for example when copying values between tables. Writing INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 will copy from tbl1 all columns that are not identity columns in tbl2 while values for the identity columns in tbl2 will be generated by the sequences associated with tbl2. copy-paste but make it identity-safe. π¦
DEFAULT VALUESβ all columns will be filled with their default values, as ifDEFAULTwere explicitly specified for each column. (AnOVERRIDINGclause is not permitted in this form.) noOVERRIDINGallowed here, the vibes are strict.expressionβ an expression or value to assign to the corresponding column. the actual value, the moment, the main event.DEFAULTβ the corresponding column will be filled with its default value. An identity column will be filled with a new value generated by the associated sequence. For a generated column, specifying this is permitted but merely specifies the normal behavior of computing the column from its generation expression. default is just the column doing its usual thing, no cap.queryβ a query (SELECTstatement) that supplies the rows to be inserted. Refer to theSELECT(7)statement for a description of the syntax. go readSELECT(7)if you need the syntax tea.output_expressionβ an expression to be computed and returned by theINSERTcommand 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). star means all the columns, bestie. all of them. πoutput_nameβ a name to use for a returned column. give your returned column a cute little name. π
π¦ ON CONFLICT Clause π¦
The optional ON 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 an arbiter constraint or index specified by conflict_target is violated, the alternative conflict_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. not me being obsessed with conflict resolution that isn't emotional. π
conflict_target can perform unique index inference. When performing inference, it consists of one or more index_column_name columns and/or index_expression expressions, and an optional index_predicate. All table_name unique indexes that, without regard to order, contain exactly the conflict_target-specified columns/expressions are inferred (chosen) as arbiter indexes. If an index_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 by ON CONFLICT) if such an index satisfying every other criteria is available. If an attempt at inference is unsuccessful, an error is raised. inference said "bestie, no." and raised an error.
ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT β βUPDATE or INSERTβ. UPSERT! the icon, the legend, the moment. β¨
conflict_targetβ specifies which conflictsON CONFLICTtakes the alternative action on by choosing arbiter indexes. Either performs unique 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. forDO UPDATE, you literally have to provide it. no skipping.conflict_actionβconflict_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 the row proposed for insertion using the specialexcludedtable.SELECTprivilege is required on any column in the target table where correspondingexcludedcolumns are read. theexcludedtable is giving special guest star energy.
Note that the effects of all per-row BEFORE INSERT triggers are reflected in excluded values, since those effects may have contributed to the row being excluded from insertion. triggers really said "I was involved."
index_column_nameβ the name of atable_namecolumn. Used to infer arbiter indexes. FollowsCREATE INDEXformat.SELECTprivilege onindex_column_nameis required. privilege check? required. periodt.index_expressionβ similar toindex_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. not a simple column, bestie. an expression. keep up.collationβ when specified, mandates that correspondingindex_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. usually omitted because collations aren't the drama here.opclassβ when specified, mandates that correspondingindex_column_nameorindex_expressionuse particular operator class in order to be matched during inference. Typically this is omitted, as the equality 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. usually omitted, trust the unique indexes, they know what equality means.index_predicateβ used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. FollowsCREATE INDEXformat.SELECTprivilege on any column appearing withinindex_predicateis required. partial unique indexes said "let me in." and this is the door.constraint_nameβ explicitly specifies an arbiter constraint by name, rather than inferring a constraint or index. naming names instead of doing inference. bold move.conditionβ an expression that returns a value of typeboolean. 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. it's evaluated last, so don't act like it's first. π
Note that exclusion constraints are not supported as arbiters with ON CONFLICT DO UPDATE. In all cases, only NOT DEFERRABLE constraints and unique indexes are supported as arbiters. exclusion constraints are NOT invited to the arbiter party with DO UPDATE. and only NOT DEFERRABLE plus unique indexes are invited at all.
INSERT with an ON 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. one row, one update. no double-dipping. cardinality violation says "absolutely not." π
Note that it is currently not supported for the ON CONFLICT DO UPDATE clause of an INSERT applied to a partitioned table to update the partition key of a conflicting row such that it requires the row be moved to a new partition. partition key updates that move rows? currently not supported, bestie. don't try it.
β¨ 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 ... CONCURRENTLYbefore dropping the index being replaced. inference is the lowkey superior choice here. it keeps working when indexes swap around.
π Warning π WhileCREATE INDEX CONCURRENTLYorREINDEX CONCURRENTLYis running on a unique index,INSERT ... ON CONFLICTstatements on the same table may unexpectedly fail with a unique violation. not a vibe. be aware.
β¨ OUTPUTS β¨
On successful completion, an INSERT command returns a command tag of the form
INSERT oid count
The count is the number of rows inserted or updated. oid is always 0 (it used to be the OID assigned to the inserted row if count was exactly one and the target table was declared WITH OIDS and 0 otherwise, but creating a table WITH OIDS is not supported anymore). oid said "I'm always 0 now," and honestly? character development. π«Ά
If the INSERT command contains a RETURNING clause, the result will be similar to that of a SELECT statement containing the columns and values defined in the RETURNING list, computed over the row(s) inserted or updated by the command. RETURNING really said "and I'll show you what I did." iconic. π
β¨ NOTES β¨
ok so quick vibe check before you yeet rows into the void π
- If the table you named is a partitioned table, every row gets routed to the right partition and inserted in there. Slay, automatic.
- But if the table you named is itself a partition? Then if any input row violates the partition constraint, you get an error. No cap, it will not be chill about it.
- Also bestie, lowkey consider using
MERGE, because that lets you mixINSERT,UPDATE, andDELETEall inside one single statement. Chef's kiss. SeeMERGE(7). π«Ά
πΈ EXAMPLES πΈ
ok these are the fun ones, let's go π
Drop a single row into table films:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Here the len column is omitted, so it just gets its default value. Iconic, honestly:
INSERT INTO films (code, title, did, date_prod, kind)
VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');
This next one uses the DEFAULT clause for the date columns instead of actually 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');
Wanna insert a row that is entirely default values? Say less:
INSERT INTO films DEFAULT VALUES;
Multirow VALUES syntax, my beloved π:
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 pulls some rows into table films from a table tmp_films that has the same column layout as films:
INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';
Now we're inserting into array columns, which is giving main character energy tbh:
-- Create an empty 3x3 gameboard for noughts-and-crosses
INSERT INTO tictactoe (game, board[1:3][1:3])
VALUES (1, '{{" "," "," "},{" "," "," "},{" "," "," "}}');
-- The subscripts in the above example aren't really needed
INSERT INTO tictactoe (game, board)
VALUES (2, '{{X," "," "},{" ",O," "},{" ",X," "}}');
Insert a single row into table distributors, and hand back the sequence number that the DEFAULT clause generated:
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;
Bump the sales count of the salesperson who manages the account for Acme Corporation, and log the whole updated row plus the current time into a log table. Obsessed with this one:
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. This assumes a unique index has been defined that constrains the values appearing in the did column. Ngl, note that the special excluded table is how you 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 exists (that's a row with a matching constrained column or columns, after before-row insert triggers fire). This example assumes a unique index has been defined that constrains the values appearing in the did 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 the values appearing in the did column. The WHERE clause is used to limit the rows actually updated β any existing row that doesn't get updated will still be locked, though π:
-- Don't update existing distributors based in a certain ZIP code
INSERT 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 a new distributor if possible; otherwise DO NOTHING. This example assumes a unique index has been defined that constrains the values appearing in the did column on a subset of rows where the is_active Boolean column evaluates to true:
-- 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 β with a few lil exceptions that are very PostgreSQL of it:
- The
RETURNINGclause is a PostgreSQL extension β¨ - So is the ability to use
WITHwithINSERT - So is the ability to specify an alternative action with
ON CONFLICT - Also: the case where a column name list is omitted, but not all the columns are filled from the
VALUESclause or query β the standard disallows that. PostgreSQL lets you live your truth. - If you'd prefer a statement that conforms more closely to the SQL standard than
ON CONFLICT, go look atMERGE(7).
The SQL standard specifies that OVERRIDING SYSTEM VALUE can only be specified if an identity column that is generated always exists. PostgreSQL allows the clause in any case and just ignores it if it isn't applicable. Slight chaotic energy, we respect it.
Possible limitations of the query clause are documented under SELECT(7).
ok that's the whole page bestie, go forth and insert responsibly π¦π
this lil beauty was brought to you by PostgreSQL 16.15, dated 2026, and filed under INSERT(7) β mwah, periodt π π
π¦ where this page comes from
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms