INSERT(7)
π INSERT(7) β PostgreSQL 14.24 Documentation π
πΈ NAME πΈ
INSERT β create new rows in a table, periodt. That's the whole vibe.
β¨ 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 π¦
Okay so bestie, INSERT is the move that puts new rows into a table. You can insert one or more rows using value expressions, or zero or more rows that come from a query. Both are valid, no cap.
The target column names? You can list them in whatever order you want. If you don't give a column list at all, the default is literally all the columns of the table in their declared order. But if the VALUES clause or query supplies only N columns, then it's the first N column names. The values supplied by the VALUES clause or query get associated with the explicit or implicit column list left-to-right.
Every column that isn't in the explicit or implicit column list gets filled with a default value: either its declared default value, or null if there isn't one. And if the expression for any column isn't the correct data type, automatic type conversion will be attempted. It's giving "we'll try to make it work."
Inserting into tables that lack unique indexes won't 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 62.5. ON CONFLICT can specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See ON CONFLICT Clause below.)
The optional RETURNING clause makes INSERT compute and return value(s) based on each row that was 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, like a serial sequence number. But 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, that row will not be returned.
Privilege check time, bestie β because permissions are the vibe check you cannot skip. π
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. But β and this is the important part β 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. And 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 β¨
π Inserting
So this whole chunk is about the parameters you'd use when you're just inserting new rows, no drama. The ones that are only for the ON CONFLICT clause get their own little section later, keep scrolling bestie π«Ά
with_queryβ theWITHclause lets you name one or more subqueries and then reference them by name inside yourINSERTquery. Go look at Section 7.8 andSELECT(7)for the full tea β
Your query (the SELECT statement) can also have its own WITH clause, and honestly? Both sets of with_query are referencable inside the query. But the second one wins, because it's nested more closely β closer nesting, higher priority, that's just the rules π
table_nameβ the name of an existing table, optionally schema-qualified.aliasβ a substitute name fortable_name. When you give an alias it completely hides the actual name of the table, like a full glow-up, nobody recognizes her anymore. This is especially iconic whenON CONFLICT DO UPDATEtargets a table literally namedexcludedβ because otherwise that name gets taken as the specialexcludedtable representing the row you proposed for insertion. Awkward π«column_nameβ the name of a column in the table named bytable_name. You can qualify the column name with a subfield name or an array subscript if you need to. (If you insert into only some fields of a composite column, the other fields are left null β ngl, that's just what happens.) When you're referencing a column withON CONFLICT DO UPDATE, do not put the table's name in the target column spec. Like,INSERT INTO table_name ... ON CONFLICT DO UPDATE SET table_name.col = 1is invalid, periodt β that follows the general behavior forUPDATE.OVERRIDING SYSTEM VALUEβ if you specify this, then any values you supply for identity columns override the default sequence-generated values. Slay, you're in charge now π
For an identity column defined as GENERATED ALWAYS, it is genuinely 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 literally nothing β but PostgreSQL allows it as an extension, cute π)
OVERRIDING USER VALUEβ if you specify this, then any values supplied for identity columns are ignored and the default sequence-generated values get applied instead. Not me ignoring your input but like, affectionately.
This clause is lowkey a lifesaver when you're copying values between tables. Writing INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 will copy from tbl1 all the columns that are not identity columns in tbl2, while the values for the identity columns in tbl2 get generated by the sequences associated with tbl2. Chef's kiss π₯
DEFAULT VALUESβ every column gets filled with its default value, as ifDEFAULTwere explicitly specified for each column. (AnOVERRIDINGclause is not permitted in this form, so don't try it π)expressionβ an expression or value to assign to the corresponding column.DEFAULTβ the corresponding column gets filled with its default value. An identity column gets filled with a new value generated by the associated sequence. For a generated column, specifying this is permitted but it merely specifies the normal behavior of computing the column from its generation expression β so it's giving "I did something" when you really didn't πqueryβ a query (aSELECTstatement) that supplies the rows to be inserted. Peep theSELECT(7)statement for the syntax description.output_expressionβ an expression that gets 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). All of them. Every single one πoutput_nameβ a name to use for a returned column.
π¦ ON CONFLICT Clause
The optional ON CONFLICT clause is your alternative to just raising a unique violation or exclusion constraint violation error and ruining everyone's day. 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 instead.
ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action, like, "nvm then π
". ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action. Very "if you can't beat them, update them".
conflict_target can perform unique index inference. When it's doing 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 columns/expressions specified by conflict_target get inferred (chosen) as arbiter indexes. And if an index_predicate is specified, it must, as a further requirement for inference, satisfy arbiter indexes.
Heads up bestie: this means a non-partial unique index (one 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 silent vibes here, she will tell you π
ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome. As long as there's no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT β "UPDATE or INSERT". Main character energy fr fr β¨
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, specifying aconflict_targetis optional; when it's omitted, conflicts with all usable constraints (and unique indexes) are handled. ForON CONFLICT DO UPDATE, aconflict_targetmust be provided β no target, no update, sorry πconflict_actionβ specifies 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 π
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. Snapshot of the row after the triggers had their moment π
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 specified, mandates that the correspondingindex_column_nameorindex_expressionuse a particular collation in order to be matched during inference. Typically this is omitted, because collations usually don't affect whether or not a constraint violation occurs. FollowsCREATE INDEXformat.opclassβ when specified, mandates that the correspondingindex_column_nameorindex_expressionuse a particular operator class in order to be matched during inference. Typically this is omitted too β 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. Old school, but valid πconditionβ an expression that returns a value of typeboolean. Only rows for which this expression returns true will be updated β but 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. Last but definitely not least π«Ά
Also note: 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. That's the vibe check and they did not pass πΈ
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. Don't make her pick which one of you is the real one π
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. Not happening, not today.
π‘ Tip It's 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. Future-proof your fit π
β οΈ Warning WhileCREATE INDEX CONCURRENTLYorREINDEX CONCURRENTLYis running on a unique index,INSERT ... ON CONFLICTstatements on the same table may unexpectedly fail with a unique violation. Yes, even withON CONFLICT. Yes, it's rude. No, you're not imagining it π
π 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. So yeah, she's a 0 now, retired legend π
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. Basically you get your receipts back, and honestly? Obsessed π
β NOTES
If the specified table is a partitioned table, each row is routed to the appropriate partition and inserted into it β like a lil delivery service, each row finds its home π
If the specified table is a partition, an error will occur if one of the input rows violates the partition constraint. So double-check your rows before you send them somewhere they don't belong π
π EXAMPLES π
Okay bestie, this is the part where it all comes together β every example from the original, untouched, with me cheering you on from the sidelines π These are literally copy-paste-able, so go off π
β¨ Just the basics β¨
Inserting one single row into table films? Child's play, we love a simple queen:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Now watch this glow-up π
β here the len column is omitted, so it just... gets its default value. No drama, no cap:
INSERT INTO films (code, title, did, date_prod, kind)
VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');
Same energy, but this time we're using the DEFAULT clause for the date columns instead of typing out an actual value. Let the database do her thing β¨:
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');
And if you want a row that's entirely defaults β no thoughts, head empty, all vibes π«§:
INSERT INTO films DEFAULT VALUES;
π¦ Multiple rows at once π¦
The multirow VALUES syntax is honestly iconic β why insert one when you can insert many, right? β¨
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
πΈ Pulling rows from another table πΈ
This one inserts some rows into table films from a table called tmp_films that has the exact same column layout as films. Table-to-table transfer, we stan π«Ά:
INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';
π Array columns, because we're fancy π
Okay this one's giving main character energy β inserting 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," "}}');
Ngl, the subscripts in that first one aren't even needed β the second version says the same thing, simpler π
π RETURNING, the moment we've all been waiting for π
Insert a single row into table distributors, and get back the sequence number that the DEFAULT clause generated. Like, thank you for your service, here's your receipt π:
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;
π§ CTE + INSERT, a collab π§
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. The way this one works is so satisfying π:
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;
π₯ ON CONFLICT β the upsert era π₯
Insert or update new distributors as appropriate. This one assumes a unique index has been defined that constrains values appearing in the did column. Also 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 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 also 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;
β Conditional upserts β
Insert or update new distributors as appropriate β again assuming a unique index on did. The WHERE clause is used to limit the rows actually updated. Heads up though: any existing row that doesn't get updated will still be locked π:
-- 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;
And finally: insert a new distributor if possible, otherwise DO NOTHING. This 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 so the tea on standards compliance β: INSERT conforms to the SQL standard β except that the RETURNING clause is a PostgreSQL extension, as is the ability to use WITH with INSERT, and the ability to specify an alternative action with ON CONFLICT. We're just built different, iykyk π
Also β and this is a real one β the case in which a column name list is omitted, but not all the columns are filled from the VALUES clause or query, is disallowed by the standard. So yeah, the standard said no π
The SQL standard specifies that OVERRIDING SYSTEM VALUE can only be specified if an identity column that is generated always exists. PostgreSQL, being the chill icon she is, allows the clause in any case and ignores it if it is not applicable π
Possible limitations of the query clause are documented under SELECT(7) β go read that one too bestie, fr fr π
That's a wrap on INSERT(7) π You made it to the end β so proud of you π«Ά This page shipped with PostgreSQL 14.24, dated 2026, and you can take that footer to the bank β¨ Go forth and insert responsibly, queen π
π¦ where this page comes from
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-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