Lesson 12 +10 XP

UPDATE Statement

UPDATE Statement

The UPDATE statement modifies existing rows.

Basic syntax

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
  • SET lists the columns to change and their new values.
  • WHERE picks which rows to change.

BE CAREFUL: UPDATE without WHERE

UPDATE Customers
SET ContactName = 'Nobody';

This updates every row in the table! Always check your WHERE clause.

Update multiple rows

UPDATE Customers
SET ContactName = 'Juan'
WHERE Country = 'Mexico';

Updates every customer in Mexico.

The safe pattern

  1. First run a SELECT with the same WHERE to see what matches.
  2. Then run the UPDATE.
SELECT * FROM Customers WHERE CustomerID = 1;  -- check
UPDATE Customers SET ContactName = 'New Name' WHERE CustomerID = 1;  -- change

TL;DR

  • UPDATE changes existing rows.
  • SET holds the new values.
  • WHERE decides which rows change.
  • Forgetting WHERE updates every row.