NO. 12 · 7 exercises

12. Modifying Data

INSERT, UPDATE, DELETE — safely, in your own sandbox.

The lesson

Modifying Data

Every query so far has been a question: SELECT reads and returns, and the tables stay exactly as they were. This chapter turns the tables around — literally. INSERT, UPDATE and DELETE are how the store actually runs: new genres get added, prices get raised, walls get cleaned.

One thing before the first statement, because it changes everything: on SQLazo the database is rebuilt from scratch before every exercise. Whatever you do — delete a table's contents, raise every price, insert a genre with a wrong id — the next run starts from the exact same pristine store. You cannot break anything, and your solution is naturally idempotent: it doesn't matter how many times it runs, because each run starts clean. Experiment fearlessly.

In a real production database there is no reset. There, a careless DELETE is permanent. That's the one habit this chapter asks you to build: always write WHERE before you write UPDATE or DELETE.

INSERT: one new row

The store is expanding into reggaeton. One statement, one row:

INSERT INTO genres (id, name) VALUES (9, 'Reggaeton');

The shape: table, column list, then VALUES with one parenthesized value per column. Column order is yours to choose — (name, id) with swapped values works too. Omit the column list and you must supply every column, in table order, which breaks the moment someone adds a column.

Types follow the rules you already know: text in quotes, numbers bare, NULL explicit.

INSERT: several rows at once

Two new signings:

INSERT INTO artists (id, name, country, formed_year) VALUES
  (13, 'Los Fuegos', 'Mexico', 2016),
  (14, 'Sonia Vale', 'Portugal', 2019);

One statement, several value lists, all inserted together.

INSERT ... SELECT: a query as the source

Some inserts don't carry their data at all — they borrow it. The manager wants every 2023 wall title also on the 2024 display:

INSERT INTO featured_2024 (title)
SELECT title FROM featured_2023;

The SELECT runs, and every row it returns becomes an inserted row. The column list still matters: featured_2024 keeps its own ids, so only title is inserted and the ids are assigned automatically. SELECT COUNT(*) FROM featured_2024; now says 20 — the original ten plus the ten copies.

This is the workhorse for filling tables from other tables, and it composes with everything you know: that SELECT can group, join, filter and sort.

UPDATE: change existing rows

"Golden Hour" keeps selling out:

UPDATE tracks SET unit_price = 1.49 WHERE id = 1;

SET names the columns and their new values; WHERE picks the rows. Together: for the track whose id is 1, set the price to 1.49.

Here is the whole danger of UPDATE in one sentence: without WHERE, every row is a candidate. UPDATE tracks SET unit_price = 1.49; would re-price all 49 tracks. When you write an UPDATE in the real world, write the WHERE first and the SET second — that way the guard is on the page before the gun fires.

UPDATE with computed values

SET accepts any expression, not just literals. The label wants every Electronic track 10% more expensive:

UPDATE tracks
SET unit_price = ROUND(unit_price * 1.1, 2)
WHERE genre_id = 5;

The new price is computed from the old one, track by track, and ROUND to two decimals keeps the money clean (1.29 becomes 1.42, 0.99 becomes 1.09). And when the pricing policy is tiered, CASE from chapter 8 steps in — Rock tracks get a raise by bracket:

UPDATE tracks
SET unit_price = CASE WHEN unit_price = 0.99 THEN 1.09
                      WHEN unit_price = 1.29 THEN 1.39
                      ELSE unit_price END
WHERE genre_id = 1;

One UPDATE, and each row picks its own new price.

DELETE: remove rows

DELETE is the simplest statement in SQL — and the most dangerous, because it removes entire rows and you don't list any columns:

DELETE FROM tracks WHERE album_id = 10;

The two live tracks of the Crossroads album are gone. A DELETE without WHERE empties the table. No confirmation, no undo — in a real database that's how a career ends. On SQLazo, it's how a fresh run begins.

The WHERE can be as sophisticated as any select — subqueries work. The 2023 wall should keep only titles that also made it to 2024:

DELETE FROM featured_2023
WHERE title NOT IN (SELECT title FROM featured_2024);

Six rows go, four stay. The chapter-10 subquery is right at home in the chapter-12 delete.

The boss recipe: several statements, one arrival

Real work rarely fits in one statement. Marina Sol's new album arrives, and cataloguing it takes two:

INSERT INTO albums (id, title, artist_id, release_year)
VALUES (18, 'Costa Norte', 2, 2025);

INSERT INTO tracks (id, title, album_id, genre_id, duration_sec, unit_price) VALUES
  (50, 'Amanecer', 18, 3, 224, 0.99),
  (51, 'Marea Alta', 18, 3, 258, 1.29);

Album first — the tracks reference it — then the tracks. And the database can be checked like any state:

SELECT a.title, COUNT(t.id)
FROM albums a LEFT JOIN tracks t ON t.album_id = a.id
WHERE a.id = 18
GROUP BY a.title;

Real systems wrap multi-statement work in transactions — all-or-nothing bundles — which is a story for another course. Here, keep the three-statement rhythm in mind: insert, update, delete, then select to verify.

What you just learned

  • INSERT ... VALUES adds rows, one at a time or several at once.
  • INSERT ... SELECT fills a table from any query.
  • UPDATE ... SET ... WHERE changes chosen rows; without WHERE it changes everything.
  • SET accepts expressions — arithmetic and CASE — computed from the current values.
  • DELETE FROM ... WHERE removes whole rows, and a subquery in WHERE is fair game.
  • On SQLazo every run starts from a pristine database: experiment freely, and your solution is naturally repeatable. In the real world, WHERE is your seatbelt.

Dialect note. SQLite assigns ids automatically when you omit the id column of an INTEGER PRIMARY KEY; PostgreSQL calls the same mechanism SERIAL (or IDENTITY) and MySQL AUTO_INCREMENT. Upsert syntax differs everywhere (INSERT ... ON CONFLICT in SQLite and PostgreSQL, ON DUPLICATE KEY UPDATE in MySQL), and PostgreSQL's UPDATE ... RETURNING has no SQLite equivalent. The four statements in this chapter are otherwise identical in every database.

The boss exercise makes you the cataloguer for one new album: insert it, insert its tracks, and prove it with a select. On SQLazo you can always press run again.