Inserting, Updating and Deleting · Lesson 36 of 64

SQL Changing Data Safely

What you will learn

  • The look, count, change, check routine
  • How to keep a copy of rows before a risky change
  • How to check a change afterwards
  • What you cannot undo

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. Why safety habits

On a real database, a wrong UPDATE or DELETE can change thousands of rows in a moment, and other people and programs use the data. The habits in this lesson are small and become automatic. Most database disasters are not clever attacks; they are a forgotten WHERE.

2. Look, count, change, check

  1. Look: run the change as a SELECT with the same WHERE and read some of the rows.
  2. Count: SELECT COUNT(*) with the same WHERE; note the number.
  3. Change: run the UPDATE or DELETE.
  4. Check: compare rows changed with the count, and SELECT the rows again.

Here it is on a real change:

Move all products in category 5 to a new supplier:

SELECT product_id, name, supplier_id FROM products WHERE category_id = 5 ORDER BY product_id;
product_id  name            supplier_id
----------  --------------  -----------
        14  Notebook A5               5
        15  Gel pens (10)             5
        16  Sticky notes              8
        17  Desk organiser            8
        18  Highlighters              6
        19  Paper clips               3
        20  Wall planner              6
(7 rows)
SELECT COUNT(*) AS rows_to_change FROM products WHERE category_id = 5;
rows_to_change
--------------
             7
(1 row)
UPDATE products SET supplier_id = 2 WHERE category_id = 5;
(7 rows changed)
SELECT product_id, name, supplier_id FROM products WHERE category_id = 5 ORDER BY product_id;
product_id  name            supplier_id
----------  --------------  -----------
        14  Notebook A5               2
        15  Gel pens (10)             2
        16  Sticky notes              2
        17  Desk organiser            2
        18  Highlighters              2
        19  Paper clips               2
        20  Wall planner              2
(7 rows)

Close every frozen savings account:

SELECT account_id, account_type, status FROM accounts WHERE status = 'frozen' AND account_type = 'savings' ORDER BY account_id;
account_id  account_type  status
----------  ------------  ------
        18  savings       frozen
       153  savings       frozen
       204  savings       frozen
       253  savings       frozen
       443  savings       frozen
(5 rows)
SELECT COUNT(*) AS rows_to_change FROM accounts WHERE status = 'frozen' AND account_type = 'savings';
rows_to_change
--------------
             5
(1 row)
UPDATE accounts SET status = 'closed' WHERE status = 'frozen' AND account_type = 'savings';
(5 rows changed)
SELECT account_id, account_type, status FROM accounts WHERE account_id IN (SELECT account_id FROM accounts WHERE account_type = 'savings' AND status = 'closed') ORDER BY account_id LIMIT 8;
account_id  account_type  status
----------  ------------  ------
         7  savings       closed
        18  savings       closed
        51  savings       closed
        95  savings       closed
       147  savings       closed
       148  savings       closed
       153  savings       closed
       156  savings       closed
(8 rows)

Raise the credits of every 3-credit course to 4:

SELECT course_id, code, credits FROM courses WHERE credits = 3 ORDER BY course_id;
course_id  code     credits
---------  -------  -------
        2  MATH201        3
        7  SCI301         3
        8  LANG101        3
       10  LANG201        3
       11  HUM101         3
       12  HUM201         3
       17  CS101          3
(7 rows)
SELECT COUNT(*) AS rows_to_change FROM courses WHERE credits = 3;
rows_to_change
--------------
             7
(1 row)
UPDATE courses SET credits = 4 WHERE credits = 3;
(7 rows changed)
SELECT course_id, code, credits FROM courses WHERE course_id IN (2, 3) ORDER BY course_id;
course_id  code     credits
---------  -------  -------
        2  MATH201        4
        3  MATH301        4
(2 rows)

The count (second query) and rows changed (third) must agree. If they do not, something is wrong with the condition.

3. Keep a copy first

Before a change you might regret, copy the affected rows into a scratch table. If the change was wrong, the copy lets you put the old values back:

CREATE TABLE products_backup AS SELECT * FROM products WHERE category_id = 6;
(done)
UPDATE products SET price = ROUND(price * 2, 2) WHERE category_id = 6;
(6 rows changed)

Oops, that was meant to be 10%, not double. Restore from the copy:

UPDATE products SET price = (SELECT b.price FROM products_backup AS b WHERE b.product_id = products.product_id)
WHERE product_id IN (SELECT product_id FROM products_backup);
(6 rows changed)
SELECT p.product_id, p.price AS price_now, b.price AS price_before
FROM products AS p JOIN products_backup AS b ON b.product_id = p.product_id ORDER BY p.product_id LIMIT 4;
product_id  price_now  price_before
----------  ---------  ------------
        21       24.0          24.0
        22       29.5          29.5
        23       49.0          49.0
        24       4.95          4.95
