3 .\" Author: The PostgreSQL Global Development Group
4 .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
6 .\" Manual: PostgreSQL 18.0 Documentation
7 .\" Source: PostgreSQL 18.0
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 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20 .\" -----------------------------------------------------------------
21 .\" * set default formatting
22 .\" -----------------------------------------------------------------
23 .\" disable hyphenation
25 .\" disable justification (adjust text to left margin only)
27 .\" -----------------------------------------------------------------
28 .\" * MAIN CONTENT STARTS HERE *
29 .\" -----------------------------------------------------------------
31 UPDATE \- update rows of a table
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 )
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 ] } [, \&.\&.\&.] ]
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
51 clause; columns not explicitly modified retain their previous values\&.
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
55 clause\&. Which technique is more appropriate depends on the specific circumstances\&.
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
64 list is identical to that of the output list of
69 privilege on the table, or at least on the column(s) that are listed to be updated\&. You must also have the
71 privilege on any column whose values are read in the
81 clause allows you to specify one or more subqueries that can be referenced by name in the
92 The name (optionally schema\-qualified) of the table to update\&. If
94 is specified before the table name, matching rows are updated in the named table only\&. If
96 is not specified, matching rows are also updated in any tables inheriting from the named table\&. Optionally,
98 can be specified after the table name to explicitly indicate that descendant tables are included\&.
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
106 statement must refer to this table as
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
122 An expression to assign to the column\&. The expression can use the old values of this and other columns in the table\&.
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\&.
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\&.
139 A table expression allowing columns from other tables to appear in the
141 condition and update expressions\&. This uses the same syntax as the
145 statement; for example, an alias for the table name can be specified\&. Do not repeat the target table as a
147 unless you intend a self\-join (in which case it must appear with an alias in the
153 An expression that returns a value of type
154 boolean\&. Only rows for which this expression returns
161 The name of the cursor to use in a
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
166 cannot be specified together with a Boolean condition\&. See
168 for more information about using cursors with
174 An optional substitute name for
182 By default, old values from the target table can be returned by writing
183 OLD\&.\fIcolumn_name\fR
185 OLD\&.*, and new values can be returned by writing
186 NEW\&.\fIcolumn_name\fR
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\&.*\&.
192 \fIoutput_expression\fR
194 An expression to be computed and returned by the
196 command after each row is updated\&. The expression can use any column names of the table named by
198 or table(s) listed in
201 to return all columns\&.
205 may be qualified using
208 NEW, or the corresponding
213 NEW, to cause old or new values to be returned\&. An unqualified column name, or
214 *, or a column name or
216 qualified using the target table name or alias will return new values\&.
221 A name to use for a returned column\&.
225 On successful completion, an
227 command returns a command tag of the form
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
243 when updates were suppressed by a
247 is 0, no rows were updated by the query (this is not considered an error)\&.
253 clause, the result will be similar to that of a
255 statement containing the columns and values defined in the
257 list, computed over the row(s) updated by the command\&.
262 clause is present, what essentially happens is that the target table is joined to the tables mentioned in the
264 list, and each output row of the join represents an update operation for the target table\&. When using
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\&.
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\&.
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
276 There is a possibility that a concurrent
280 on the row being moved will get a serialization failure error\&. Suppose session 1 is performing an
282 on a partition key, and meanwhile a concurrent session 2 for which this row is visible performs an
286 operation on this row\&. In such case, session 2\*(Aqs
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\&.
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\&.
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
314 UPDATE films SET kind = \*(AqDramatic\*(Aq WHERE kind = \*(AqDrama\*(Aq;
320 Adjust temperature entries and reset precipitation to its default value in one row of the table
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;
334 Perform the same operation and return the updated entries, and the old precipitation value:
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;
348 Use the alternative column\-list syntax to do the same update:
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;
361 Increment the sales count of the salesperson who manages the account for Acme Corporation, using the
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;
377 Perform the same operation, using a sub\-select in the
385 UPDATE employees SET sales_count = sales_count + 1 WHERE id =
386 (SELECT sales_person FROM accounts WHERE name = \*(AqAcme Corporation\*(Aq);
392 Update contact names in an accounts table to match the currently assigned salespeople:
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);
406 A similar result could be accomplished with a join:
412 UPDATE accounts SET contact_first_name = first_name,
413 contact_last_name = last_name
414 FROM employees WHERE employees\&.id = accounts\&.sales_person;
420 However, the second query may give unexpected results if
422 is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple
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\&.
428 Update statistics in a summary table to match the current data:
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);
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:
449 \-\- other operations
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:
455 UPDATE wines SET stock = stock + 24 WHERE winename = \*(AqChateau Lafite 2003\*(Aq;
456 \-\- continue with other operations, and eventually
467 in the row on which the cursor
469 is currently positioned:
475 UPDATE films SET kind = \*(AqDramatic\*(Aq WHERE CURRENT OF c_films;
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
483 operation on the table between batches\&. While there is no
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
490 table access method, a self\-join on the system column
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
505 UPDATE work_item SET status = \*(Aqfailed\*(Aq
506 FROM exceeded_max_retries AS emr
507 WHERE work_item\&.ctid = emr\&.ctid;
513 This command will need to be repeated until no rows remain to be updated\&. Use of an
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
519 to prevent multiple commands from updating the same row\&. However, then a final
525 will be needed to ensure that no matching rows were overlooked\&.
528 This command conforms to the
530 standard, except that the
536 extensions, as is the ability to use
541 Some other database systems offer a
543 option in which the target table is supposed to be listed again within
544 FROM\&. That is not how
547 FROM\&. Be careful when porting applications that use this extension\&.
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\&.
551 only allows the source value to be a
553 or a sub\-SELECT\&. An individual column\*(Aqs updated value can be specified as
555 in the row\-constructor case, but not inside a sub\-SELECT\&.