So far you've read data; now you'll change it. The three data-modification statements — INSERT, UPDATE, DELETE — are simple but unforgiving: a missing WHERE can rewrite an entire table. This chapter covers them and, just as importantly, the habits that keep you safe.
INSERT
INSERT INTO students (name, email, package)VALUES ('Aanya', 'aanya@example.com', 6.5);-- Several rows at onceINSERT INTO students (name, package) VALUES('Rohan', 8.0), ('Priya', 7.25);-- Insert the result of a queryINSERT INTO archive (id, name)SELECT id, name FROM students WHERE graduated;
UPDATE
UPDATE studentsSET package = package * 1.1WHERE programme = 'Data'; -- 10% raise for one programme-- Update several columns at onceUPDATE students SET placed = true, package = 9.0 WHERE id = 42;
DELETE
DELETE FROM students WHERE enrolled IS NULL;DELETE FROM sessions WHERE created_at < CURRENT_DATE - INTERVAL '90 days';
Upsert
"Insert, or update if it already exists" is common enough to have dedicated syntax:
-- Postgres / SQLiteINSERT INTO settings (user_id, theme)VALUES (1, 'dark')ON CONFLICT (user_id) DO UPDATE SET theme = EXCLUDED.theme;-- MySQL: INSERT … ON DUPLICATE KEY UPDATE theme = VALUES(theme);
Safety habits
- Write the
WHEREbefore theSET/DELETE, and test it as aSELECTfirst. - Wrap risky multi-statement changes in a transaction (next chapters) so you can
ROLLBACK. - Use
RETURNING(Postgres) to see what changed:UPDATE … RETURNING id, package;. - Have a backup before bulk changes on production data.
Practice
Insert three students (single and multi-row). Give one programme a raise with a scoped UPDATE — after previewing the rows with a SELECT. Delete rows older than 90 days, and write an upsert for a settings row.
Key takeaways
- 01INSERT adds rows (single, multi-row, or from a SELECT).
- 02UPDATE … SET … WHERE changes columns; DELETE … WHERE removes rows.
- 03A missing WHERE on UPDATE/DELETE hits every row — the costliest SQL mistake.
- 04Preview changes as a SELECT first, and use RETURNING/transactions for safety.
- 05Upsert (ON CONFLICT / ON DUPLICATE KEY) inserts or updates in one statement.
