Sub topic 7
Computing new values from old ones
This chapter covers the right-hand side of SET in an UPDATE. You can compute a new value from the row's current values, from other columns, from functions, and from subqueries. The sections below also cover the pitfalls: NULL arithmetic, rounding, and what happens when you assign several columns at once.
It assumes you can write SELECT ... WHERE, know basic UPDATE ... SET ... WHERE, and know the example schema (customers and orders) from earlier in this tutorial.
The right-hand side is an expression
In SET column = expression, the expression can be anything that produces one value of a compatible type. Common ingredients are:
- Column references, such as
total - Literals, such as
1.10or'repriced' - Arithmetic, such as
total * 1.10 - Functions, such as
UPPER(name)orCOALESCE(email, '') CASEexpressions- Scalar subqueries, meaning a
SELECTthat returns exactly one value
Here is the update from the spine, which uses two of these:
UPDATE orders
SET total = total * 1.10,
status = 'repriced'
WHERE status = 'new';For each row where status = 'new', the database reads the row's current total, multiplies it by 1.10, and stores the result. It also sets status. One statement changes two columns on every matching row.
Old values on the right, new values on the left
Every reference to a column on the right-hand side means the value the row had before the statement changed it. The standard says all the right-hand expressions are evaluated against the old row, and then the assignments are applied.
PostgreSQL, SQL Server, and SQLite follow this rule. MySQL is the exception. By default MySQL evaluates assignments left to right, so a later assignment sees the already-updated value of an earlier one. Compare:
-- Swap two columns. Assume a table with columns a and b.
UPDATE pairs
SET a = b,
b = a;In PostgreSQL, SQL Server, and SQLite this swaps the values. In MySQL, a receives b, and then b receives the new a, so both columns end up holding the old b. In MySQL, avoid depending on assignment order. Put the assignments in an order that works in both cases, or use a temporary value.
Percentages and rounding
The total column is NUMERIC(10, 2), which holds two decimal places. Multiplying by 1.10 can produce more digits than that. For example, 19.99 * 1.10 is 21.989. The database must fit the result into the column.
Most databases round the result to the column's scale when they store it. The exact rule differs by system, so make the rounding explicit with ROUND:
UPDATE orders
SET total = ROUND(total * 1.10, 2)
WHERE status = 'new';Two more points to check:
- If the result needs more digits before the decimal point than the column allows, the statement fails with a numeric overflow error.
NUMERIC(10, 2)allows up to 8 digits before the point. - Do not use floating-point types for money.
NUMERICkeeps decimal values exact, andFLOATdoes not.
NULL in arithmetic
Any arithmetic with NULL produces NULL. If a column allows NULL and you write SET bonus = bonus + 10, rows where bonus is NULL stay NULL. The statement does not fail, so the problem is easy to miss.
Use COALESCE, which returns its first non-NULL argument, to supply a fallback:
-- Assume a nullable column: customers.loyalty_points INTEGER
UPDATE customers
SET loyalty_points = COALESCE(loyalty_points, 0) + 10
WHERE status = 'active';Now a customer with no points recorded gets 10 instead of staying NULL.
The opposite problem also exists. Setting a column to NULL on purpose is allowed only if the column accepts NULL. In the example schema, customers.name is NOT NULL, so SET name = NULL is rejected. COALESCE can also protect against this:
UPDATE customers
SET name = COALESCE(NULLIF(TRIM(name), ''), 'Unknown');TRIM removes surrounding spaces. NULLIF(x, '') turns an empty string into NULL. COALESCE then replaces NULL with 'Unknown'. Note that this statement has no WHERE, so it touches every row. That is intended here, but you should always notice when it is.
Conditional values with CASE
A CASE expression lets one statement apply different rules to different rows. The alternative is several separate UPDATE statements, each scanning the table.
UPDATE orders
SET total = CASE
WHEN total >= 500 THEN ROUND(total * 0.95, 2)
WHEN total >= 100 THEN ROUND(total * 0.98, 2)
ELSE total
END
WHERE status = 'new';Always include an ELSE. Without it, rows that match no WHEN branch receive NULL. For total, which is NOT NULL, that would make the whole statement fail. For a nullable column it would silently erase data. Writing ELSE total keeps the old value.
Using values from another table
A scalar subquery can supply the new value. It must return at most one row and one column. If it returns more than one row, the database raises an error. If it returns none, the result is NULL.
-- Assume a nullable column: customers.order_count INTEGER
UPDATE customers
SET order_count = (
SELECT COUNT(*)
FROM orders
WHERE orders.customer_id = customers.id
);The subquery is correlated: it refers to customers.id from the outer row, so it runs once for each customer. COUNT(*) always returns a row, so customers with no orders get 0. If you had used MAX(total) instead, customers with no orders would get NULL.
The dialect-specific UPDATE ... FROM and UPDATE ... JOIN forms are covered in a later chapter. A correlated subquery works in all four dialects.
Check the result before you run it
The new value is just an expression, so you can test it with a SELECT first. Put the same expression in the select list next to the old value:
SELECT id,
total AS old_total,
ROUND(total * 1.10, 2) AS new_total
FROM orders
WHERE status = 'new';This shows the rows the WHERE clause matches and the exact values SET would store. It catches rounding surprises, NULL results, and a WHERE that matches too many rows.
Constraints still apply
Computed values must pass the same constraints as inserted values. A few examples against the example schema:
SET email = '[email protected]'fails with aUNIQUEviolation if another customer already has that email.SET customer_id = 999on an order fails if no customer 999 exists.- A calculation that produces NULL for a
NOT NULLcolumn fails.
The failure is all or nothing. If one row out of a thousand violates a constraint, the statement fails and none of the thousand rows change. A computed update that puts two rows on the same unique value is a common cause.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Forgetting `WHERE` | Every row is recalculated | Preview with `SELECT`, use a transaction |
| Running a percentage update twice | The increase compounds (1.10 × 1.10) | Filter on a status that the update changes, as the `'new'` to `'repriced'` example does |
| Arithmetic on a nullable column | NULL stays NULL | Use `COALESCE` |
| `CASE` with no `ELSE` | Unmatched rows become NULL | Add `ELSE column` |
| Order-dependent `SET` list | Different results in MySQL | Avoid reading a column you also assign |
| Subquery returns several rows | Error | Aggregate, or make the match unique |
The "running twice" mistake deserves attention. An update such as SET total = total * 1.10 is not idempotent: each run changes the data further. The spine example guards against this by selecting status = 'new' and changing the status in the same statement, so a second run matches no rows.
Exercise
A table products has price NUMERIC(8, 2) NOT NULL and discount NUMERIC(8, 2) which may be NULL. You run UPDATE products SET price = price - discount;. Some prices are now unchanged and others are lower, but the statement raised an error on a database where price is NOT NULL. What went wrong, and how do you rewrite it so rows with a NULL discount keep their price?
Show answer
For rows where discount is NULL, price - discount is NULL, and assigning NULL to the NOT NULL column price makes the statement fail. Because failure is all or nothing, no row changed (so the "lower" prices you saw came from another source, such as a database that does not enforce it, or an earlier statement). Rewrite it as UPDATE products SET price = price - COALESCE(discount, 0);. Preview it first with a SELECT that shows price and price - COALESCE(discount, 0).
Exercise
Why is UPDATE orders SET total = ROUND(total * 1.10, 2); risky to run twice, and what two changes make a safe version?
Show answer
Each run multiplies the totals again, so the 10 percent increase compounds, and with no WHERE it hits every order. Add a WHERE that selects only rows not yet processed (for example status = 'new'), and set a marker in the same statement (for example status = 'repriced') so a second run matches nothing. Wrapping it in a transaction and previewing with SELECT adds further protection.