Sub topic 7
Computing New Values from Old Ones
Assume you know how to select rows with WHERE, and that orders contains numeric columns such as total and text columns such as status. In this chapter, you will use expressions in UPDATE statements to calculate new values from each row's current values.
Use the Current Value in `SET`
The right side of an assignment can refer to the column being changed. For example, this increases every new order by 10 percent:
UPDATE orders
SET total = total * 1.10
WHERE status = 'new';For each matching row, the database reads the current total, multiplies it by 1.10, and stores the result. An order totaling 50.00 becomes 55.00.
The WHERE clause is essential. Without it, every order would receive a 10 percent increase.
You can update several columns in one statement. Each expression can use the row's existing values:
UPDATE orders
SET total = total * 1.10,
status = 'repriced'
WHERE status = 'new';The comma separates assignments. Do not use AND between them.
SELECT
id,
total AS old_total,
total * 1.10 AS new_total,
status AS old_status
FROM orders
WHERE status = 'new';This query changes nothing. It lets you check the affected rows and the calculated values first.
Conditional Calculations with CASE
CASE produces different values based on conditions. This is useful when a change depends on several rules:
UPDATE orders
SET status = CASE
WHEN total >= 1000 THEN 'priority'
WHEN total >= 100 THEN 'standard'
ELSE 'small'
END
WHERE status = 'new';Every matching row receives exactly one result. The database checks the WHEN clauses from top to bottom and uses the first true condition.
You can also calculate a value with CASE:
UPDATE orders
SET total = CASE
WHEN total < 20 THEN total + 5
ELSE total
END
WHERE status = 'new';Here, only small orders receive a fee. The other matching rows keep their current totals.
Common Errors
- Omitting
WHEREupdates every row. - Using
total + 10when you mean a 10 percent increase. Usetotal * 1.10. - Forgetting that
NULLusually makes arithmetic produceNULL. Handle missing values withCOALESCE, such asCOALESCE(discount, 0). - Assuming all database systems handle multiple assignments in exactly the same way. Keep each expression clear, and do not make one assignment depend on another assignment in the same statement unless your database documents that behavior.
After checking the preview, run the update inside a transaction when the change matters. You can inspect the result and roll it back if the calculation is wrong.
Exercise
Write an UPDATE statement that adds 5 percent to orders with status 'pending' and changes their status to 'reviewed'.
Show answer
UPDATE orders SET total = total * 1.05, status = 'reviewed' WHERE status = 'pending';