]> begriffs open source - ai-pg/blob - full-docs/txt/sql-insert.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / sql-insert.txt
1
2 INSERT
3
4    INSERT — create new rows in a table
5
6 Synopsis
7
8 [ WITH [ RECURSIVE ] with_query [, ...] ]
9 INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
10     [ OVERRIDING { SYSTEM | USER } VALUE ]
11     { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | que
12 ry }
13     [ ON CONFLICT [ conflict_target ] conflict_action ]
14     [ RETURNING [ WITH ( { OLD | NEW } AS output_alias [, ...] ) ]
15                 { * | output_expression [ [ AS ] output_name ] } [, ...] ]
16
17 where conflict_target can be one of:
18
19     ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opcla
20 ss ] [, ...] ) [ WHERE index_predicate ]
21     ON CONSTRAINT constraint_name
22
23 and conflict_action is one of:
24
25     DO NOTHING
26     DO UPDATE SET { column_name = { expression | DEFAULT } |
27                     ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT }
28  [, ...] ) |
29                     ( column_name [, ...] ) = ( sub-SELECT )
30                   } [, ...]
31               [ WHERE condition ]
32
33 Description
34
35    INSERT inserts new rows into a table. One can insert one or more rows
36    specified by value expressions, or zero or more rows resulting from a
37    query.
38
39    The target column names can be listed in any order. If no list of
40    column names is given at all, the default is all the columns of the
41    table in their declared order; or the first N column names, if there
42    are only N columns supplied by the VALUES clause or query. The values
43    supplied by the VALUES clause or query are associated with the explicit
44    or implicit column list left-to-right.
45
46    Each column not present in the explicit or implicit column list will be
47    filled with a default value, either its declared default value or null
48    if there is none.
49
50    If the expression for any column is not of the correct data type,
51    automatic type conversion will be attempted.
52
53    INSERT into tables that lack unique indexes will not be blocked by
54    concurrent activity. Tables with unique indexes might block if
55    concurrent sessions perform actions that lock or modify rows matching
56    the unique index values being inserted; the details are covered in
57    Section 63.5. ON CONFLICT can be used to specify an alternative action
58    to raising a unique constraint or exclusion constraint violation error.
59    (See ON CONFLICT Clause below.)
60
61    The optional RETURNING clause causes INSERT to compute and return
62    value(s) based on each row actually inserted (or updated, if an ON
63    CONFLICT DO UPDATE clause was used). This is primarily useful for
64    obtaining values that were supplied by defaults, such as a serial
65    sequence number. However, any expression using the table's columns is
66    allowed. The syntax of the RETURNING list is identical to that of the
67    output list of SELECT. Only rows that were successfully inserted or
68    updated will be returned. For example, if a row was locked but not
69    updated because an ON CONFLICT DO UPDATE ... WHERE clause condition was
70    not satisfied, the row will not be returned.
71
72    You must have INSERT privilege on a table in order to insert into it.
73    If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is
74    also required.
75
76    If a column list is specified, you only need INSERT privilege on the
77    listed columns. Similarly, when ON CONFLICT DO UPDATE is specified, you
78    only need UPDATE privilege on the column(s) that are listed to be
79    updated. However, ON CONFLICT DO UPDATE also requires SELECT privilege
80    on any column whose values are read in the ON CONFLICT DO UPDATE
81    expressions or condition.
82
83    Use of the RETURNING clause requires SELECT privilege on all columns
84    mentioned in RETURNING. If you use the query clause to insert rows from
85    a query, you of course need to have SELECT privilege on any table or
86    column used in the query.
87
88 Parameters
89
90 Inserting
91
92    This section covers parameters that may be used when only inserting new
93    rows. Parameters exclusively used with the ON CONFLICT clause are
94    described separately.
95
96    with_query
97           The WITH clause allows you to specify one or more subqueries
98           that can be referenced by name in the INSERT query. See
99           Section 7.8 and SELECT for details.
100
101           It is possible for the query (SELECT statement) to also contain
102           a WITH clause. In such a case both sets of with_query can be
103           referenced within the query, but the second one takes precedence
104           since it is more closely nested.
105
106    table_name
107           The name (optionally schema-qualified) of an existing table.
108
109    alias
110           A substitute name for table_name. When an alias is provided, it
111           completely hides the actual name of the table. This is
112           particularly useful when ON CONFLICT DO UPDATE targets a table
113           named excluded, since that will otherwise be taken as the name
114           of the special table representing the row proposed for
115           insertion.
116
117    column_name
118           The name of a column in the table named by table_name. The
119           column name can be qualified with a subfield name or array
120           subscript, if needed. (Inserting into only some fields of a
121           composite column leaves the other fields null.) When referencing
122           a column with ON CONFLICT DO UPDATE, do not include the table's
123           name in the specification of a target column. For example,
124           INSERT INTO table_name ... ON CONFLICT DO UPDATE SET
125           table_name.col = 1 is invalid (this follows the general behavior
126           for UPDATE).
127
128    OVERRIDING SYSTEM VALUE
129           If this clause is specified, then any values supplied for
130           identity columns will override the default sequence-generated
131           values.
132
133           For an identity column defined as GENERATED ALWAYS, it is an
134           error to insert an explicit value (other than DEFAULT) without
135           specifying either OVERRIDING SYSTEM VALUE or OVERRIDING USER
136           VALUE. (For an identity column defined as GENERATED BY DEFAULT,
137           OVERRIDING SYSTEM VALUE is the normal behavior and specifying it
138           does nothing, but PostgreSQL allows it as an extension.)
139
140    OVERRIDING USER VALUE
141           If this clause is specified, then any values supplied for
142           identity columns are ignored and the default sequence-generated
143           values are applied.
144
145           This clause is useful for example when copying values between
146           tables. Writing INSERT INTO tbl2 OVERRIDING USER VALUE SELECT *
147           FROM tbl1 will copy from tbl1 all columns that are not identity
148           columns in tbl2 while values for the identity columns in tbl2
149           will be generated by the sequences associated with tbl2.
150
151    DEFAULT VALUES
152           All columns will be filled with their default values, as if
153           DEFAULT were explicitly specified for each column. (An
154           OVERRIDING clause is not permitted in this form.)
155
156    expression
157           An expression or value to assign to the corresponding column.
158
159    DEFAULT
160           The corresponding column will be filled with its default value.
161           An identity column will be filled with a new value generated by
162           the associated sequence. For a generated column, specifying this
163           is permitted but merely specifies the normal behavior of
164           computing the column from its generation expression.
165
166    query
167           A query (SELECT statement) that supplies the rows to be
168           inserted. Refer to the SELECT statement for a description of the
169           syntax.
170
171    output_alias
172           An optional substitute name for OLD or NEW rows in the RETURNING
173           list.
174
175           By default, old values from the target table can be returned by
176           writing OLD.column_name or OLD.*, and new values can be returned
177           by writing NEW.column_name or NEW.*. When an alias is provided,
178           these names are hidden and the old or new rows must be referred
179           to using the alias. For example RETURNING WITH (OLD AS o, NEW AS
180           n) o.*, n.*.
181
182    output_expression
183           An expression to be computed and returned by the INSERT command
184           after each row is inserted or updated. The expression can use
185           any column names of the table named by table_name. Write * to
186           return all columns of the inserted or updated row(s).
187
188           A column name or * may be qualified using OLD or NEW, or the
189           corresponding output_alias for OLD or NEW, to cause old or new
190           values to be returned. An unqualified column name, or *, or a
191           column name or * qualified using the target table name or alias
192           will return new values.
193
194           For a simple INSERT, all old values will be NULL. However, for
195           an INSERT with an ON CONFLICT DO UPDATE clause, the old values
196           may be non-NULL.
197
198    output_name
199           A name to use for a returned column.
200
201 ON CONFLICT Clause
202
203    The optional ON CONFLICT clause specifies an alternative action to
204    raising a unique violation or exclusion constraint violation error. For
205    each individual row proposed for insertion, either the insertion
206    proceeds, or, if an arbiter constraint or index specified by
207    conflict_target is violated, the alternative conflict_action is taken.
208    ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative
209    action. ON CONFLICT DO UPDATE updates the existing row that conflicts
210    with the row proposed for insertion as its alternative action.
211
212    conflict_target can perform unique index inference. When performing
213    inference, it consists of one or more index_column_name columns and/or
214    index_expression expressions, and an optional index_predicate. All
215    table_name unique indexes that, without regard to order, contain
216    exactly the conflict_target-specified columns/expressions are inferred
217    (chosen) as arbiter indexes. If an index_predicate is specified, it
218    must, as a further requirement for inference, satisfy arbiter indexes.
219    Note that this means a non-partial unique index (a unique index without
220    a predicate) will be inferred (and thus used by ON CONFLICT) if such an
221    index satisfying every other criteria is available. If an attempt at
222    inference is unsuccessful, an error is raised.
223
224    ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome;
225    provided there is no independent error, one of those two outcomes is
226    guaranteed, even under high concurrency. This is also known as UPSERT —
227    “UPDATE or INSERT”.
228
229    conflict_target
230           Specifies which conflicts ON CONFLICT takes the alternative
231           action on by choosing arbiter indexes. Either performs unique
232           index inference, or names a constraint explicitly. For ON
233           CONFLICT DO NOTHING, it is optional to specify a
234           conflict_target; when omitted, conflicts with all usable
235           constraints (and unique indexes) are handled. For ON CONFLICT DO
236           UPDATE, a conflict_target must be provided.
237
238    conflict_action
239           conflict_action specifies an alternative ON CONFLICT action. It
240           can be either DO NOTHING, or a DO UPDATE clause specifying the
241           exact details of the UPDATE action to be performed in case of a
242           conflict. The SET and WHERE clauses in ON CONFLICT DO UPDATE
243           have access to the existing row using the table's name (or an
244           alias), and to the row proposed for insertion using the special
245           excluded table. SELECT privilege is required on any column in
246           the target table where corresponding excluded columns are read.
247
248           Note that the effects of all per-row BEFORE INSERT triggers are
249           reflected in excluded values, since those effects may have
250           contributed to the row being excluded from insertion.
251
252    index_column_name
253           The name of a table_name column. Used to infer arbiter indexes.
254           Follows CREATE INDEX format. SELECT privilege on
255           index_column_name is required.
256
257    index_expression
258           Similar to index_column_name, but used to infer expressions on
259           table_name columns appearing within index definitions (not
260           simple columns). Follows CREATE INDEX format. SELECT privilege
261           on any column appearing within index_expression is required.
262
263    collation
264           When specified, mandates that corresponding index_column_name or
265           index_expression use a particular collation in order to be
266           matched during inference. Typically this is omitted, as
267           collations usually do not affect whether or not a constraint
268           violation occurs. Follows CREATE INDEX format.
269
270    opclass
271           When specified, mandates that corresponding index_column_name or
272           index_expression use particular operator class in order to be
273           matched during inference. Typically this is omitted, as the
274           equality semantics are often equivalent across a type's operator
275           classes anyway, or because it's sufficient to trust that the
276           defined unique indexes have the pertinent definition of
277           equality. Follows CREATE INDEX format.
278
279    index_predicate
280           Used to allow inference of partial unique indexes. Any indexes
281           that satisfy the predicate (which need not actually be partial
282           indexes) can be inferred. Follows CREATE INDEX format. SELECT
283           privilege on any column appearing within index_predicate is
284           required.
285
286    constraint_name
287           Explicitly specifies an arbiter constraint by name, rather than
288           inferring a constraint or index.
289
290    condition
291           An expression that returns a value of type boolean. Only rows
292           for which this expression returns true will be updated, although
293           all rows will be locked when the ON CONFLICT DO UPDATE action is
294           taken. Note that condition is evaluated last, after a conflict
295           has been identified as a candidate to update.
296
297    Note that exclusion constraints are not supported as arbiters with ON
298    CONFLICT DO UPDATE. In all cases, only NOT DEFERRABLE constraints and
299    unique indexes are supported as arbiters.
300
301    INSERT with an ON CONFLICT DO UPDATE clause is a “deterministic”
302    statement. This means that the command will not be allowed to affect
303    any single existing row more than once; a cardinality violation error
304    will be raised when this situation arises. Rows proposed for insertion
305    should not duplicate each other in terms of attributes constrained by
306    an arbiter index or constraint.
307
308    Note that it is currently not supported for the ON CONFLICT DO UPDATE
309    clause of an INSERT applied to a partitioned table to update the
310    partition key of a conflicting row such that it requires the row be
311    moved to a new partition.
312
313 Tip
314
315    It is often preferable to use unique index inference rather than naming
316    a constraint directly using ON CONFLICT ON CONSTRAINT constraint_name.
317    Inference will continue to work correctly when the underlying index is
318    replaced by another more or less equivalent index in an overlapping
319    way, for example when using CREATE UNIQUE INDEX ... CONCURRENTLY before
320    dropping the index being replaced.
321
322 Outputs
323
324    On successful completion, an INSERT command returns a command tag of
325    the form
326 INSERT oid count
327
328    The count is the number of rows inserted or updated. oid is always 0
329    (it used to be the OID assigned to the inserted row if count was
330    exactly one and the target table was declared WITH OIDS and 0
331    otherwise, but creating a table WITH OIDS is not supported anymore).
332
333    If the INSERT command contains a RETURNING clause, the result will be
334    similar to that of a SELECT statement containing the columns and values
335    defined in the RETURNING list, computed over the row(s) inserted or
336    updated by the command.
337
338 Notes
339
340    If the specified table is a partitioned table, each row is routed to
341    the appropriate partition and inserted into it. If the specified table
342    is a partition, an error will occur if one of the input rows violates
343    the partition constraint.
344
345    You may also wish to consider using MERGE, since that allows mixing
346    INSERT, UPDATE, and DELETE within a single statement. See MERGE.
347
348 Examples
349
350    Insert a single row into table films:
351 INSERT INTO films VALUES
352     ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
353
354    In this example, the len column is omitted and therefore it will have
355    the default value:
356 INSERT INTO films (code, title, did, date_prod, kind)
357     VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');
358
359    This example uses the DEFAULT clause for the date columns rather than
360    specifying a value:
361 INSERT INTO films VALUES
362     ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes');
363 INSERT INTO films (code, title, did, date_prod, kind)
364     VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama');
365
366    To insert a row consisting entirely of default values:
367 INSERT INTO films DEFAULT VALUES;
368
369    To insert multiple rows using the multirow VALUES syntax:
370 INSERT INTO films (code, title, did, date_prod, kind) VALUES
371     ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
372     ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
373
374    This example inserts some rows into table films from a table tmp_films
375    with the same column layout as films:
376 INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';
377
378    This example inserts into array columns:
379 -- Create an empty 3x3 gameboard for noughts-and-crosses
380 INSERT INTO tictactoe (game, board[1:3][1:3])
381     VALUES (1, '{{" "," "," "},{" "," "," "},{" "," "," "}}');
382 -- The subscripts in the above example aren't really needed
383 INSERT INTO tictactoe (game, board)
384     VALUES (2, '{{X," "," "},{" ",O," "},{" ",X," "}}');
385
386    Insert a single row into table distributors, returning the sequence
387    number generated by the DEFAULT clause:
388 INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
389    RETURNING did;
390
391    Increment the sales count of the salesperson who manages the account
392    for Acme Corporation, and record the whole updated row along with
393    current time in a log table:
394 WITH upd AS (
395   UPDATE employees SET sales_count = sales_count + 1 WHERE id =
396     (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation')
397     RETURNING *
398 )
399 INSERT INTO employees_log SELECT *, current_timestamp FROM upd;
400
401    Insert or update new distributors as appropriate. Assumes a unique
402    index has been defined that constrains values appearing in the did
403    column. Note that the special excluded table is used to reference
404    values originally proposed for insertion:
405 INSERT INTO distributors (did, dname)
406     VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
407     ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;
408
409    Insert or update new distributors as above, returning information about
410    any existing values that were updated, together with the new data
411    inserted. Note that the returned values for old_did and old_dname will
412    be NULL for non-conflicting rows:
413 INSERT INTO distributors (did, dname)
414     VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
415     ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname
416     RETURNING old.did AS old_did, old.dname AS old_dname,
417               new.did AS new_did, new.dname AS new_dname;
418
419    Insert a distributor, or do nothing for rows proposed for insertion
420    when an existing, excluded row (a row with a matching constrained
421    column or columns after before row insert triggers fire) exists.
422    Example assumes a unique index has been defined that constrains values
423    appearing in the did column:
424 INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH')
425     ON CONFLICT (did) DO NOTHING;
426
427    Insert or update new distributors as appropriate. Example assumes a
428    unique index has been defined that constrains values appearing in the
429    did column. WHERE clause is used to limit the rows actually updated
430    (any existing row not updated will still be locked, though):
431 -- Don't update existing distributors based in a certain ZIP code
432 INSERT INTO distributors AS d (did, dname) VALUES (8, 'Anvil Distribution')
433     ON CONFLICT (did) DO UPDATE
434     SET dname = EXCLUDED.dname || ' (formerly ' || d.dname || ')'
435     WHERE d.zipcode <> '21201';
436
437 -- Name a constraint directly in the statement (uses associated
438 -- index to arbitrate taking the DO NOTHING action)
439 INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design')
440     ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;
441
442    Insert new distributor if possible; otherwise DO NOTHING. Example
443    assumes a unique index has been defined that constrains values
444    appearing in the did column on a subset of rows where the is_active
445    Boolean column evaluates to true:
446 -- This statement could infer a partial unique index on "did"
447 -- with a predicate of "WHERE is_active", but it could also
448 -- just use a regular unique constraint on "did"
449 INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International')
450     ON CONFLICT (did) WHERE is_active DO NOTHING;
451
452 Compatibility
453
454    INSERT conforms to the SQL standard, except that the RETURNING clause
455    is a PostgreSQL extension, as is the ability to use WITH with INSERT,
456    and the ability to specify an alternative action with ON CONFLICT.
457    Also, the case in which a column name list is omitted, but not all the
458    columns are filled from the VALUES clause or query, is disallowed by
459    the standard. If you prefer a more SQL standard conforming statement
460    than ON CONFLICT, see MERGE.
461
462    The SQL standard specifies that OVERRIDING SYSTEM VALUE can only be
463    specified if an identity column that is generated always exists.
464    PostgreSQL allows the clause in any case and ignores it if it is not
465    applicable.
466
467    Possible limitations of the query clause are documented under SELECT.