(4 rows)
CREATE TABLE accounts_backup AS SELECT * FROM accounts WHERE branch_id = 3;
(done)
UPDATE accounts SET balance_cents = balance_cents * 2 WHERE branch_id = 3;
(64 rows changed)

Oops, that was a mistake. Restore from the copy:

UPDATE accounts SET balance_cents = (SELECT b.balance_cents FROM accounts_backup AS b WHERE b.account_id = accounts.account_id)
WHERE account_id IN (SELECT account_id FROM accounts_backup);
(64 rows changed)
SELECT a.account_id, a.balance_cents AS balance_now, b.balance_cents AS balance_before
FROM accounts AS a JOIN accounts_backup AS b ON b.account_id = a.account_id ORDER BY a.account_id LIMIT 4;
account_id  balance_now  balance_before
----------  -----------  --------------
        11        54700           54700
        26        38000           38000
        31        34800           34800
        36         9700            9700
(4 rows)
CREATE TABLE sections_backup AS SELECT * FROM sections WHERE term = '2026-Spring';
(done)
UPDATE sections SET capacity = capacity * 2 WHERE term = '2026-Spring';
(11 rows changed)

Oops, that was a mistake. Restore from the copy:

UPDATE sections SET capacity = (SELECT b.capacity FROM sections_backup AS b WHERE b.section_id = sections.section_id)
WHERE section_id IN (SELECT section_id FROM sections_backup);
(11 rows changed)
SELECT s.section_id, s.capacity AS capacity_now, b.capacity AS capacity_before
FROM sections AS s JOIN sections_backup AS b ON b.section_id = s.section_id ORDER BY s.section_id LIMIT 4;
section_id  capacity_now  capacity_before
----------  ------------  ---------------
         4            30               30
        14            30               30
        19            25               25
        22            35               35
(4 rows)

On a real database, a full backup (Database Fundamentals, chapter 8) is the real safety net; a scratch copy is a quick extra for one change.

4. Change in small steps

Do not mix several different changes in one statement. Make one change, check it, then the next. For a huge change, try it on a sample first: the first 100 rows, or a copy of the table.

5. Check afterwards

Check more than "no error". Useful checks after a change:

  • Counts: the number of rows with each value, before and after (GROUP BY counts, lesson 3.2).
  • Totals: a sum that must not change, or must change by a known amount.
  • A few rows: SELECT the rows you changed and some you did not.
SELECT supplier_id, COUNT(*) AS products FROM products GROUP BY supplier_id ORDER BY supplier_id;
supplier_id  products
-----------  --------
          1         5
          2        13
          3         7
          4         1
          5         1
          6         2
          7         3
          8         2
          9         5
         10         6
(10 rows)
SELECT status, COUNT(*) AS accounts FROM accounts GROUP BY status ORDER BY status;
status  accounts
------  --------
closed        35
frozen        11
open         404
(3 rows)
SELECT credits, COUNT(*) AS courses FROM courses GROUP BY credits ORDER BY credits;
credits  courses
-------  -------
      2        5
      4       14
(2 rows)

6. What you cannot undo

After a change is saved (committed, lesson 5.5), the old values are gone from the table. Only a backup or a copy that you made can bring them back. That is why copies come before the change, and why transactions (next lesson) matter: they let you take a change back before it is saved.

Worked example: the checklist before pressing Run

Question Yes?
Does the statement have a WHERE (or do I really mean every row)?
Did I run the WHERE as a SELECT and read the rows?
Do I know how many rows should change?
Is there a backup or a copy of the affected rows?
Am I on the right database (not production by mistake)?

If any answer is "no", stop and fix that first. The list is for any change to real data.

Common mistakes

  • Running a change on the wrong database (production instead of a test copy).
  • No backup, so a mistake cannot be undone.
  • Changing in one big step with no check in between.
  • Checking only for errors, not for the right numbers.
  • Trusting a condition you never ran as a SELECT.

Key takeaways

  • Look, count, change, check: run the WHERE as a SELECT first, and compare rows changed with the count.
  • Keep a copy of the affected rows (or a backup) before a risky change.
  • Make small changes and check the result with counts and totals.
  • A saved change cannot be undone; copies and transactions come first.

Practice

1. What are the four steps of a safe change?

Show answer

Look, count, change, check.

2. How do you keep a copy of some rows before changing them?

Show answer

CREATE TABLE copy AS SELECT * FROM table WHERE condition;

3. What should rows changed equal?

Show answer

The count from the SELECT COUNT(*) with the same WHERE.

4. Why try a change on a sample first?

Show answer

A mistake affects only a few rows or a copy, and you can see the effect before touching all the data.

5. Name two checks to run after a change.

Show answer

For example counts per value before and after, a total that must not change, and a look at some changed rows.

6. Why do copies have to be made before the change?

Show answer

Once the change is saved, the old values no longer exist in the table.