INSERT, UPDATE and DELETE — safely

Add, change and remove rows, and the habits that stop you destroying data by accident.

Module 6: Changing data and designing tables · Lesson 21 of 26 · 15 min read · Free

So far you've only read data. Analysts mostly do that, but sooner or later you'll need to add a record, correct a mistake or clear out test rows. These statements change data, so they come with habits.

INSERT: add a row

INSERT INTO products (name, category, unit_price, cost_price)
VALUES ('Golden Morn 500g', 'Food', 2100, 1700);
  • List the columns, then the values in the same order.
  • Leave out product_id: an INTEGER PRIMARY KEY gets the next number automatically (31).
  • Several rows at once: VALUES (…), (…), (…);

UPDATE: change existing rows

UPDATE products
SET unit_price = 700
WHERE name = 'Peak Milk Tin 160g';

SET gives the new value(s); WHERE says which rows. Several columns: SET unit_price = 700, cost_price = 560.

DELETE: remove rows

DELETE FROM products
WHERE name = 'Golden Morn 500g';

The safe routine

  1. Write the WHERE as a SELECT first. SELECT * FROM products WHERE name = 'Peak Milk Tin 160g'; — check it returns exactly the rows you mean.
  2. Change SELECT * into UPDATE … SET … or DELETE, keeping the same WHERE.
  3. Check the message: 1 row affected. If it says 30, something's wrong.
  4. In DB Browser, nothing is permanent until Write Changes (Ctrl+S). Revert Changes undoes everything since the last write.

Other databases use transactions for the same safety net:

BEGIN;
UPDATE products SET unit_price = unit_price * 1.10 WHERE category = 'Beverages';
-- check the result...
COMMIT;      -- keep it, or
-- ROLLBACK; -- undo it

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. What happens if you run UPDATE products SET unit_price = 700; with no WHERE?

    • A Every product's price becomes 700
    • B Nothing — WHERE is required
    • C Only the first product changes
    • D An error
    Show the answer

    A) Every product's price becomes 700 — Without WHERE, every row is updated.

  2. What's the safest first step before a DELETE?

    • A Run a SELECT with the same WHERE to see which rows will go
    • B Delete and check afterwards
    • C Remove the primary key
    • D Close the database
    Show the answer

    A) Run a SELECT with the same WHERE to see which rows will go — Check exactly which rows match before changing anything.

  3. In a transaction, which command undoes the changes?

    • A ROLLBACK
    • B COMMIT
    • C UNDO
    • D REVERT TABLE
    Show the answer

    A) ROLLBACK — ROLLBACK discards changes since BEGIN; COMMIT keeps them.

More free lessons: What SQL is, and why employers want it · Install DB Browser and open the practice database · WHERE: only the rows you need · COUNT, SUM, AVG, MIN and MAX · INNER JOIN: combine two tables · CASE: if-then logic inside a query · From a business question to an answer