Stop 09 · Modifying DataTopics · 3/9

UPDATE with WHERE

Part of the SQL Roadmap

In short

UPDATE is how prices change, addresses get fixed and orders move to 'shipped'. It's also the statement behind many famous data accidents, and the difference is one WHERE line.

UPDATE changes values in existing rows. Without a WHERE clause it changes every row in the table, so always check the condition first.

The jaadu holds a red pen over a tall pile of answer sheets, carefully pulling out only the few sheets with a blue corner tab to correct.

Think of it like this

The teacher's red pen

A teacher finds that question 4 was marked wrongly, but only for Section B. She picks out Section B's answer sheets and corrects just those. If she corrected every sheet in the school, it would be chaos. WHERE is the step where she picks the right sheets.

Watch it happen

UPDATE products SET price = price * 1.05 WHERE category = 'Stationery'

Pen ₹20
0
Rice ₹60
1
Notebook ₹50
2
Oil ₹180
3
Pencil ₹10
4

1/4Five products in the table. Only the stationery ones should get a 5% price rise.

The big ideas

What you need to know

WHERE picks the rows

UPDATE changes every row the WHERE matches. No WHERE means every row in the table.

Commas between changes

SET price = 21, stock = 50 changes two columns. Use commas, never AND, between them.

Use the old value

SET price = price * 1.05 reads the current value and writes the new one in a single step.

Use the key for one row

To change one specific row, filter on its primary key, like WHERE product_id = 42, not on a name.

See it in code

Walk through the code

sql
1SELECT product_id, product_name, price2FROM products3WHERE category = 'Stationery'4  AND price < 500;5 6UPDATE products7SET price      = ROUND(price * 1.05, 2),8    updated_at = NOW()9WHERE category = 'Stationery'10  AND price < 500;

1/3Run this first. The rows it returns are exactly the rows the UPDATE will change.

Preview the rows, then raise stationery prices under ₹500 by 5%. Works in PostgreSQL and MySQL. In SQL Server, use GETDATE() instead of NOW().

Save yourself the pain

Common mistakes

Oops

Running UPDATE products SET price = 0 and forgetting the WHERE.

Do this instead

Every row changes. Write the WHERE first, preview it with SELECT, and work inside a transaction.

Oops

Writing SET price = 21 AND stock = 50.

Do this instead

Use a comma: SET price = 21, stock = 50. With AND, the database reads it as one boolean expression and fails or writes nonsense.

Your mission

A careful price change

~15 min

Quick check

What does UPDATE orders SET status = 'shipped'; do?

Go deeper

  1. 1Run the WHERE condition as a SELECT before turning it into an UPDATE.
  2. 2Practise updates inside a transaction so you can roll back.
  3. 3Update one table using values joined from another.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge