SQL from Zero › Module 3: DML: filling and changing data

Changing rows with UPDATE

Fix a price, restock a book, run a sale, and why WHERE matters so much.

Lesson 14 of 33 · about 12 minutes

Video: Relabelling the price tagsThe narrated video for this lesson is coming soon. The lesson below covers the same ideas.

The lesson

Prices change, stock runs out, people move house. UPDATE changes values in rows that already exist.

UPDATE books
SET price = 19.99
WHERE title = 'Sapiens';

Reading it out loud: "In books, set the price to 19.99, but only where the title is Sapiens."

You can change several columns at once, and use the current value in a calculation:

UPDATE books
SET stock = stock + 10, price = 12.99
WHERE id = 4;

⚠️ The most important rule in this lesson: always write the WHERE. Without it, UPDATE changes every row in the table. UPDATE books SET price = 0; makes every book free.

A habit professionals use: first run a SELECT with the same WHERE, check it returns only the rows you expect, then turn it into an UPDATE.

SELECT * FROM books WHERE genre = 'Fantasy';  -- check first
UPDATE books SET price = ROUND(price * 0.9, 2) WHERE genre = 'Fantasy';  -- then change

ROUND(value, 2) keeps prices to two decimal places.

Key ideas
  • UPDATE table SET column = value WHERE condition changes existing rows.
  • Without WHERE, every row is changed. Check with a SELECT first.
  • SET can use the current value, like stock = stock + 10, and change several columns at once.

Practise

Loading practice…

Quick check

1. What does UPDATE books SET price = 5; do?

2. What's a safe habit before running an UPDATE?

3. Which adds 5 copies to the current stock of book 2?