]> begriffs open source - ai-pg/blob - full-docs/man7/UPDATE.7
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / man7 / UPDATE.7
1 '\" t
2 .\"     Title: UPDATE
3 .\"    Author: The PostgreSQL Global Development Group
4 .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
5 .\"      Date: 2025
6 .\"    Manual: PostgreSQL 18.0 Documentation
7 .\"    Source: PostgreSQL 18.0
8 .\"  Language: English
9 .\"
10 .TH "UPDATE" "7" "2025" "PostgreSQL 18.0" "PostgreSQL 18.0 Documentation"
11 .\" -----------------------------------------------------------------
12 .\" * Define some portability stuff
13 .\" -----------------------------------------------------------------
14 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 .\" http://bugs.debian.org/507673
16 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
17 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18 .ie \n(.g .ds Aq \(aq
19 .el       .ds Aq '
20 .\" -----------------------------------------------------------------
21 .\" * set default formatting
22 .\" -----------------------------------------------------------------
23 .\" disable hyphenation
24 .nh
25 .\" disable justification (adjust text to left margin only)
26 .ad l
27 .\" -----------------------------------------------------------------
28 .\" * MAIN CONTENT STARTS HERE *
29 .\" -----------------------------------------------------------------
30 .SH "NAME"
31 UPDATE \- update rows of a table
32 .SH "SYNOPSIS"
33 .sp
34 .nf
35 [ WITH [ RECURSIVE ] \fIwith_query\fR [, \&.\&.\&.] ]
36 UPDATE [ ONLY ] \fItable_name\fR [ * ] [ [ AS ] \fIalias\fR ]
37     SET { \fIcolumn_name\fR = { \fIexpression\fR | DEFAULT } |
38           ( \fIcolumn_name\fR [, \&.\&.\&.] ) = [ ROW ] ( { \fIexpression\fR | DEFAULT } [, \&.\&.\&.] ) |
39           ( \fIcolumn_name\fR [, \&.\&.\&.] ) = ( \fIsub\-SELECT\fR )
40         } [, \&.\&.\&.]
41     [ FROM \fIfrom_item\fR [, \&.\&.\&.] ]
42     [ WHERE \fIcondition\fR | WHERE CURRENT OF \fIcursor_name\fR ]
43     [ RETURNING [ WITH ( { OLD | NEW } AS \fIoutput_alias\fR [, \&.\&.\&.] ) ]
44                 { * | \fIoutput_expression\fR [ [ AS ] \fIoutput_name\fR ] } [, \&.\&.\&.] ]
45 .fi
46 .SH "DESCRIPTION"
47 .PP
48 \fBUPDATE\fR
49 changes the values of the specified columns in all rows that satisfy the condition\&. Only the columns to be modified need be mentioned in the
50 SET
51 clause; columns not explicitly modified retain their previous values\&.
52 .PP
53 There are two ways to modify a table using information contained in other tables in the database: using sub\-selects, or specifying additional tables in the
54 FROM
55 clause\&. Which technique is more appropriate depends on the specific circumstances\&.
56 .PP
57 The optional
58 RETURNING
59 clause causes
60 \fBUPDATE\fR
61 to compute and return value(s) based on each row actually updated\&. Any expression using the table\*(Aqs columns, and/or columns of other tables mentioned in
62 FROM, can be computed\&. By default, the new (post\-update) values of the table\*(Aqs columns are used, but it is also possible to request the old (pre\-update) values\&. The syntax of the
63 RETURNING
64 list is identical to that of the output list of
65 \fBSELECT\fR\&.
66 .PP
67 You must have the
68 UPDATE
69 privilege on the table, or at least on the column(s) that are listed to be updated\&. You must also have the
70 SELECT
71 privilege on any column whose values are read in the
72 \fIexpressions\fR
73 or
74 \fIcondition\fR\&.
75 .SH "PARAMETERS"
76 .PP
77 \fIwith_query\fR
78 .RS 4
79 The
80 WITH
81 clause allows you to specify one or more subqueries that can be referenced by name in the
82 \fBUPDATE\fR
83 query\&. See
84 Section\ \&7.8
85 and
86 \fBSELECT\fR(7)
87 for details\&.
88 .RE
89 .PP
90 \fItable_name\fR
91 .RS 4
92 The name (optionally schema\-qualified) of the table to update\&. If
93 ONLY
94 is specified before the table name, matching rows are updated in the named table only\&. If
95 ONLY
96 is not specified, matching rows are also updated in any tables inheriting from the named table\&. Optionally,
97 *
98 can be specified after the table name to explicitly indicate that descendant tables are included\&.
99 .RE
100 .PP
101 \fIalias\fR
102 .RS 4
103 A substitute name for the target table\&. When an alias is provided, it completely hides the actual name of the table\&. For example, given
104 UPDATE foo AS f, the remainder of the
105 \fBUPDATE\fR
106 statement must refer to this table as
107 f
108 not
109 foo\&.
110 .RE
111 .PP
112 \fIcolumn_name\fR
113 .RS 4
114 The name of a column in the table named by
115 \fItable_name\fR\&. The column name can be qualified with a subfield name or array subscript, if needed\&. Do not include the table\*(Aqs name in the specification of a target column \(em for example,
116 UPDATE table_name SET table_name\&.col = 1
117 is invalid\&.
118 .RE
119 .PP
120 \fIexpression\fR
121 .RS 4
122 An expression to assign to the column\&. The expression can use the old values of this and other columns in the table\&.
123 .RE
124 .PP
125 DEFAULT
126 .RS 4
127 Set the column to its default value (which will be NULL if no specific default expression has been assigned to it)\&. An identity column will be set to 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\&.
128 .RE
129 .PP
130 \fIsub\-SELECT\fR
131 .RS 4
132 A
133 SELECT
134 sub\-query that produces as many output columns as are listed in the parenthesized column list preceding it\&. The sub\-query must yield no more than one row when executed\&. If it yields one row, its column values are assigned to the target columns; if it yields no rows, NULL values are assigned to the target columns\&. The sub\-query can refer to old values of the current row of the table being updated\&.
135 .RE
136 .PP
137 \fIfrom_item\fR
138 .RS 4
139 A table expression allowing columns from other tables to appear in the
140 WHERE
141 condition and update expressions\&. This uses the same syntax as the
142 FROM
143 clause of a
144 \fBSELECT\fR
145 statement; for example, an alias for the table name can be specified\&. Do not repeat the target table as a
146 \fIfrom_item\fR
147 unless you intend a self\-join (in which case it must appear with an alias in the
148 \fIfrom_item\fR)\&.
149 .RE
150 .PP
151 \fIcondition\fR
152 .RS 4
153 An expression that returns a value of type
154 boolean\&. Only rows for which this expression returns
155 true
156 will be updated\&.
157 .RE
158 .PP
159 \fIcursor_name\fR
160 .RS 4
161 The name of the cursor to use in a
162 WHERE CURRENT OF
163 condition\&. The row to be updated is the one most recently fetched from this cursor\&. The cursor must be a non\-grouping query on the
164 \fBUPDATE\fR\*(Aqs target table\&. Note that
165 WHERE CURRENT OF
166 cannot be specified together with a Boolean condition\&. See
167 \fBDECLARE\fR(7)
168 for more information about using cursors with
169 WHERE CURRENT OF\&.
170 .RE
171 .PP
172 \fIoutput_alias\fR
173 .RS 4
174 An optional substitute name for
175 OLD
176 or
177 NEW
178 rows in the
179 RETURNING
180 list\&.
181 .sp
182 By default, old values from the target table can be returned by writing
183 OLD\&.\fIcolumn_name\fR
184 or
185 OLD\&.*, and new values can be returned by writing
186 NEW\&.\fIcolumn_name\fR
187 or
188 NEW\&.*\&. When an alias is provided, these names are hidden and the old or new rows must be referred to using the alias\&. For example
189 RETURNING WITH (OLD AS o, NEW AS n) o\&.*, n\&.*\&.
190 .RE
191 .PP
192 \fIoutput_expression\fR
193 .RS 4
194 An expression to be computed and returned by the
195 \fBUPDATE\fR
196 command after each row is updated\&. The expression can use any column names of the table named by
197 \fItable_name\fR
198 or table(s) listed in
199 FROM\&. Write
200 *
201 to return all columns\&.
202 .sp
203 A column name or
204 *
205 may be qualified using
206 OLD
207 or
208 NEW, or the corresponding
209 \fIoutput_alias\fR
210 for
211 OLD
212 or
213 NEW, to cause old or new values to be returned\&. An unqualified column name, or
214 *, or a column name or
215 *
216 qualified using the target table name or alias will return new values\&.
217 .RE
218 .PP
219 \fIoutput_name\fR
220 .RS 4
221 A name to use for a returned column\&.
222 .RE
223 .SH "OUTPUTS"
224 .PP
225 On successful completion, an
226 \fBUPDATE\fR
227 command returns a command tag of the form
228 .sp
229 .if n \{\
230 .RS 4
231 .\}
232 .nf
233 UPDATE \fIcount\fR
234 .fi
235 .if n \{\
236 .RE
237 .\}
238 .sp
239 The
240 \fIcount\fR
241 is the number of rows updated, including matched rows whose values did not change\&. Note that the number may be less than the number of rows that matched the
242 \fIcondition\fR
243 when updates were suppressed by a
244 BEFORE UPDATE
245 trigger\&. If
246 \fIcount\fR
247 is 0, no rows were updated by the query (this is not considered an error)\&.
248 .PP
249 If the
250 \fBUPDATE\fR
251 command contains a
252 RETURNING
253 clause, the result will be similar to that of a
254 \fBSELECT\fR
255 statement containing the columns and values defined in the
256 RETURNING
257 list, computed over the row(s) updated by the command\&.
258 .SH "NOTES"
259 .PP
260 When a
261 FROM
262 clause is present, what essentially happens is that the target table is joined to the tables mentioned in the
263 \fIfrom_item\fR
264 list, and each output row of the join represents an update operation for the target table\&. When using
265 FROM
266 you should ensure that the join produces at most one output row for each row to be modified\&. In other words, a target row shouldn\*(Aqt join to more than one row from the other table(s)\&. If it does, then only one of the join rows will be used to update the target row, but which one will be used is not readily predictable\&.
267 .PP
268 Because of this indeterminacy, referencing other tables only within sub\-selects is safer, though often harder to read and slower than using a join\&.
269 .PP
270 In the case of a partitioned table, updating a row might cause it to no longer satisfy the partition constraint of the containing partition\&. In that case, if there is some other partition in the partition tree for which this row satisfies its partition constraint, then the row is moved to that partition\&. If there is no such partition, an error will occur\&. Behind the scenes, the row movement is actually a
271 \fBDELETE\fR
272 and
273 \fBINSERT\fR
274 operation\&.
275 .PP
276 There is a possibility that a concurrent
277 \fBUPDATE\fR
278 or
279 \fBDELETE\fR
280 on the row being moved will get a serialization failure error\&. Suppose session 1 is performing an
281 \fBUPDATE\fR
282 on a partition key, and meanwhile a concurrent session 2 for which this row is visible performs an
283 \fBUPDATE\fR
284 or
285 \fBDELETE\fR
286 operation on this row\&. In such case, session 2\*(Aqs
287 \fBUPDATE\fR
288 or
289 \fBDELETE\fR
290 will detect the row movement and raise a serialization failure error (which always returns with an SQLSTATE code \*(Aq40001\*(Aq)\&. Applications may wish to retry the transaction if this occurs\&. In the usual case where the table is not partitioned, or where there is no row movement, session 2 would have identified the newly updated row and carried out the
291 \fBUPDATE\fR/\fBDELETE\fR
292 on this new row version\&.
293 .PP
294 Note that while rows can be moved from local partitions to a foreign\-table partition (provided the foreign data wrapper supports tuple routing), they cannot be moved from a foreign\-table partition to another partition\&.
295 .PP
296 An attempt of moving a row from one partition to another will fail if a foreign key is found to directly reference an ancestor of the source partition that is not the same as the ancestor that\*(Aqs mentioned in the
297 \fBUPDATE\fR
298 query\&.
299 .SH "EXAMPLES"
300 .PP
301 Change the word
302 Drama
303 to
304 Dramatic
305 in the column
306 kind
307 of the table
308 films:
309 .sp
310 .if n \{\
311 .RS 4
312 .\}
313 .nf
314 UPDATE films SET kind = \*(AqDramatic\*(Aq WHERE kind = \*(AqDrama\*(Aq;
315 .fi
316 .if n \{\
317 .RE
318 .\}
319 .PP
320 Adjust temperature entries and reset precipitation to its default value in one row of the table
321 weather:
322 .sp
323 .if n \{\
324 .RS 4
325 .\}
326 .nf
327 UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
328   WHERE city = \*(AqSan Francisco\*(Aq AND date = \*(Aq2003\-07\-03\*(Aq;
329 .fi
330 .if n \{\
331 .RE
332 .\}
333 .PP
334 Perform the same operation and return the updated entries, and the old precipitation value:
335 .sp
336 .if n \{\
337 .RS 4
338 .\}
339 .nf
340 UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
341   WHERE city = \*(AqSan Francisco\*(Aq AND date = \*(Aq2003\-07\-03\*(Aq
342   RETURNING temp_lo, temp_hi, prcp, old\&.prcp AS old_prcp;
343 .fi
344 .if n \{\
345 .RE
346 .\}
347 .PP
348 Use the alternative column\-list syntax to do the same update:
349 .sp
350 .if n \{\
351 .RS 4
352 .\}
353 .nf
354 UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT)
355   WHERE city = \*(AqSan Francisco\*(Aq AND date = \*(Aq2003\-07\-03\*(Aq;
356 .fi
357 .if n \{\
358 .RE
359 .\}
360 .PP
361 Increment the sales count of the salesperson who manages the account for Acme Corporation, using the
362 FROM
363 clause syntax:
364 .sp
365 .if n \{\
366 .RS 4
367 .\}
368 .nf
369 UPDATE employees SET sales_count = sales_count + 1 FROM accounts
370   WHERE accounts\&.name = \*(AqAcme Corporation\*(Aq
371   AND employees\&.id = accounts\&.sales_person;
372 .fi
373 .if n \{\
374 .RE
375 .\}
376 .PP
377 Perform the same operation, using a sub\-select in the
378 WHERE
379 clause:
380 .sp
381 .if n \{\
382 .RS 4
383 .\}
384 .nf
385 UPDATE employees SET sales_count = sales_count + 1 WHERE id =
386   (SELECT sales_person FROM accounts WHERE name = \*(AqAcme Corporation\*(Aq);
387 .fi
388 .if n \{\
389 .RE
390 .\}
391 .PP
392 Update contact names in an accounts table to match the currently assigned salespeople:
393 .sp
394 .if n \{\
395 .RS 4
396 .\}
397 .nf
398 UPDATE accounts SET (contact_first_name, contact_last_name) =
399     (SELECT first_name, last_name FROM employees
400      WHERE employees\&.id = accounts\&.sales_person);
401 .fi
402 .if n \{\
403 .RE
404 .\}
405 .sp
406 A similar result could be accomplished with a join:
407 .sp
408 .if n \{\
409 .RS 4
410 .\}
411 .nf
412 UPDATE accounts SET contact_first_name = first_name,
413                     contact_last_name = last_name
414   FROM employees WHERE employees\&.id = accounts\&.sales_person;
415 .fi
416 .if n \{\
417 .RE
418 .\}
419 .sp
420 However, the second query may give unexpected results if
421 employees\&.id
422 is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple
423 id
424 matches\&. Also, if there is no match for a particular
425 accounts\&.sales_person
426 entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all\&.
427 .PP
428 Update statistics in a summary table to match the current data:
429 .sp
430 .if n \{\
431 .RS 4
432 .\}
433 .nf
434 UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) =
435     (SELECT sum(x), sum(y), avg(x), avg(y) FROM data d
436      WHERE d\&.group_id = s\&.group_id);
437 .fi
438 .if n \{\
439 .RE
440 .\}
441 .PP
442 Attempt to insert a new stock item along with the quantity of stock\&. If the item already exists, instead update the stock count of the existing item\&. To do this without failing the entire transaction, use savepoints:
443 .sp
444 .if n \{\
445 .RS 4
446 .\}
447 .nf
448 BEGIN;
449 \-\- other operations
450 SAVEPOINT sp1;
451 INSERT INTO wines VALUES(\*(AqChateau Lafite 2003\*(Aq, \*(Aq24\*(Aq);
452 \-\- Assume the above fails because of a unique key violation,
453 \-\- so now we issue these commands:
454 ROLLBACK TO sp1;
455 UPDATE wines SET stock = stock + 24 WHERE winename = \*(AqChateau Lafite 2003\*(Aq;
456 \-\- continue with other operations, and eventually
457 COMMIT;
458 .fi
459 .if n \{\
460 .RE
461 .\}
462 .PP
463 Change the
464 kind
465 column of the table
466 films
467 in the row on which the cursor
468 c_films
469 is currently positioned:
470 .sp
471 .if n \{\
472 .RS 4
473 .\}
474 .nf
475 UPDATE films SET kind = \*(AqDramatic\*(Aq WHERE CURRENT OF c_films;
476 .fi
477 .if n \{\
478 .RE
479 .\}
480 .PP
481 Updates affecting many rows can have negative effects on system performance, such as table bloat, increased replica lag, and increased lock contention\&. In such situations it can make sense to perform the operation in smaller batches, possibly with a
482 \fBVACUUM\fR
483 operation on the table between batches\&. While there is no
484 LIMIT
485 clause for
486 \fBUPDATE\fR, it is possible to get a similar effect through the use of a
487 Common Table Expression
488 and a self\-join\&. With the standard
489 PostgreSQL
490 table access method, a self\-join on the system column
491 ctid
492 is very efficient:
493 .sp
494 .if n \{\
495 .RS 4
496 .\}
497 .nf
498 WITH exceeded_max_retries AS (
499   SELECT w\&.ctid FROM work_item AS w
500     WHERE w\&.status = \*(Aqactive\*(Aq AND w\&.num_retries > 10
501     ORDER BY w\&.retry_timestamp
502     FOR UPDATE
503     LIMIT 5000
504 )
505 UPDATE work_item SET status = \*(Aqfailed\*(Aq
506   FROM exceeded_max_retries AS emr
507   WHERE work_item\&.ctid = emr\&.ctid;
508 .fi
509 .if n \{\
510 .RE
511 .\}
512 .sp
513 This command will need to be repeated until no rows remain to be updated\&. Use of an
514 ORDER BY
515 clause allows the command to prioritize which rows will be updated; it can also prevent deadlock with other update operations if they use the same ordering\&. If lock contention is a concern, then
516 SKIP LOCKED
517 can be added to the
518 CTE
519 to prevent multiple commands from updating the same row\&. However, then a final
520 \fBUPDATE\fR
521 without
522 SKIP LOCKED
523 or
524 LIMIT
525 will be needed to ensure that no matching rows were overlooked\&.
526 .SH "COMPATIBILITY"
527 .PP
528 This command conforms to the
529 SQL
530 standard, except that the
531 FROM
532 and
533 RETURNING
534 clauses are
535 PostgreSQL
536 extensions, as is the ability to use
537 WITH
538 with
539 \fBUPDATE\fR\&.
540 .PP
541 Some other database systems offer a
542 FROM
543 option in which the target table is supposed to be listed again within
544 FROM\&. That is not how
545 PostgreSQL
546 interprets
547 FROM\&. Be careful when porting applications that use this extension\&.
548 .PP
549 According to the standard, the source value for a parenthesized sub\-list of target column names can be any row\-valued expression yielding the correct number of columns\&.
550 PostgreSQL
551 only allows the source value to be a
552 row constructor
553 or a sub\-SELECT\&. An individual column\*(Aqs updated value can be specified as
554 DEFAULT
555 in the row\-constructor case, but not inside a sub\-SELECT\&.