Inserting, Updating and Deleting · Lesson 34 of 64

SQL UPDATE

What you will learn

  • How UPDATE ... SET ... WHERE changes rows
  • How to change several columns, and calculate the new value from the old
  • How to read the number of rows changed
  • Why WHERE is essential

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The changes happen only in your browser's copy of the data; Reset data puts everything back. Run the cells from top to bottom.

1. UPDATE one row

UPDATE table SET column = value WHERE condition changes the rows that match. Use the primary key in the condition to change exactly one row. Look before and after:

SELECT product_id, name, price FROM products WHERE product_id = 1;
product_id  name       price
----------  ---------  -----
         1  Steel pan    6.6
(1 row)
UPDATE products SET price = 7.5 WHERE product_id = 1;
(1 row changed)
SELECT product_id, name, price FROM products WHERE product_id = 1;
product_id  name       price
----------  ---------  -----
         1  Steel pan    7.5
(1 row)
SELECT account_id, status FROM accounts WHERE account_id = 1;
account_id  status
----------  ------
         1  open
(1 row)
UPDATE accounts SET status = 'frozen' WHERE account_id = 1;
(1 row changed)
SELECT account_id, status FROM accounts WHERE account_id = 1;
account_id  status
----------  ------
         1  frozen
(1 row)
SELECT course_id, title, credits FROM courses WHERE course_id = 1;
course_id  title                   credits
---------  ----------------------  -------
        1  Foundations of Algebra        4
(1 row)
UPDATE courses SET credits = 5 WHERE course_id = 1;
(1 row changed)
SELECT course_id, title, credits FROM courses WHERE course_id = 1;
course_id  title                   credits
---------  ----------------------  -------
        1  Foundations of Algebra        5
(1 row)

The middle statement reports how many rows it changed (1 row changed). Always check that number against what you expect.

2. Change several columns

Separate the assignments with commas:

UPDATE products SET price = 8.0, stock = 25 WHERE product_id = 1;
(1 row changed)
SELECT product_id, price, stock FROM products WHERE product_id = 1;
product_id  price  stock
----------  -----  -----
         1    8.0     25
(1 row)
UPDATE accounts SET status = 'open', account_type = 'savings' WHERE account_id = 1;
(1 row changed)
SELECT account_id, status, account_type FROM accounts WHERE account_id = 1;
account_id  status  account_type
----------  ------  ------------
         1  open    savings
(1 row)
UPDATE courses SET credits = 4, title = 'Foundations of Algebra I' WHERE course_id = 1;
(1 row changed)
SELECT course_id, title, credits FROM courses WHERE course_id = 1;
course_id  title                     credits
---------  ------------------------  -------
        1  Foundations of Algebra I        4
(1 row)

3. Calculate from the old value

The new value may be an expression that uses the current value of columns of the same row:

Raise the price of product 2 by 10% (and round it):

SELECT product_id, price FROM products WHERE product_id = 2;
product_id  price
----------  -----
         2   44.1
(1 row)
UPDATE products SET price = ROUND(price * 1.10, 2) WHERE product_id = 2;
(1 row changed)
SELECT product_id, price FROM products WHERE product_id = 2;
product_id  price
----------  -----
         2  48.51
(1 row)

Add 5.00 (500 cents) to account 2:

SELECT account_id, balance_cents FROM accounts WHERE account_id = 2;
account_id  balance_cents
----------  -------------
         2          52078
(1 row)
UPDATE accounts SET balance_cents = balance_cents + 500 WHERE account_id = 2;
(1 row changed)
SELECT account_id, balance_cents FROM accounts WHERE account_id = 2;
account_id  balance_cents
----------  -------------
         2          52578
(1 row)

Add one point to a grade:

SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 AND section_id = 30;
student_id  section_id  grade
----------  ----------  -----
         1          30   49.2
(1 row)
UPDATE enrollments SET grade = grade + 1 WHERE student_id = 1 AND section_id = 30;
(1 row changed)
SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 AND section_id = 30;
student_id  section_id  grade
----------  ----------  -----
         1          30   50.2
(1 row)

On the right of = the old values are used; the result is stored. This is safe and tidy: the database reads and writes the row in one step (Database Fundamentals, lesson 6.4 shows why that matters).

4. Change many rows

A condition that matches many rows changes all of them:

Put products with no stock on the shelf out of sale (is_active = 0). First count them:

SELECT COUNT(*) AS products_with_no_stock FROM products WHERE stock = 0;
products_with_no_stock
----------------------
                     9
(1 row)
UPDATE products SET is_active = 0 WHERE stock = 0;
(9 rows changed)
SELECT COUNT(*) AS now_inactive FROM products WHERE is_active = 0;
now_inactive
------------
          11
(1 row)

Mark every blocked card as expired. First count:

SELECT COUNT(*) AS blocked_cards FROM cards WHERE status = 'blocked';
blocked_cards
-------------
           12
(1 row)
UPDATE cards SET status = 'expired' WHERE status = 'blocked';
(12 rows changed)
SELECT COUNT(*) AS blocked_now FROM cards WHERE status = 'blocked';
blocked_now
-----------
          0
(1 row)

Give every 2025-Spring section 5 more seats. First look at the totals:

