Sub topic 2
Changing rows with UPDATE
This chapter assumes you know basic SELECT with WHERE, the orders table from the example schema (columns id, customer_id, total, status), and how primary keys work. The examples use standard SQL and run on PostgreSQL, MySQL, SQL Server, or SQLite with minor syntax changes.
Changing rows with UPDATE
UPDATE changes the values in existing rows. The SET clause names the columns and their new values. The WHERE clause picks which rows change.
UPDATE orders
SET status = 'shipped'
WHERE id = 100;Without WHERE, every row in the table changes. Always include a WHERE clause unless you truly want all rows updated.
Computing new values from old ones
The right side of SET can use the current values in the row. You can also change several columns in one statement.
UPDATE orders
SET total = total * 1.10,
status = 'repriced'
WHERE status = 'new';In this statement, every total is read before the update and multiplied by 1.10. Both assignments apply to the same matched rows.
Removing rows with DELETE
DELETE FROM removes rows. It uses the same WHERE logic as UPDATE.
DELETE FROM orders
WHERE status = 'cancelled';Previewing and limiting the rows you change
Run a SELECT with the same WHERE condition before you change anything. The row count tells you how many rows the statement will affect.
SELECT COUNT(*) FROM orders WHERE status = 'cancelled';
DELETE FROM orders
WHERE status = 'cancelled';> Tip: Keep the WHERE conditions of the preview and the change identical. Copying one condition into both statements prevents most accidental changes.
Exercise
Write a statement that sets the status of order 205 to 'cancelled' and changes no other order.
Show answer
UPDATE orders SET status = 'cancelled' WHERE id = 205;