UPDATE
TheUPDATE statement modifies the values of columns in existing rows of a table.
Syntax
Description
UPDATE changes column values in rows that match the WHERE condition. If no WHERE clause is provided, all rows in the table are updated.
Conflict Handling
The optionalOR clause specifies how to handle constraint violations during the update. When omitted, the default behavior is ABORT.
| Algorithm | Behavior |
|---|---|
ABORT | Roll back the current statement and return an error. The transaction remains active. This is the default. |
ROLLBACK | Roll back the entire transaction and return an error. |
FAIL | Stop at the first constraint violation and return an error, but keep changes made by earlier rows in this statement. |
IGNORE | Skip the row that caused the constraint violation and continue processing remaining rows. |
REPLACE | Delete the conflicting row before updating the current row. If a NOT NULL constraint fails and there is no DEFAULT value, the statement behaves as ABORT. |
SET Clause
TheSET clause assigns new values to one or more columns. Each assignment consists of a column name, an equals sign, and an expression. The expression can reference other columns of the same row, and it sees the original (pre-update) values of all columns.
FROM Clause
TheFROM clause allows the UPDATE to reference other tables. Columns from the joined tables can be used in SET expressions and the WHERE clause. This is useful for updating a table based on matching rows from another table.
FROM clause, it refers to a second instance of that table that can be used for self-joins.
WHERE Clause
TheWHERE clause restricts which rows are updated. Only rows where the expression evaluates to true are modified. If the WHERE clause is omitted, every row in the table is updated.
RETURNING Clause
TheRETURNING clause causes the UPDATE statement to return the new values of each modified row. The result columns can be expressions referencing the updated column values.
ORDER BY and LIMIT
TheORDER BY and LIMIT clauses restrict which rows are updated. ORDER BY determines the order in which rows are considered, and LIMIT caps the number of rows that are actually modified. ORDER BY requires LIMIT to be present.
LIMIT accepts an optional OFFSET to skip a number of rows before applying the limit:
Examples
Update rows matching a condition
Update using a join with FROM
Update with RETURNING
See Also
- INSERT for adding new rows
- DELETE for removing rows
- INSERT … ON CONFLICT for conditional insert-or-update operations
- SELECT for querying data