Until now, you read rows and added rows. Rows also change: a price goes down, new stock arrives, a customer gives a new email. UPDATE changes values in rows that already exist.
sql
UPDATE products
SET price = 27.99
WHERE id = 1;UPDATE productschange this tableSET price = 27.99column = new valueWHERE id = 1only these rows
products
| id | name | price | stock |
|---|---|---|---|
| 1 | Kraken Plush | 27.99 | 40 |
| 2 | Pod Golem Plush | 34.50 | 12 |
| 3 | Daemon Cat Plush | 24.00 | 0 |
WHEREworks the same as in a SELECT. It picks the rows to change.- The rows that WHERE does not keep do not change.
- The columns that SET does not name do not change.
Several columns
Put a comma between each two column = value pairs:
sql
UPDATE products
SET price = 27.99, stock = 50
WHERE id = 1;Use the old value
The new value can be an expression. A column name in it gives the value before the change:
sql
UPDATE products
SET stock = stock + 10
WHERE id = 2;stock = 12before
12 + 10
stock = 22after
When WHERE keeps several rows, the expression runs once for each row, with that row's own value.
The new value must fit the column. Its type and every constraint still apply: price = -5 fails the CHECK (price >= 0) on products.