INSERT, UPDATE and DELETE
So far you've only read data. Now let's change it. These commands are powerful, and in production a careless UPDATE or DELETE can wipe out real data, so we'll also cover the habits pros use to stay safe.
INSERT: adding rows
Always list the column names. It protects you if columns are added or reordered later.
Insert several rows at once
We left out id. Because it's an INTEGER PRIMARY KEY, SQLite generates it automatically. (PostgreSQL uses SERIAL or GENERATED ... AS IDENTITY; MySQL uses AUTO_INCREMENT.)
UPDATE: changing rows
⚠️ The most famous SQL mistake: forgetting
WHERE.UPDATE products SET price = 0;sets every product to 0. Always write theWHEREclause first.
DELETE: removing rows
DELETE FROM orders; without WHERE empties the whole table.
Safe habits pros use
- SELECT first. Run the
WHEREas aSELECTto see exactly which rows you'll touch, then change the command toUPDATE/DELETE. - Use transactions so you can undo:
- Soft deletes: many apps never truly delete. They set a
deleted_attimestamp column and filter it out instead. - Back up before bulk changes in production.
Upsert: insert or update
"Insert this row, or update it if it already exists" is so common that most databases support it:
(PostgreSQL and SQLite use ON CONFLICT. MySQL uses ON DUPLICATE KEY UPDATE.)
Practice
- Add yourself as a new customer.
- Restock every product with
stock = 0tostock = 25. - Delete orders with
quantitygreater than 5.
1.What happens with DELETE FROM orders;?
2.What does ROLLBACK do?