Sikau

Databases and SQL · Day 7 · about 30 min

Changing data

INSERT, UPDATE, DELETE and RETURNING.

Write carefully

Reading data can't hurt. Changing it can: an UPDATE without WHERE changes *every* row. Learn the three commands — and the habit of checking what you'll change before you change it.

INSERT, UPDATE, DELETE

INSERT INTO dishes (name, category, price, veg)
VALUES ('Yomari', 'Snack', 90, true), ('Chatamari', 'Snack', 150, false)
RETURNING id, name;

UPDATE dishes SET price = price + 10 WHERE category = 'Drink' RETURNING name, price;

SELECT name FROM dishes WHERE price > 400;
DELETE FROM dishes WHERE price > 400 AND name <> 'Thakali set' RETURNING name;

SELECT count(*) FROM dishes;
  • Deleting rows that others reference (foreign keys) fails — next lesson.
  • "Upsert": INSERT … ON CONFLICT (name) DO UPDATE SET price = excluded.price (PostgreSQL course).

The rest of this lesson

  • Preview before you changeexplain
  • Soft deletesexplain
  • How many rows change?predict
  • The missing WHEREpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 17 lessons of Databases and SQL