SELECT COUNT(*) AS sections, SUM(capacity) AS seats FROM sections WHERE term = '2025-Spring';
sections  seats
--------  -----
      16    480
(1 row)
UPDATE sections SET capacity = capacity + 5 WHERE term = '2025-Spring';
(16 rows changed)
SELECT COUNT(*) AS sections, SUM(capacity) AS seats FROM sections WHERE term = '2025-Spring';
sections  seats
--------  -----
      16    560
(1 row)

The count before the update told us how many rows to expect, and the statement's rows changed should be the same.

5. UPDATE from another table

The new value can come from a subquery (chapter 7). For example, set a column to a value looked up in another table:

Copy each customer's lower-cased city into a scratch table, then update the scratch table from customers:

CREATE TABLE city_notes (customer_id INTEGER PRIMARY KEY, city TEXT);
INSERT INTO city_notes (customer_id) SELECT customer_id FROM customers WHERE customer_id <= 3;
(3 rows changed)
UPDATE city_notes SET city = (SELECT city FROM customers WHERE customers.customer_id = city_notes.customer_id);
(3 rows changed)
SELECT * FROM city_notes ORDER BY customer_id;
customer_id  city
-----------  -----
          1  Leeds
          2  Leeds
          3  Cairo
(3 rows)

Copy each account's type into a scratch table, then update it from accounts:

CREATE TABLE type_notes (account_id INTEGER PRIMARY KEY, account_type TEXT);
INSERT INTO type_notes (account_id) SELECT account_id FROM accounts WHERE account_id <= 3;
(3 rows changed)
UPDATE type_notes SET account_type = (SELECT account_type FROM accounts WHERE accounts.account_id = type_notes.account_id);
(3 rows changed)
SELECT * FROM type_notes ORDER BY account_id;
account_id  account_type
----------  ------------
         1  savings
         2  savings
         3  savings
(3 rows)

Copy each course's title into a scratch table, then update it from courses:

CREATE TABLE title_notes (course_id INTEGER PRIMARY KEY, title TEXT);
INSERT INTO title_notes (course_id) SELECT course_id FROM courses WHERE course_id <= 3;
(3 rows changed)
UPDATE title_notes SET title = (SELECT title FROM courses WHERE courses.course_id = title_notes.course_id);
(3 rows changed)
SELECT * FROM title_notes ORDER BY course_id;
course_id  title
---------  ------------------------
        1  Foundations of Algebra I
        2  Geometry
        3  Statistics
(3 rows)

6. The danger: no WHERE

UPDATE without WHERE changes every row of the table. There is no "are you sure?" The habit that prevents it: write the WHERE first, run it as a SELECT to see which rows match, and only then turn it into an UPDATE:

SELECT COUNT(*) AS rows_that_match FROM products WHERE price > 40;
rows_that_match
---------------
              8
(1 row)
UPDATE products SET price = price WHERE price > 40;
(8 rows changed)
SELECT COUNT(*) AS rows_that_match FROM accounts WHERE balance_cents > 400000;
rows_that_match
---------------
              4
(1 row)
UPDATE accounts SET balance_cents = balance_cents WHERE balance_cents > 400000;
(4 rows changed)
SELECT COUNT(*) AS rows_that_match FROM courses WHERE credits > 3;
rows_that_match
---------------
              7
(1 row)
UPDATE courses SET credits = credits WHERE credits > 3;
(7 rows changed)

(This update sets each column to its own value, so it changes nothing; it only shows that the rows changed equals the count of the SELECT. Lesson 5.4 collects the safety habits.)

Worked example: a safe price change

"Raise the price of all products in category 3 by 5%."

Step Do
1 SELECT product_id, price FROM products WHERE category_id = 3; and look at the rows
2 SELECT COUNT(*) FROM products WHERE category_id = 3; and note the number
3 UPDATE products SET price = ROUND(price * 1.05, 2) WHERE category_id = 3;
4 check that rows changed equals the count
5 SELECT the rows again and compare

The table is from the Shop sample.

Common mistakes

  • No WHERE, changing every row.
  • A condition that matches too many rows. Count first.
  • Comparing with = against NULL in the WHERE (lesson 2.5).
  • Updating a primary key that other tables refer to.
  • Not checking the rows changed number.

Key takeaways

  • UPDATE t SET a = x, b = y WHERE condition changes the matching rows.
  • The new value can be calculated from the old: SET stock = stock - 1.
  • Check rows changed against a SELECT COUNT(*) with the same WHERE.
  • Write the WHERE first and test it as a SELECT.

Practice

1. Write an update that sets the status of account 5 to closed.

Show answer

UPDATE accounts SET status = 'closed' WHERE account_id = 5;

2. What does UPDATE products SET price = price * 2 do without a WHERE?

Show answer

It doubles the price of every product.

3. How can you know how many rows an update will change before you run it?

Show answer

Run SELECT COUNT(*) FROM table WHERE condition with the same condition.

4. What does SET stock = stock - 1 use on the right of the equals sign?

Show answer

The current (old) value of stock in that row.

5. How do you change two columns in one update?

Show answer

Separate the assignments with a comma: SET a = 1, b = 2.

6. Why check the rows changed number?

Show answer

It tells you if the update touched the number of rows you expected; a surprise means a wrong condition.