INSERT
INSERT adds one or more rows to a table. Rows can come from explicit value expressions or a query.
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 ]Parameters
Insert parameters
| Parameter | Description |
|---|---|
with_query | One or more subqueries (common table expressions) referenceable by name in the INSERT query. If the query clause also contains a WITH clause, both sets of with_query are available, but the inner one takes precedence. |
table_name | The name (optionally schema-qualified) of an existing table. |
alias | A substitute name for table_name. When provided, it completely hides the actual table name. Useful when ON CONFLICT DO UPDATE targets a table named excluded, which would otherwise be taken as the special table representing the row proposed for insertion. |
column_name | The name of a column in table_name, optionally qualified with a subfield name or array subscript. When using ON CONFLICT DO UPDATE, do not include the table name in the target column specification — INSERT INTO table_name ... ON CONFLICT DO UPDATE SET table_name.col = 1 is invalid. |
OVERRIDING SYSTEM VALUE | Overrides the default sequence-generated values for identity columns. Required when inserting an explicit value into a column defined as GENERATED ALWAYS (otherwise an error is raised). For a 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 | Ignores any supplied values for identity columns and applies the default sequence-generated values instead. Useful when copying rows between tables: INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 copies non-identity columns from tbl1 while generating fresh identity values for tbl2. |
DEFAULT VALUES | Fills all columns with their default values. The OVERRIDING clause is not permitted with this form. |
expression | An expression or value to assign to the corresponding column. |
DEFAULT | Fills the corresponding column with its default value. For an identity column, a new value is generated by the associated sequence. For a generated column, specifying DEFAULT is permitted but merely specifies the normal behavior of computing the column from its generation expression. |
query | A SELECT statement that supplies the rows to be inserted. |
output_expression | An expression computed and returned by INSERT after each row is inserted or updated. Write * to return all columns of the inserted or updated row. |
output_name | The name to use for a returned column. |
Column list behavior: If no column list is given, the default is all columns in their declared order, or the first N columns if the VALUES clause or query supplies only N columns. Values are matched to columns left-to-right. Columns absent from the list are filled with their declared default value, or null if none exists. If a value is not of the correct data type, automatic type conversion is attempted.
ON CONFLICT parameters
| Parameter | Description |
|---|---|
conflict_target | Specifies which conflicts ON CONFLICT handles, by identifying arbiter indexes through unique index inference or by naming a constraint explicitly. Optional for DO NOTHING; required for DO UPDATE. |
conflict_action | Either DO NOTHING or a DO UPDATE SET clause. Within DO UPDATE, the SET and WHERE clauses can reference the existing row using the table name (or alias) and the proposed row using the special excluded table. 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. |
index_column_name | A column of table_name used to infer arbiter indexes. Follows CREATE INDEX format. Requires SELECT privilege. |
index_expression | An expression on table_name columns used to infer arbiter indexes (for functional indexes). Follows CREATE INDEX format. Requires SELECT privilege on referenced columns. |
collation | Restricts arbiter index inference to indexes using a specific collation. Typically omitted. |
opclass | Restricts arbiter index inference to indexes using a specific operator class. Typically omitted. |
index_predicate | Allows inference of partial unique indexes. Any index satisfying the predicate can be inferred. Requires SELECT privilege on referenced columns. |
constraint_name | Names an arbiter constraint directly, bypassing index inference. |
condition | A boolean expression. Only rows where this expression returns true are updated, though all candidate rows are locked. Evaluated last, after a conflict is identified. |
Required privileges
| Operation | Required privilege |
|---|---|
Basic INSERT | INSERT on the table |
| Column list specified | INSERT on the listed columns only |
ON CONFLICT DO UPDATE | INSERT + UPDATE on the table |
ON CONFLICT DO UPDATE with column list | INSERT + UPDATE on the listed columns |
ON CONFLICT DO UPDATE expressions/condition | SELECT on columns read in expressions or condition |
RETURNING clause | SELECT on all columns referenced in RETURNING |
query clause (insert from query) | SELECT on any table or column used in the query |
index_column_name, index_expression, index_predicate | SELECT on referenced columns |
ON CONFLICT behavior
ON CONFLICT specifies an alternative action when a proposed row violates a unique constraint or exclusion constraint. For each proposed row, either the insertion proceeds or the alternative conflict_action is taken.
DO NOTHING: Silently skips the row instead of raising an error.DO UPDATE: Updates the conflicting existing row. This guarantees an atomicINSERTorUPDATEoutcome — also known as UPSERT.
ON CONFLICT DO UPDATE is deterministic: it cannot affect any single existing row more than once. If the proposed rows duplicate each other on the arbiter constraint, a cardinality violation error is raised.
Prefer unique index inference over naming a constraint directly with ON CONFLICT ON CONSTRAINT constraint_name. Inference continues to work correctly when the underlying index is replaced by an equivalent one (for example, using CREATE UNIQUE INDEX ... CONCURRENTLY before dropping the old index).
Exclusion constraints are not supported as arbiters with ON CONFLICT DO UPDATE. Only NOT DEFERRABLE constraints and unique indexes are supported. It is also not currently supported to use ON CONFLICT DO UPDATE on a partitioned table when the update would move the conflicting row to a different partition.
RETURNING clause
RETURNING makes INSERT compute and return values based on each row actually inserted or updated. The syntax is identical to the output list of SELECT.
Only rows that are successfully inserted or updated are returned. If a row is locked but not updated because an ON CONFLICT DO UPDATE ... WHERE condition is not satisfied, that row is not returned.
RETURNING is particularly useful for retrieving default-generated values such as sequence numbers.
Example: insert a distributor and retrieve its generated did:
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;Outputs
On successful completion, INSERT returns a command tag:
INSERT oid countcount: the number of rows inserted or updated.oid: always0. (Previously held the OID of the inserted row whencountwas 1, but creating tablesWITH OIDSis no longer supported.)
When a RETURNING clause is present, the result resembles a SELECT output with the columns and values defined in the RETURNING list.
Usage notes
Concurrency:
INSERTinto tables without unique indexes is never blocked by concurrent activity. Tables with unique indexes may block if concurrent sessions lock or modify rows that match the unique index values being inserted.Partitioned tables: Each row is routed to the appropriate partition. If the table specified is itself a partition (not the partitioned table), an error occurs if any input row violates the partition constraint.
Alternative: Consider
MERGEwhen you need to mixINSERT,UPDATE, andDELETEin a single statement.
Examples
Insert a single row:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');Omit a column (uses default value):
INSERT INTO films (code, title, did, date_prod, kind)
VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');Use DEFAULT for specific columns:
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');Insert an all-default row:
INSERT INTO films DEFAULT VALUES;Insert multiple rows in one statement:
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');Insert from a query:
INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';Insert 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," "}}');Retrieve sequence-generated values with RETURNING:
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;Use a common table expression (CTE) with RETURNING:
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;UPSERT — insert or update on conflict:
INSERT INTO distributors (did, dname)
VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;The special excluded table references the values originally proposed for insertion.
Skip conflicting rows with DO NOTHING:
INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH')
ON CONFLICT (did) DO NOTHING;Conditional update on conflict:
-- Update the name only if the distributor is not in ZIP code 21201
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:
INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design')
ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;Infer a partial unique index:
-- Infers a partial unique index on "did" WHERE is_active
INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International')
ON CONFLICT (did) WHERE is_active DO NOTHING;