UPDATE
UPDATE — Update rows of a table
Synopsis
[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
SET { column_name = { expression | DEFAULT } |
( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] )
| ( column_name [, ...] ) = ( sub-SELECT )
} [, ...]
[ FROM from_item [, ...] ]
[ WHERE condition | WHERE CURRENT OF cursor_name ]
[ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
Description
UPDATE changes the values of the specified columns in all rows that satisfy the condition. Only the columns to be modified need to be mentioned in the SET clause; columns not explicitly modified retain their previous values.
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 FROM clause. This technique is appropriate only in specific circumstances.
The optional RETURNING clause causes UPDATE to compute and return values based on each row actually updated. Any expression using the columns of the table, as well as columns of other tables mentioned in FROM, can be computed. The computation uses the new (post-update) values of the table's columns. The syntax of the RETURNING list is identical to that of the output list of SELECT.
You must have the UPDATE privilege on the table, or at least on the columns to be updated. If any column's values are read by expressions or the condition, you must also have the SELECT privilege on those columns.
Parameters
with_query
The WITH clause allows you to specify one or more subqueries that can be referenced by name within the UPDATE.
table_name
The name of the table to update (can be schema-qualified). If ONLY is specified before the table name, only matching rows in the named table are updated. If ONLY is not specified, any matching rows in tables inheriting from the named table are also updated. Optionally, * can be specified after the table name to explicitly indicate that descendant tables should be included.
alias
A substitute name for the target table. When an alias is provided, it completely hides the real name of the table. For example, given UPDATE foo AS f, the remainder of the UPDATE statement must reference the table as f rather than foo.
column_name
The name of a column in the table specified by table_name. If needed, the column name can be qualified with a subfield name or array subscript. Do not include the table name in the target column specification — for example, UPDATE table_name SET table_name.col = 1 is invalid.
expression
An expression to assign to the column. The expression can use the old value of this column or other columns in the table.
DEFAULT
Sets the column to its default value (if no default expression has been specified for it, the default will be NULL).
Identity columns will be set to a new value generated by the associated sequence. For generated columns, specifying this is allowed but merely specifies the normal behavior of computing the column from its generation expression.
sub-SELECT
A SELECT subquery that produces as many output columns as the parenthesized column list preceding it. When executed, the subquery must return no more than one row. If it returns one row, its column values are assigned to the target columns. If it returns no rows, NULL values are assigned to the target columns. The subquery can reference the old values of the current row of the table being updated.
from_item
A table expression allowing columns from other tables to appear in the WHERE condition and update expressions. This uses the same syntax as the FROM clause of a SELECT statement; for example, aliases for table names can be specified. Do not repeat the target table as a from_item unless you intend a self-join (in which case it must appear with an alias in the from_item list).
condition
An expression that returns a value of type boolean. Only rows for which this expression returns true will be updated.
cursor_name
The name of the cursor to use in a WHERE CURRENT OF 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 UPDATE target table. Note that WHERE CURRENT OF cannot be specified together with a Boolean condition. See DECLARE for more information about using WHERE CURRENT OF with cursors.
output_expression
An expression to be computed and returned by the UPDATE command after each row is updated. The expression can use any column name from the table specified by table_name or from tables listed in FROM. Write * to return all columns.
output_name
A name to use for a returned column.
Output
On successful completion, an UPDATE command returns a command tag of the form UPDATE count. The count is the number of rows updated, including matching rows whose values did not change. Note that this number may be less than the number of rows matching condition when an update is suppressed by a BEFORE UPDATE trigger. If count is zero, no rows were updated by the query (this is not considered an error).
If the UPDATE command contains a RETURNING clause, its result will be similar to that of a SELECT statement (computed over the rows updated by the command) with the columns and values defined in the RETURNING list.
Notes
When a FROM clause is present, what essentially happens is: the target table is joined to the tables in the from_item list, and each output row of the join represents an update operation on the target table. When using FROM, you should ensure that the join produces at most one output row for each row to be modified. In other words, a target row should not be joined to more than one row from other tables. If this occurs, only one of the joined rows will be used to update the target row, but it is difficult to predict which one.
Due to this uncertainty, it is safer to reference other tables only in a sub-select, though such statements are typically harder to write and slower than using a join.
In the case of partitioned tables, updating a row may cause it to no longer satisfy the partition constraint of its current partition. In this case, if the row satisfies the partition constraint of some other partition in the partition tree, the row will be moved to that partition. If no such partition exists, an error will occur. Behind the scenes, row movement is actually a DELETE followed by an INSERT.
Concurrent UPDATE or DELETE operations on a moved row may receive a serialization failure error. Suppose session 1 is performing an UPDATE on the partition key, while a concurrent session 2 that can access the row performs an UPDATE or DELETE on the same row. In this case, session 2's UPDATE or DELETE will detect the row movement and raise a serialization failure error (this error always returns SQLSTATE code "40001"). If this occurs, the application may wish to retry the transaction. In the normal case where the table is not partitioned or no row movement occurs, session 2 will identify the newly updated row and perform the UPDATE/DELETE on this new row version.
Note that while rows can be moved from a local partition to a foreign table partition (if the foreign data wrapper supports tuple routing), they cannot be moved from a foreign table partition to another partition.
Examples
# Change the word Drama to Dramatic in the column kind of the table films:
UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama';
# Adjust temperature entries and reset precipitation to its default value in a row of the table weather:
UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
WHERE city = 'San Francisco' AND date = '2003-07-03';
# Perform the same operation and return the updated entries:
UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
WHERE city = 'San Francisco' AND date = '2003-07-03'
RETURNING temp_lo, temp_hi, prcp;
# Perform the same update using alternative column list syntax:
UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT)
WHERE city = 'San Francisco' AND date = '2003-07-03';
# Increase the sales count of the salesperson managing the Acme Corporation account, using FROM clause syntax:
UPDATE employees SET sales_count = sales_count + 1 FROM accounts
WHERE accounts.name = 'Acme Corporation'
AND employees.id = accounts.sales_person;
# Perform the same operation using a sub-select in the WHERE clause:
UPDATE employees SET sales_count = sales_count + 1 WHERE id =
(SELECT sales_person FROM accounts WHERE name = 'Acme Corporation');
# Update the contact names in the accounts table to match the currently assigned salesperson:
UPDATE accounts SET (contact_first_name, contact_last_name) =
(SELECT first_name, last_name FROM salesmen
WHERE salesmen.id = accounts.sales_id);
# A similar result can be achieved with a join:
UPDATE accounts SET contact_first_name = first_name,
contact_last_name = last_name
FROM salesmen WHERE salesmen.id = accounts.sales_id;
# However, if salesmen.id is not a unique key, the second query may give unexpected results, whereas the first query is guaranteed to raise an error if there are multiple matching ids. Also, if there is no match for a particular accounts.sales_id entry, the first query will set the corresponding name fields to NULL, while the second query will not update that row at all.
# Update statistics in a summary table to match current data:
UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) =
(SELECT sum(x), sum(y), avg(x), avg(y) FROM data d
WHERE d.group_id = s.group_id);
# Attempt to insert a new inventory item along with its stock quantity. If the item already exists, update the existing item's stock quantity instead. To do this without causing the entire transaction to fail, use savepoints:
BEGIN;
-- Other operations
SAVEPOINT sp1;
INSERT INTO wines VALUES('Chateau Lafite 2003', '24');
-- Suppose the above statement fails due to a unique key violation,
-- then we issue these commands:
ROLLBACK TO sp1;
UPDATE wines SET stock = stock + 24 WHERE winename = 'Chateau Lafite 2003';
-- Continue with other operations, and finally
COMMIT;
# Change the kind column of the row positioned by cursor c_films in the table films:
UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;