INSERT(7)
๐ NAME ๐
INSERT โ bestie, this is the one that creates new rows in a table โจ (and yes, this is the INSERT(7) page from the PostgreSQL 18.6 docs, we're doing this together ๐ซถ)
โจ SYNOPSIS โจ
Like, here's the whole shape of it, no cap:
[ 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 [ WITH ( { OLD | NEW } AS output_alias [, ...] ) ]
{ * | 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 ๐ธ
So INSERT inserts new rows into a table. You can drop in one or more rows using value expressions, or zero or more rows coming out of a query. Zero rows is allowed bestie, it's giving "nothing to see here" and that's fine ๐
The target column names? Any order you want, queen. If you don't give a column list at all, the default is all the columns of the table in their declared order โ or, if your VALUES clause or query only hands over N columns, it's the first N column names. And the values you supply get matched up with the explicit-or-implicit column list left-to-right, in order, no vibes-based shuffling.
Every column that's not in that list gets filled with a default value โ either its declared default, or null if it doesn't have one. That's just how it is ๐
If the expression for any column isn't the right data type, PostgreSQL will attempt automatic type conversion. Lowkey magic, highkey useful.
Inserting into tables that lack unique indexes will not be blocked by concurrent activity. But tables with unique indexes might block if concurrent sessions do stuff that locks or modifies rows matching the unique index values you're inserting โ all the gory details live in Section 63.5. ON CONFLICT can be used to specify an alternative action instead of raising a unique constraint or exclusion constraint violation error. (Peep the ON CONFLICT Clause section below ๐)
The optional RETURNING clause makes INSERT compute and return value(s) based on each row that actually got inserted (or updated, if you used an ON CONFLICT DO UPDATE clause). This is mostly useful for grabbing values that came from defaults, like a serial sequence number. But honestly any expression using the table's columns is allowed. The syntax of the RETURNING list is identical to the output list of SELECT. Only rows that were successfully inserted or updated get returned. For example, if a row was locked but not updated because an ON CONFLICT DO UPDATE ... WHERE clause condition wasn't satisfied โ that row is not returned. Not even a little.
You must have INSERT privilege on a table to insert into it. And if ON CONFLICT DO UPDATE is present, you also need UPDATE privilege on the table.
If you specify a column list, you only need INSERT privilege on the listed columns. Same energy with ON CONFLICT DO UPDATE โ you only need UPDATE privilege on the column(s) listed to be updated. However ๐ all forms of ON CONFLICT also require SELECT privilege on any column whose values are read. That 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.
Using the RETURNING clause requires SELECT privilege on all columns mentioned in RETURNING. And if you use the query clause to insert rows from a query โ yeah, of course you need SELECT privilege on any table or column used in that query. Obviously. ๐
๐ PARAMETERS ๐
Inserting
This section covers the parameters you might use when you're only inserting new rows. The parameters that are exclusively for the ON CONFLICT clause get their own separate glow-up down below โจ
with_queryโ theWITHclause lets you specify one or more subqueries that can be referenced by name inside theINSERTquery. Details live in Section 7.8 andSELECT(7), go read 'em bestie.
It's possible for the query (the SELECT statement) to also contain a WITH clause. When that happens, both sets of with_query can be referenced inside the query โ but the second one takes precedence, because it's more closely nested. Closest one wins, that's the rule ๐
table_nameโ the name (optionally schema-qualified) of an existing table.aliasโ a substitute name fortable_name. When you give an alias, it completely hides the actual name of the table. This is especially useful whenON CONFLICT DO UPDATEtargets a table namedexcludedโ because otherwise that name gets taken as the special table representing the row proposed for insertion. Awkward, so alias it. ๐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 fieldsnull.) 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).OVERRIDING SYSTEM VALUEโ if this clause is specified, then any values you supply for identity columns will override the default sequence-generated values.
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.)
OVERRIDING USER VALUEโ if this clause is specified, then any values you supply for identity columns are ignored and the default sequence-generated values are applied. Sorry bestie, they're going in the bin ๐๏ธ
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. Chef's kiss ๐
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. Don't try it.)expressionโ an expression or value to assign to the corresponding column.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.queryโ a query (aSELECTstatement) that supplies the rows to be inserted. Go check theSELECT(7)statement for a description of the syntax.output_aliasโ an optional substitute name forOLDorNEWrows in theRETURNINGlist.
By default, old values from the target table can be returned by writing OLD.column_name or OLD.*, and new values can be returned by writing NEW.column_name or NEW.*. When an alias is provided, those names get hidden and the old or new rows must be referred to using the alias. For example RETURNING WITH (OLD AS o, NEW AS n) o.*, n.*.
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).
A column name or * may be qualified using OLD or NEW, or the corresponding output_alias for OLD or NEW, to make old or new values come back. An unqualified column name, or *, or a column name or * qualified using the target table name or alias, will return new values.
For a simple INSERT, all old values will be NULL. However, for an INSERT with an ON CONFLICT DO UPDATE clause, the old values may be non-NULL. Plot twist ๐
output_nameโ a name to use for a returned column.
ON CONFLICT Clause
The optional ON CONFLICT clause specifies an alternative action instead of 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. Pick your fighter ๐
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, plus 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. No inference, no mercy.
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". Say it with me, iconic behavior โจ
conflict_targetโ specifies which conflictsON CONFLICTtakes the alternative action on, by choosing arbiter indexes. It either performs unique index inference, or names a constraint explicitly. ForON CONFLICT DO NOTHING, it's 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. Non-negotiable, bestie ๐ซถconflict_actionโ bestie, this is the alternativeON CONFLICTaction, and itโs giving two options: eitherDO NOTHING, or aDO UPDATEclause that spells out exactly what UPDATE should happen when a conflict pops off. ๐ TheSETandWHEREclauses insideON CONFLICT DO UPDATEcan see the existing row via the tableโs name (or an alias), and the row you were trying to insert via the specialexcludedtable. You needSELECTprivilege on any column in the target table where correspondingexcludedcolumns are read. ๐
Also, a little note: the effects of all per-row BEFORE INSERT triggers are reflected in excluded values, because those effects may have contributed to the row being excluded from insertion. No cap.
index_column_nameโ the name of atable_namecolumn. Used to infer arbiter indexes. FollowsCREATE INDEXformat.SELECTprivilege onindex_column_nameis required. โจ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. ๐ฆcollationโ when you specify this, it mandates that the correspondingindex_column_nameorindex_expressionuse a particular collation in order to be matched during inference. Typically you omit this, because collations usually donโt affect whether or not a constraint violation occurs. FollowsCREATE INDEXformat. ๐opclassโ when specified, it mandates that the correspondingindex_column_nameorindex_expressionuse a particular operator class in order to be matched during inference. Typically omitted, since 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. ๐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. ๐ธconstraint_nameโ explicitly specifies an arbiter constraint by name, rather than inferring a constraint or index. Simple as that. ๐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. ๐ฅ
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. ๐ซ
INSERT with an ON CONFLICT DO UPDATE clause is a โdeterministicโ statement. That means 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. ๐ญ
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. ๐
๐ก Tip
It is often preferable to use unique index inference rather than naming a constraint directly using ON 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 using CREATE UNIQUE INDEX ... CONCURRENTLY before dropping the index being replaced. ๐
โ ๏ธ Warning
While CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is running on a unique index, INSERT ... ON CONFLICT statements on the same table may unexpectedly fail with a unique violation. ๐
โจ 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). ๐ซถ
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. ๐
๐ซถ NOTES ๐ซถ
If the specified table is a partitioned table, each row is routed to the appropriate partition and inserted into it. If the specified table is a partition, an error will occur if one of the input rows violates the partition constraint. ๐ง
You may also wish to consider using MERGE, since that allows mixing INSERT, UPDATE, and DELETE within a single statement. See MERGE(7). ๐
๐ EXAMPLES ๐
Insert a single row into table films:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
In this example, the len 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 the DEFAULT 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 multirow VALUES 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 table films from a table tmp_films with the same column layout as films:
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-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, returning the sequence number generated by the DEFAULT 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 the did column. Note that the special excluded 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 or update new distributors as above, returning information about any existing values that were updated, together with the new data inserted. Note that the returned values for old_did and old_dname will be NULL for non-conflicting rows:
INSERT INTO distributors (did, dname)
VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname
RETURNING old.did AS old_did, old.dname AS old_dname,
new.did AS new_did, new.dname AS new_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 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 values appearing in the did 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 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 new distributor if possible; otherwise DO NOTHING. Example assumes a unique index has been defined that constrains 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 ๐
okay bestie, gather round, because this is the part where we find out how much of this is โจstandardโจ and how much is just PostgreSQL doing its own thing ๐
INSERT conforms to the SQL standard, except for a few little flourishes that are very much our house rules:
- the
RETURNINGclause is a PostgreSQL extension โ the standard did NOT come up with this, we did, and honestly? iconic of us ๐ - so is the ability to use
WITHwithINSERT๐ธ - and so is the ability to specify an alternative action with
ON CONFLICT๐ฆ
Also, there's this one case that the standard is not a fan of: when you omit the column name list but not all of the columns are filled from the VALUES clause or the query โ the standard says no, disallowed, absolutely not ๐
โโ๏ธ PostgreSQL lets you do it anyway, but just know the standard is side-eyeing you.
if you want something more standard-conforming than ON CONFLICT, go peek at MERGE(7) ๐
The SQL standard also says that OVERRIDING SYSTEM VALUE can only be specified if an identity column that is GENERATED ALWAYS exists. PostgreSQL is way more chill about it: it allows the clause in any case, and just ignores it if it's not applicable. no drama, no error, just vibes ๐
And one last thing โ any possible limitations of the query clause are documented over in SELECT(7), so go read that if you're curious ๐โจ
and that's a wrap on this whole page, bestie!!</purl> this little masterpiece is from PostgreSQL 18.6, dated 2026, and it lives its best life as INSERT(7) ๐ you now know more about inserting rows than like 99% of the group chat, no cap. go forth and INSERT responsibly ๐ซถโจ๐
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms