Skip to main content
Albero Academy

INSERT, UPDATE & DELETE

Change data safely — insert rows, update and delete with a WHERE, upsert on conflict, and the habits that prevent disasters.

Chapter 13SQL14 min readBeginner friendly
  • #SQL
  • #DML
  • #INSERT

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

adding rows
INSERT INTO students (name, email, package)
VALUES ('Aanya', 'aanya@example.com', 6.5);
-- Several rows at once
INSERT INTO students (name, package) VALUES
('Rohan', 8.0), ('Priya', 7.25);
-- Insert the result of a query
INSERT INTO archive (id, name)
SELECT id, name FROM students WHERE graduated;

UPDATE

changing rows
UPDATE students
SET package = package * 1.1
WHERE programme = 'Data'; -- 10% raise for one programme
-- Update several columns at once
UPDATE students SET placed = true, package = 9.0 WHERE id = 42;

DELETE

removing rows
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:

insert or update
-- Postgres / SQLite
INSERT 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 WHERE before the SET/DELETE, and test it as a SELECT first.
  • 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

  1. 01INSERT adds rows (single, multi-row, or from a SELECT).
  2. 02UPDATE … SET … WHERE changes columns; DELETE … WHERE removes rows.
  3. 03A missing WHERE on UPDATE/DELETE hits every row — the costliest SQL mistake.
  4. 04Preview changes as a SELECT first, and use RETURNING/transactions for safety.
  5. 05Upsert (ON CONFLICT / ON DUPLICATE KEY) inserts or updates in one statement.