Loading

T11 SQL · Lesson 6

Creating, updating and deleting

Write in the ledger: add rows with INSERT and see them with RETURNING, change them with UPDATE, remove them with DELETE, let the table refuse bad rows with NOT NULL, UNIQUE, DEFAULT and CHECK, and change the table itself with ALTER TABLE and DROP TABLE.

  • add one row or several with INSERT, and see what was added with RETURNING
  • make a table refuse bad rows with NOT NULL, UNIQUE, DEFAULT, CHECK and its primary key
  • change rows with UPDATE ... SET ... WHERE, and say what happens without the WHERE
  • remove rows with DELETE, checking the WHERE with a SELECT first
  • change a table with ALTER TABLE, and remove it with DROP TABLE
  • read SQLite's constraint errors and fix what they point at
About 75 minutesChecked against SQLite's command-line shell, sqlite3, the "sqlite-tools-linux-x64-3540100.zip" of sqlite.org (the kit compares every SQL block with it, in its sandbox; the page runs the small sqlite3 of plan 34) 3.54.1 (2026-11-21); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-21)Play this lesson's games

The back cover

Reading a ledger never hurts it. Writing in one is different: a wrong line stays wrong until someone notices, and a line struck out may be gone for good. Every app that saves anything, a sign-up, a new photo, a deleted message, is writing in a table.

These pages write with care. They add rows with INSERT and see what was stored with RETURNING, change rows with UPDATE and remove them with DELETE, always checking the WHERE first. They give a table rules that refuse impossible rows, and they change the table itself with ALTER TABLE, or remove it with DROP TABLE.

Before you start

The story: Ink on the page

Until now the clerks have only read the ledger. Today the works sends changes. The compass has found its place in the Archive. The chimney has been read at last: 91.5. The pendulum's old reading is wrong and must be put right, and a broken gauge, the valve, is to be struck out.

A clerk reaches for the ink and stops. Last winter someone wrote a reading of minus forty on a boiler, and a gauge with no name at all, and two lines for the same fan; nobody noticed for a month.

Registrar Nadia Folio sets out new rules at the top of each page. "Ask the ledger, not your memory," she says. "And let the ledger refuse what cannot be true. Every change names the lines it touches, and nothing is struck out without a WHERE."

Five lessons have only read the ledger. Every SELECT left the tables exactly as it found them. This lesson writes in them, and that changes the stakes: a wrong SELECT shows a wrong answer, but a wrong UPDATE leaves wrong data behind, and SQL has no undo button.

It adds rows with INSERT, changes them with UPDATE and removes them with DELETE. It lets the table refuse rows that cannot be true, with rules called constraints. And it changes the table itself, its columns and its name, with ALTER TABLE, or removes it whole with DROP TABLE.

The ledger holds lesson 05's two tables and the same rows, but the gauges' CREATE TABLE now carries the Registrar's rules. The dot-command .schema shows how a table was made:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

.schema gauges
SELECT * FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

CREATE TABLE gauges (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  hall_id INTEGER REFERENCES halls(id),
  unit TEXT NOT NULL DEFAULT 'C',
  reading REAL CHECK (reading >= 0)
);
╭────┬──────────┬─────────┬──────┬─────────╮
│ id │   name   │ hall_id │ unit │ reading │
╞════╪══════════╪═════════╪══════╪═════════╡
│  1 │ boiler   │       1 │ C    │    96.5 │
│  2 │ pump     │       1 │ bar  │     4.2 │
│  3 │ fan      │       1 │ rpm  │  1200.0 │
│  4 │ chimney  │       3 │ C    │ NULL    │
│  5 │ pendulum │       2 │ s    │     2.0 │
│  6 │ kettle   │       3 │ C    │    88.0 │
│  7 │ bell     │       2 │ Hz   │   440.0 │
│  8 │ valve    │       1 │ bar  │     4.2 │
│  9 │ compass  │ NULL    │ deg  │   270.0 │
╰────┴──────────┴─────────┴──────┴─────────╯

Read the new words in the CREATE TABLE: NOT NULL, UNIQUE, DEFAULT and CHECK. Each is a rule the table will enforce from now on, and the constraints section explains them one by one. Every block of this lesson starts from this same ledger, so the changes one block makes never reach the next: change things freely.

This lesson builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
CREATE TABLE with a type for each column.reading REALRules after the types.
INSERT adds a row.INSERT INTO gauges (name) VALUES ('fan');Its other forms.
WHERE chooses rows.WHERE name = 'valve'Which rows UPDATE and DELETE touch.
NULL is found with IS NULL, never = NULL.WHERE hall_id IS NULLDeleting the rows with no hall.
The id is the primary key.id INTEGER PRIMARY KEYSQLite numbers new rows.
hall_id points at halls.id.REFERENCES halls(id)Deleting a hall others point at.
PRAGMA foreign_keys = ON checks the links.lesson 05A DELETE refused.
COUNT(*) counts rows.SELECT COUNT(*) FROM gauges;Checking what a DELETE removed.
Adding, changing and removing in JavaScript.list.push(x); obj.unit = 's';INSERT, UPDATE, DELETE.
An undo button in an editor.Ctrl+ZSQL has none: check before you change.

By the end of this lesson you will be able to:

  • add one row or several with INSERT, and see what was added with RETURNING;
  • make a table refuse bad rows with NOT NULL, UNIQUE, DEFAULT, CHECK and its primary key;
  • change rows with UPDATE ... SET ... WHERE, and say what happens without the WHERE;
  • remove rows with DELETE, checking the WHERE with a SELECT first;
  • change a table with ALTER TABLE, and remove it with DROP TABLE;
  • read SQLite's constraint errors and fix what they point at.

How to follow this lesson

As before, each block is a file of SQL and the command sqlite3 ledger.db < query.sql. A block that changes the ledger usually ends with a SELECT, or uses RETURNING, so that you can see the change it made.

Every block was also run with the real sqlite3 3.54.1 in a real terminal, and printed exactly what you see.

In one line

INSERT adds rows, UPDATE changes them, DELETE removes them, constraints refuse rows that cannot be true, and ALTER TABLE and DROP TABLE change the table itself.

Adding rows: INSERT

At a glance

INSERT adds rows to a table: one, or several in one statement. It is the first of the three statements that change a table's rows.

Name the columns being filled, in brackets, then give VALUES in the same order. A column left out gets its default, or NULL if it has none, and SQLite chooses the id itself. Several rows go in one INSERT, each in its own brackets. RETURNING, at the end, shows the rows just added, so there is no need for a separate SELECT to find them again.

Take a guess: Is the word AUTOINCREMENT needed to make SQLite number new rows by itself?

Lesson 01 met INSERT. Here it is again, in the form to use every time: the table, a list of columns in brackets, and VALUES with one value for each column, in the same order. A lamp arrives for the Archive, hall 4:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('lamp', 4, 'lux', 300);
SELECT * FROM gauges WHERE name = 'lamp';

Terminal: sqlite3 ledger.db < query.sql

╭────┬──────┬─────────┬──────┬─────────╮
│ id │ name │ hall_id │ unit │ reading │
╞════╪══════╪═════════╪══════╪═════════╡
│ 10 │ lamp │       4 │ lux  │   300.0 │
╰────┴──────┴─────────┴──────┴─────────╯

Read it aloud: "insert into gauges, giving name, hall_id, unit and reading, the values lamp, 4, lux and 300." The INSERT itself printed nothing; the SELECT after it shows the new row. Notice the id: nobody gave one, and SQLite chose 10, one more than the largest id so far. That is what INTEGER PRIMARY KEY does for a column left out.

Several rows at once

One INSERT can add many rows: put each row's values in its own brackets, with commas between them.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('lamp', 4, 'lux', 300), ('clock', 4, 's', 60);
SELECT id, name, hall_id FROM gauges WHERE hall_id = 4;

Terminal: sqlite3 ledger.db < query.sql

╭────┬───────┬─────────╮
│ id │ name  │ hall_id │
╞════╪═══════╪═════════╡
│ 10 │ lamp  │       4 │
│ 11 │ clock │       4 │
╰────┴───────┴─────────╯

The lamp got 10 and the clock 11, in the order they were written. The Archive, empty in lesson 05, now holds two gauges.

Columns left out

A column missing from the list gets its default value. Most columns have none, so they get NULL; but this ledger's unit column was made with DEFAULT 'C'. A stove arrives for the Couriers' Yard, with no unit and no reading given:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id) VALUES ('stove', 3);
SELECT * FROM gauges WHERE name = 'stove';

Terminal: sqlite3 ledger.db < query.sql

╭────┬───────┬─────────┬──────┬─────────╮
│ id │ name  │ hall_id │ unit │ reading │
╞════╪═══════╪═════════╪══════╪═════════╡
│ 10 │ stove │       3 │ C    │ NULL    │
╰────┴───────┴─────────┴──────┴─────────╯

The unit became C, from the default, and the reading NULL, the default of a column with none.

Seeing what was added: RETURNING

A SELECT afterwards works, but it has to find the row again. RETURNING, at the end of the INSERT, hands back the new row's columns at once, the chosen id among them:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('lamp', 4, 'lux', 300) RETURNING id, name;

Terminal: sqlite3 ledger.db < query.sql

╭────┬──────╮
│ id │ name │
╞════╪══════╡
│ 10 │ lamp │
╰────┴──────╯

RETURNING works the same way at the end of UPDATE and DELETE, and those sections use it to show exactly which rows changed.

PartWhat it gives
INSERT INTO gaugesthe table that gets the row
(name, hall_id, unit, reading)the columns being filled, in this order
VALUES ('lamp', 4, 'lux', 300)one value per column, in the same order
, ('clock', 4, 's', 60)another row, in the same INSERT
RETURNING id, namethe new rows' columns, shown at once

Worked example 1

A barometer reading 1013 hPa arrives for the Archive. Add it, and show the id it was given.

What we have: The Archive is hall 4; the gauge's name, unit and reading are given; SQLite chooses the id.

What we need: One new row, and its id on the screen.

The plan: INSERT with a column list for the four values, and RETURNING id, name, hall_id to see the result.

  1. The columns: (name, hall_id, unit, reading); the id is left to SQLite.
  2. The values, in the same order: ('barometer', 4, 'hPa', 1013).
  3. See the row: RETURNING id, name, hall_id.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('barometer', 4, 'hPa', 1013) RETURNING id, name, hall_id;

Terminal: sqlite3 ledger.db < query.sql

╭────┬───────────┬─────────╮
│ id │   name    │ hall_id │
╞════╪═══════════╪═════════╡
│ 10 │ barometer │       4 │
╰────┴───────────┴─────────╯

The barometer was added with id 10, in hall 4.

Check: The largest id before was the compass's 9, so 10 is the next. A SELECT COUNT(*) now gives 10 rows.

A path that fails: Leaving out the column list, as in INSERT INTO gauges VALUES ('barometer', 4, 'hPa', 1013);. Without a list, SQLite wants a value for every column, the id included, and stops: table gauges has 5 columns but 4 values were supplied.

When you are stuck: INSERT

If SQLite counts columns and values, compare your column list with your values, one by one: they must match in number and order.

If a row seems missing after an INSERT, add RETURNING, or a SELECT, to see exactly what was stored.

A common mistake

Writing the values in a different order from the column list. SQLite does not guess: it puts the first value in the first column named, whatever it looks like.

Your turn

Write an INSERT that adds a gauge called gong to the Clock Tower (hall 2), measured in Hz, reading 220.Tap to reveal
  1. Name the four columns, then the four values in the same order.

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('gong', 2, 'Hz', 220);

After INSERT INTO gauges (name) VALUES ('spare');, what are the spare's unit and reading?Tap to reveal
  1. One column has a default; the other has none.

The unit is C, from DEFAULT 'C'; the reading is NULL.

What does RETURNING add to an INSERT?Tap to reveal
  1. Think of the new id.

It shows the columns of the rows just added, such as the id SQLite chose, without a separate SELECT.

Did you know?

AUTOINCREMENT is usually not needed

Many tutorials add the word AUTOINCREMENT to an id column. SQLite's own documentation advises against it: the keyword imposes extra CPU, memory, disk space and disk I/O overhead and should be avoided if not strictly needed, and it is usually not needed. A plain INTEGER PRIMARY KEY already numbers new rows by itself, as this lesson's lamp showed.

Why it fits here: It saves a common habit from this topic's INSERT: the id fills itself without AUTOINCREMENT.

Source: SQLite: Autoincrement

RETURNING arrived in 2021

RETURNING is newer than most of SQLite. Its list of changes adds support for the RETURNING clause on DELETE, INSERT and UPDATE statements in version 3.35.0, released on 2021-03-12. Its documentation says the clause makes the statement return one result row for each row deleted, inserted or updated.

Why it fits here: It dates this topic's RETURNING, which older tutorials do not show.

Sources: SQLite: Release History; SQLite: The RETURNING Clause

In one line

INSERT INTO table (columns) VALUES (values) adds a row, or several with more brackets; columns left out get their default or NULL, the id is chosen by SQLite, and RETURNING shows what was added.

Rules the table enforces: constraints

At a glance

Constraints are rules written into CREATE TABLE, and the table checks every new or changed row against them.

NOT NULL refuses a row with no value in that column. UNIQUE refuses a second row with the same value, and the primary key is unique too. CHECK runs a test on every row and refuses it when the test is false, but lets a NULL through. DEFAULT refuses nothing: it fills a missing value. A refused row is not stored at all, and the error names the rule and the column.

Take a guess: Can the primary key column of an SQLite table ever hold a NULL?

The opening scene's clerk remembered a reading of minus forty, a gauge with no name, and two lines for the same fan. A constraint is a rule written into CREATE TABLE that stops such rows at the door: the table checks every INSERT and UPDATE against its rules, and refuses a row that breaks one. The ledger's gauges have four kinds. Here each one is tried.

NOT NULL: a value must be given

name TEXT NOT NULL means a gauge cannot be stored without a name. Leave it out:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (hall_id, unit) VALUES (2, 's');

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: NOT NULL constraint failed: gauges.name

Read the message from the end: the column, gauges.name; the rule, NOT NULL; and the verdict, failed. Nothing was stored. The message says "Error", not "Parse error": the SQL was well written, and the problem was found while it ran.

UNIQUE: no two rows alike

UNIQUE on name means no two gauges may share one. Try a second fan:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, unit) VALUES ('fan', 'rpm');

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: UNIQUE constraint failed: gauges.name

The primary key is unique by its nature, so an id that is already taken is refused the same way:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (id, name) VALUES (1, 'stove');

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: UNIQUE constraint failed: gauges.id

The boiler already has id 1. This is one more reason to leave the id out and let SQLite choose it.

CHECK: a test every row must pass

CHECK (reading >= 0) is a test SQLite runs on every new or changed row. A reading of minus forty fails it:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, reading) VALUES ('icebox', -40);

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: CHECK constraint failed: reading >= 0

The message even quotes the test that failed. But a CHECK refuses a row only when its test is false, and lesson 02's rule returns: NULL >= 0 is not known, which is not false. So a missing reading passes:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, reading) VALUES ('icebox', NULL);
SELECT name, unit, reading FROM gauges WHERE name = 'icebox';

Terminal: sqlite3 ledger.db < query.sql

╭────────┬──────┬─────────╮
│  name  │ unit │ reading │
╞════════╪══════╪═════════╡
│ icebox │ C    │ NULL    │
╰────────┴──────┴─────────╯

That is how the chimney, unread, lives in a table that forbids readings below zero. To forbid NULL too, a column needs NOT NULL as well as its CHECK.

DEFAULT: a value when none is given

DEFAULT 'C' does not refuse anything; it fills a gap. The INSERT section's stove got unit C from it, and so did the icebox above.

RuleIn CREATE TABLERefusesThe message names
NOT NULLname TEXT NOT NULLa row with no value thereNOT NULL constraint failed: gauges.name
UNIQUEname TEXT UNIQUEa second row with the same valueUNIQUE constraint failed: gauges.name
PRIMARY KEYid INTEGER PRIMARY KEYan id already takenUNIQUE constraint failed: gauges.id
CHECKCHECK (reading >= 0)a row whose test is false (NULL passes)CHECK constraint failed: reading >= 0
DEFAULTunit TEXT DEFAULT 'C'nothing: it fills a missing valueno message

Worked example 2

A second bell, reading 512 Hz, arrives for the Archive. Add it.

What we have: The gauges' names must be unique, and the Clock Tower already has a bell.

What we need: The new bell stored, under a name the ledger accepts.

The plan: Try the obvious INSERT, read the error, and choose a name that is not taken.

  1. The first try: INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('bell', 4, 'Hz', 512);

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('bell', 4, 'Hz', 512);

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: UNIQUE constraint failed: gauges.name
  1. The message names the rule and the column: UNIQUE, gauges.name. A different name is needed, such as hand bell.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('hand bell', 4, 'Hz', 512) RETURNING id, name;

Terminal: sqlite3 ledger.db < query.sql

╭────┬───────────╮
│ id │   name    │
╞════╪═══════════╡
│ 10 │ hand bell │
╰────┴───────────╯

The hand bell is stored with id 10.

Check: The refusal is the rule doing its job: a second row called bell would make every query about the bell ambiguous.

A path that fails: Removing UNIQUE from the table to let the second bell in. The rule exists to keep names telling gauges apart; change the data, not the rule.

When you are stuck: constraint errors

Read the message from the end: the last part names the column (gauges.name), the middle names the rule (NOT NULL, UNIQUE, CHECK).

If a CHECK seems to let a bad row through, look for NULL: a CHECK passes when its test is not known.

A common mistake

Thinking a refused INSERT stored part of its row. A row that breaks a rule is not stored at all, and the table is just as it was.

Your turn

Which rule refuses INSERT INTO gauges (name, reading) VALUES ('frost', -2);?Tap to reveal
  1. Look at the reading column's rule.

The CHECK: reading >= 0 is false for −2, so SQLite reports CHECK constraint failed: reading >= 0.

Why does INSERT INTO gauges (name) VALUES ('spare'); succeed though no reading is given?Tap to reveal
  1. Which rules does the reading column have?

The reading has only a CHECK, and a missing reading is NULL, which a CHECK lets through.

What does the message UNIQUE constraint failed: gauges.id mean?Tap to reveal
  1. Which rule makes ids unique?

The id given is already taken: the primary key is unique, so leave the id out and let SQLite choose.

Did you know?

A NULL passes a CHECK

SQLite's documentation spells out the CHECK rule. The test's result is turned into a number: if it is zero, the row breaks the rule; if it is NULL, or any other non-zero value, it does not. CHECK rules are also verified only when the table is written, never when it is read, so rows stored before a rule existed are not checked again.

Why it fits here: It explains this topic's icebox and chimney: a test on NULL is not zero, so the CHECK lets them through.

Source: SQLite: CREATE TABLE

A primary key that allows NULL

By the SQL standard, a primary key is never NULL. SQLite's documentation admits that, due to a bug in some early versions, this is not the case in SQLite: most primary key columns accept NULL, unless the column is an INTEGER PRIMARY KEY or declared NOT NULL. It could be fixed, but doing so might break legacy applications, so the quirk is documented instead.

Why it fits here: It answers the topic's question, and shows why this lesson's id is an INTEGER PRIMARY KEY.

Source: SQLite: CREATE TABLE

In one line

Constraints are rules in CREATE TABLE that refuse bad rows: NOT NULL needs a value, UNIQUE and the primary key forbid repeats, CHECK needs its test not to be false, and DEFAULT fills a missing value.

Changing rows: UPDATE

At a glance

UPDATE changes values in rows that are already there: the table, SET with the new values, and WHERE to choose the rows.

Several columns change at once, separated by commas, never by AND. A new value can be worked out from the old one, such as reading + 0.5. RETURNING shows each changed row as it now is. An UPDATE with no WHERE changes every row of the table, with no question asked, so the safe habit is to run the WHERE in a SELECT first and only then turn it into the UPDATE.

Take a guess: Can an UPDATE take its new values from another table, the way a join reads two tables?

UPDATE changes values in rows that are already there. It names the table, then SET with the new values, then WHERE to choose the rows. The opening scene's first change: the compass has found its place in the Archive, hall 4.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

UPDATE gauges SET hall_id = 4 WHERE name = 'compass';
SELECT name, hall_id FROM gauges WHERE name = 'compass';

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬─────────╮
│  name   │ hall_id │
╞═════════╪═════════╡
│ compass │       4 │
╰─────────┴─────────╯

Read it aloud: "update gauges, setting hall_id to 4, where the name is compass." Only the compass's row changed, because only the compass passed the WHERE. RETURNING works here too, and shows each changed row as it is now. The chimney has been read at last:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

UPDATE gauges SET reading = 91.5 WHERE name = 'chimney' RETURNING name, reading;

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬─────────╮
│  name   │ reading │
╞═════════╪═════════╡
│ chimney │    91.5 │
╰─────────┴─────────╯

New values from old ones

SET can work out a value from the row itself. Suppose the Clock Tower's gauges were all read half a unit too low; add 0.5 to each:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

UPDATE gauges SET reading = reading + 0.5 WHERE hall_id = 2;
SELECT name, reading FROM gauges WHERE hall_id = 2;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ pendulum │     2.5 │
│ bell     │   440.5 │
╰──────────┴─────────╯

For each row that passed the WHERE, SQLite read its old reading, added 0.5, and stored the result: 2.0 became 2.5, and 440.0 became 440.5. One statement changed two rows.

UPDATE without WHERE

Here is the most dangerous line in this lesson. An UPDATE with no WHERE changes every row of the table. The dot-command .changes on makes the shell report how many rows each statement changed:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

.changes on
UPDATE gauges SET reading = 0;

Terminal: sqlite3 ledger.db < query.sql

changes: 9   total_changes: 9

Nine rows: every gauge now reads 0, and the real readings are gone. SQLite did not ask "are you sure?", and there is no undo. That is why careful people write the WHERE first, and check it with a SELECT before they turn it into an UPDATE, as the worked examples below do.

PartWhat it does
UPDATE gaugesthe table whose rows change
SET reading = 91.5the new value; several are separated by commas
SET reading = reading + 0.5a new value worked out from the old one
WHERE name = 'chimney'which rows change; without it, all of them
RETURNING name, readingthe changed rows, as they are now

Worked example 3

The pendulum's record is wrong twice over: its reading should be 2.1, and its unit s. Fix both in one statement.

What we have: The pendulum's row; two columns to change.

What we need: The pendulum showing reading 2.1 and unit s.

The plan: One UPDATE, with both new values in SET separated by a comma, and RETURNING to see the row.

  1. The row: WHERE name = 'pendulum'.
  2. Both values, with a comma between them: SET reading = 2.1, unit = 's'.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

UPDATE gauges SET reading = 2.1, unit = 's' WHERE name = 'pendulum' RETURNING name, unit, reading;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬──────┬─────────╮
│   name   │ unit │ reading │
╞══════════╪══════╪═════════╡
│ pendulum │ s    │     2.1 │
╰──────────┴──────┴─────────╯

The pendulum now reads 2.1, in s.

Check: RETURNING shows the row after the change, so the check is on the screen: both columns hold what was asked.

A path that fails: Joining the two values with AND, as in SET reading = 2.1 AND unit = 's'. SQL reads that as one value, the test 2.1 AND unit = 's', which is true, so the reading becomes 1.0 and the unit is not set at all. No error is reported.

Worked example 4

The Clock Tower's gauges were read half a unit too low. Correct them, and check the rows before changing them.

What we have: The Clock Tower is hall 2; its gauges are the pendulum and the bell.

What we need: Each of its readings raised by 0.5, and no other row touched.

The plan: Write the WHERE first and run it in a SELECT; then use the very same WHERE in the UPDATE, with .changes on to count the rows changed.

  1. Look first: SELECT name, reading FROM gauges WHERE hall_id = 2;

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

SELECT name, reading FROM gauges WHERE hall_id = 2;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ pendulum │     2.0 │
│ bell     │   440.0 │
╰──────────┴─────────╯
  1. Two rows, the right two. Now the same WHERE in the UPDATE:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

.changes on
UPDATE gauges SET reading = reading + 0.5 WHERE hall_id = 2;

Terminal: sqlite3 ledger.db < query.sql

changes: 2   total_changes: 2

Two rows changed: the pendulum and the bell, now 2.5 and 440.5.

Check: The SELECT found two rows and the UPDATE changed two: the counts agree, so the WHERE did what was meant.

A path that fails: Typing the UPDATE first and the WHERE last, from memory. One slip, such as hall_id = 1, changes the Engine Hall's four gauges instead, and nothing warns you.

When you are stuck: UPDATE

If an UPDATE seems to have done nothing, turn on .changes and run it again: changes: 0 means the WHERE matched no row, often from a capital letter or a NULL.

If an UPDATE changed too much, the WHERE was missing or too wide. Always try the WHERE in a SELECT first.

A common mistake

Writing AND between two values in SET. Values in SET are separated by commas; AND makes them one true or false value.

Your turn

Write an UPDATE that moves the fan to the Archive (hall 4).Tap to reveal
  1. SET the hall_id, WHERE the name.

UPDATE gauges SET hall_id = 4 WHERE name = 'fan';

How many rows does UPDATE gauges SET unit = 'C'; change in this ledger?Tap to reveal
  1. No WHERE.

All nine: with no WHERE, every row changes.

What does SET reading = reading * 2 do to a NULL reading?Tap to reveal
  1. NULL in arithmetic.

It stays NULL: anything worked out from NULL is NULL, as lesson 02 showed.

Did you know?

UPDATE FROM, borrowed from PostgreSQL

An UPDATE can take its new values from another table. SQLite's list of changes adds support for UPDATE FROM, following the PostgreSQL syntax, in version 3.33.0, released on 2020-08-14. With it, the gauges could take new readings from a table of fresh readings in one statement, matched row by row like a join.

Why it fits here: It answers the topic's question, and joins this lesson's UPDATE to lesson 05's joins.

Source: SQLite: Release History

The count is a function too

The .changes on of this topic has an SQL twin. SQLite's documentation says the changes() function returns the number of rows changed, inserted or deleted by the most recently completed INSERT, DELETE or UPDATE statement. So SELECT changes(); right after an UPDATE tells a program how many rows its WHERE really matched.

Why it fits here: It gives this topic's safety check a form that works inside any program, not only in the sqlite3 shell.

Source: SQLite: Built-In Scalar SQL Functions

In one line

UPDATE table SET column = value, more with commas, WHERE test changes the rows that pass the test; without WHERE it changes every row, so check the WHERE with a SELECT first.

Removing rows: DELETE

At a glance

DELETE removes whole rows: DELETE FROM a table, WHERE a test chooses them.

Without WHERE, every row goes and the empty table stays. RETURNING shows the rows as they go. A row that others point at can be deleted when foreign keys are not checked, leaving orphans whose keys point at nothing; with PRAGMA foreign_keys = ON, the DELETE is refused instead. The safe habit is the same as for UPDATE: run the WHERE in a SELECT first, then change SELECT * to DELETE.

Take a guess: When a row is deleted, is its content really wiped from the database file?

DELETE removes whole rows. It needs only the table and a WHERE: there are no columns to name, because the row goes entirely. The broken valve is to be struck out:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DELETE FROM gauges WHERE name = 'valve' RETURNING id, name;
SELECT COUNT(*) FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬───────╮
│ id │ name  │
╞════╪═══════╡
│  8 │ valve │
╰────┴───────╯
╭──────────╮
│ COUNT(*) │
╞══════════╡
│        8 │
╰──────────╯

RETURNING showed the row that went, the valve with id 8, and the count fell from nine to eight. The id 8 is not given to the next new gauge in its place: a new row still gets one more than the largest id.

DELETE without WHERE

Like UPDATE, a DELETE with no WHERE touches every row. It removes them all, and leaves the table standing, empty:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DELETE FROM gauges;
SELECT COUNT(*) FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│ COUNT(*) │
╞══════════╡
│        0 │
╰──────────╯

No question was asked and nothing can bring the rows back. Write DELETE FROM gauges WHERE as one piece, and finish the WHERE before anything else; better still, run SELECT * FROM gauges WHERE ... first, and only then change SELECT * to DELETE.

Deleting what others point at

Lesson 05's gauges point at halls by number. Delete a hall that gauges point at, and SQLite, which does not check REFERENCES by default, lets it go. The Engine Hall's four gauges are left pointing at nothing:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DELETE FROM halls WHERE name = 'Engine Hall';
SELECT g.name, h.name FROM gauges g LEFT JOIN halls h ON g.hall_id = h.id WHERE g.hall_id = 1;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬──────╮
│  name  │ name │
╞════════╪══════╡
│ boiler │ NULL │
│ pump   │ NULL │
│ fan    │ NULL │
│ valve  │ NULL │
╰────────┴──────╯

Their hall_id is still 1, but no hall 1 exists any more, so the LEFT JOIN finds NULL. Rows like these are called orphans. With the checks switched on, the same DELETE is refused, and the ledger stays whole:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

PRAGMA foreign_keys = ON;
DELETE FROM halls WHERE name = 'Engine Hall';

Terminal: sqlite3 ledger.db < query.sql

Error near line 2: FOREIGN KEY constraint failed

What a database should do instead, move the gauges, delete them too, or refuse, can be written into the REFERENCES itself. Those rules wait for the PostgreSQL track, T12.

You writeWhat goes
DELETE FROM gauges WHERE name = 'valve';the rows that pass the test
DELETE FROM gauges;every row; the table stays, empty
DROP TABLE gauges;the table itself, rows and all (the next section)
DELETE ... RETURNING id, namethe same rows, shown as they go

Worked example 5

Strike out every gauge that has no hall.

What we have: The compass is the only gauge whose hall_id is NULL.

What we need: The gauges with no hall removed, and their names shown.

The plan: DELETE with WHERE hall_id IS NULL, remembering lesson 02's NULL rule, and RETURNING name to see what went.

  1. The test for a missing value: WHERE hall_id IS NULL, never = NULL.
  2. Show the rows as they go: RETURNING name.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DELETE FROM gauges WHERE hall_id IS NULL RETURNING name;

Terminal: sqlite3 ledger.db < query.sql

╭─────────╮
│  name   │
╞═════════╡
│ compass │
╰─────────╯

The compass was removed, and nothing else.

Check: Only one row had a NULL hall_id, and RETURNING shows exactly one name.

A path that fails: Writing WHERE hall_id = NULL. A comparison with NULL is never true, so the DELETE removes nothing, and with .changes on the shell reports changes: 0 total_changes: 0.

When you are stuck: DELETE

Before any DELETE, run the same WHERE in a SELECT *, and read the rows it finds: those, and only those, will go.

If a DELETE of a hall is refused with FOREIGN KEY constraint failed, gauges still point at it. Move them or delete them first.

A common mistake

Expecting DELETE to empty a single column. DELETE removes whole rows; to clear one value, UPDATE it to NULL.

Your turn

Write a DELETE that removes the gauges measured in bar.Tap to reveal
  1. WHERE on the unit.

DELETE FROM gauges WHERE unit = 'bar'; removes the pump and the valve.

What is the difference between DELETE FROM gauges; and DROP TABLE gauges;?Tap to reveal
  1. Does the table survive?

DELETE removes every row but keeps the empty table; DROP TABLE removes the table itself.

Why did SQLite let the Engine Hall be deleted while gauges pointed at it?Tap to reveal
  1. Lesson 05's PRAGMA.

SQLite checks REFERENCES only after PRAGMA foreign_keys = ON; without it, the gauges were left as orphans.

Did you know?

Deleted, but not wiped

Deleting a row does not erase it from the file. SQLite's documentation says deleted content is usually not erased, but its space is marked as available for reuse, which can allow it to be recovered by a hacker or by forensic analysis. Running VACUUM cleans the database of all traces of deleted content, and PRAGMA secure_delete is another way.

Why it fits here: It answers the topic's question: a deleted row can linger in the file until VACUUM or secure_delete clears it.

Source: SQLite: VACUUM

The truncate shortcut

Emptying a whole table is fast in SQLite. Its documentation says that when a DELETE has no WHERE and no RETURNING, and the table has no triggers, it uses an optimization to erase the entire table content without visiting each row. This truncate optimization makes the delete run much faster, which is one more reason a missing WHERE can do its damage in an instant.

Why it fits here: It shows what this topic's DELETE without WHERE does inside: the whole table is cleared at once.

Source: SQLite: DELETE

In one line

DELETE FROM table WHERE test removes whole rows; without WHERE it empties the table, so check the WHERE with a SELECT first, and switch on foreign key checks so that rows others point at are not deleted.

Changing the table itself: ALTER and DROP

At a glance

ALTER TABLE changes a table's shape without losing its rows, and DROP TABLE removes a table altogether.

ADD COLUMN puts a new column at the end of every row; the rows already there get its default, so a NOT NULL column needs one. RENAME COLUMN and RENAME TO change names, and every query must then use the new ones. DROP COLUMN removes a column with its values. DROP TABLE removes the table with its rows and rules, and IF EXISTS keeps a missing table from being an error.

Take a guess: Which kinds of change can SQLite's ALTER TABLE make, and since when could it drop a column?

INSERT, UPDATE and DELETE change the rows. Sometimes the table's shape must change instead: a new column, a better name. ALTER TABLE does that, and DROP TABLE removes a table altogether.

Adding a column

The Registrar wants to record when each gauge was last checked. ADD COLUMN puts a new column at the end of every row:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

ALTER TABLE gauges ADD COLUMN checked_on TEXT;
SELECT name, checked_on FROM gauges LIMIT 2;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬────────────╮
│  name  │ checked_on │
╞════════╪════════════╡
│ boiler │ NULL       │
│ pump   │ NULL       │
╰────────┴────────────╯

The rows already in the table get the new column's default, here NULL, as nobody has checked anything yet. That raises a question: what if the new column must not be NULL?

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

ALTER TABLE gauges ADD COLUMN serial TEXT NOT NULL;

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: Cannot add a NOT NULL column with default value NULL

SQLite refuses, and the message gives the reason: the nine rows already there would each need a value, and the only one available is NULL. Give the column a DEFAULT, and the old rows take it: the worked example below does exactly that.

Renaming

RENAME COLUMN gives a column a new name, and every query must then use the new one:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

ALTER TABLE gauges RENAME COLUMN reading TO value;
SELECT name, value FROM gauges WHERE name = 'bell';

Terminal: sqlite3 ledger.db < query.sql

╭──────┬───────╮
│ name │ value │
╞══════╪═══════╡
│ bell │ 440.0 │
╰──────┴───────╯

RENAME TO renames the whole table. The dot-command .tables lists the tables of the database:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

ALTER TABLE halls RENAME TO rooms;
.tables

Terminal: sqlite3 ledger.db < query.sql

gauges     rooms

Dropping a column, or a whole table

DROP COLUMN removes a column and every value in it. Here the unit goes, and .schema shows the table's new shape:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

ALTER TABLE gauges DROP COLUMN unit;
.schema gauges

Terminal: sqlite3 ledger.db < query.sql

CREATE TABLE gauges (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  hall_id INTEGER REFERENCES halls(id),
  reading REAL CHECK (reading >= 0)
);

DROP TABLE removes a table, its rows and its rules, all at once. Afterwards, .tables lists only halls:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DROP TABLE gauges;
.tables

Terminal: sqlite3 ledger.db < query.sql

halls

Dropping a table that does not exist is an error, which stops a script that meant to tidy up. IF EXISTS turns it into a quiet no-op:

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DROP TABLE shifts;

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: no such table: shifts

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

DROP TABLE IF EXISTS shifts;
.tables

Terminal: sqlite3 ledger.db < query.sql

gauges     halls
You writeWhat changes
ALTER TABLE gauges ADD COLUMN checked_on TEXT;a new column, NULL in the old rows
... ADD COLUMN status TEXT NOT NULL DEFAULT 'working';a new required column; the old rows take the default
ALTER TABLE gauges RENAME COLUMN reading TO value;a column's name
ALTER TABLE halls RENAME TO rooms;the table's name
ALTER TABLE gauges DROP COLUMN unit;a column and all its values go
DROP TABLE IF EXISTS gauges;the whole table goes, with no error if it was not there

Worked example 6

Add a status column to the gauges, working for every gauge unless told otherwise, then mark the valve broken.

What we have: Every gauge works except the valve; the new column must never be empty.

What we need: A status column holding working for the Engine Hall's gauges, except broken for the valve.

The plan: ADD COLUMN with NOT NULL and DEFAULT 'working', so that the old rows take the default; then an UPDATE for the valve alone.

  1. The column, with its default: ALTER TABLE gauges ADD COLUMN status TEXT NOT NULL DEFAULT 'working';
  2. The one exception: UPDATE gauges SET status = 'broken' WHERE name = 'valve';
  3. A look at the Engine Hall: SELECT name, status FROM gauges WHERE hall_id = 1;

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

ALTER TABLE gauges ADD COLUMN status TEXT NOT NULL DEFAULT 'working';
UPDATE gauges SET status = 'broken' WHERE name = 'valve';
SELECT name, status FROM gauges WHERE hall_id = 1;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬─────────╮
│  name  │ status  │
╞════════╪═════════╡
│ boiler │ working │
│ pump   │ working │
│ fan    │ working │
│ valve  │ broken  │
╰────────┴─────────╯

Three gauges working and the valve broken.

Check: The default filled every old row, so only one UPDATE was needed. A column kept like this lets a broken gauge stay in the records, where a DELETE would have lost its history.

A path that fails: Adding the column as status TEXT NOT NULL with no DEFAULT. SQLite refuses: Cannot add a NOT NULL column with default value NULL.

When you are stuck: ALTER TABLE

If an ADD COLUMN with NOT NULL is refused, give it a DEFAULT: the rows already there need a value.

If a query fails after a rename, it still uses the old name: no such column or no such table points at it.

A common mistake

Dropping a table to empty it. DROP TABLE removes the table and its rules too; to keep the table and lose the rows, use DELETE FROM.

Your turn

Write the statement that adds a column note, of type TEXT, to the halls.Tap to reveal
  1. ALTER TABLE, then ADD COLUMN.

ALTER TABLE halls ADD COLUMN note TEXT;

After ALTER TABLE gauges RENAME COLUMN unit TO measure;, what does SELECT unit FROM gauges; report?Tap to reveal
  1. The old name is gone.

An error: no such column: unit. The column is now called measure.

Why use DROP TABLE IF EXISTS in a script?Tap to reveal
  1. What if the table was never made?

Without IF EXISTS, a missing table is an error that stops the script; with it, nothing happens and the script goes on.

Did you know?

Four changes, and only four

SQLite's documentation says it supports a limited subset of ALTER TABLE: a table can be renamed, and a column can be renamed, added or dropped. The reason is how it stores a table's shape: as the original text of the CREATE statement, which ALTER TABLE edits. Any other change, such as a new rule on an old column, means building a new table and copying the rows across.

Why it fits here: It explains the edges of this topic's ALTER TABLE: four changes, made by editing the stored CREATE text.

Source: SQLite: ALTER TABLE

Rename in 2018, drop in 2021

Two of this topic's statements are recent. SQLite's list of changes adds support for renaming columns within a table, with ALTER TABLE RENAME COLUMN, in version 3.25.0 of 2018-09-15. It adds support for ALTER TABLE DROP COLUMN in version 3.35.0 of 2021-03-12, the same release that brought RETURNING. Before then, both needed a new table and a copy.

Why it fits here: It answers the topic's question with the releases that made renaming and dropping a column possible.

Source: SQLite: Release History

In one line

ALTER TABLE adds, renames or drops a column, or renames the table, and a new NOT NULL column needs a DEFAULT; DROP TABLE removes the whole table, rows and rules.

Where it is used

Every button that saves something in an app ends in one of this lesson's statements.

Sign up, edit, delete

Signing up for a site is an INSERT into its users table. Changing your profile picture is an UPDATE of one row, found by your id. Deleting your account is a DELETE, or, very often, an UPDATE that only marks the row as deleted, so that the records can be kept or restored: the same idea as the worked example's status column.

Rules that protect the data

The constraints of this lesson guard real tables everywhere. UNIQUE on an e-mail column is why a site says "this e-mail is already registered". NOT NULL keeps an order from being saved without a customer. CHECK keeps a price or a stock count from going below zero, whatever a buggy app tries to store.

Changing a live database

Apps grow, and their tables must grow with them. Teams write each ALTER TABLE as a small, numbered script called a migration, kept with the code, so that every copy of the database can be brought to the same shape, step by step. Lesson 05's foreign keys and this lesson's constraints come back in the PostgreSQL track, T12, together with transactions, which let a group of changes be undone as one.

On the screenIn the database
Sign upINSERT INTO users (email, name) VALUES (...)
"This e-mail is already registered"UNIQUE constraint failed: users.email
Edit profileUPDATE users SET name = ... WHERE id = 42
Delete accountDELETE FROM users WHERE id = 42, or an UPDATE that marks it deleted
A new feature needs a new fieldALTER TABLE users ADD COLUMN ..., in a migration

Mistakes and how to find them

Writing goes wrong in the same two ways as reading, loudly or quietly, but a quiet mistake now leaves wrong data behind. This file holds four mistakes, two of each kind, and a SELECT at the end to see what they did.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (hall_id, unit) VALUES (2, 's');
UPDATE gauges SET reading = 2.1 WHERE name = 'Pendulum';
UPDATE gauges SET reading = 2.1 AND unit = 's' WHERE name = 'pendulum';
DROP TABLE shifts;
SELECT name, unit, reading FROM gauges WHERE name = 'pendulum';

Terminal: sqlite3 ledger.db < query.sql

Error near line 1: NOT NULL constraint failed: gauges.name
Parse error near line 4: no such table: shifts
╭──────────┬──────┬─────────╮
│   name   │ unit │ reading │
╞══════════╪══════╪═════════╡
│ pendulum │ s    │     1.0 │
╰──────────┴──────┴─────────╯

Line 1 left out the name, and the NOT NULL rule refused the row: loud, and harmless, as nothing was stored. Line 4 dropped a table that does not exist: loud again.

Lines 2 and 3 are the quiet ones, and they printed nothing at all. Line 2 asked for Pendulum with a capital P; = is exact, no row matched, and nothing changed. Line 3 found the pendulum, but joined its two new values with AND, so the reading became 1.0, the result of a true test, and the unit was never set. The last SELECT shows the damage: a reading of 1.0 that nobody meant.

The quiet mistakes

The statementWhat it really doesWhat was meant
UPDATE gauges SET reading = 0;changes every rowadd the WHERE
DELETE FROM gauges;removes every rowadd the WHERE
SET reading = 2.1 AND unit = 's'stores 1.0 in readingSET reading = 2.1, unit = 's'
WHERE name = 'Pendulum'matches no row, changes nothingWHERE name = 'pendulum'
WHERE hall_id = NULLmatches no row, everWHERE hall_id IS NULL
VALUES ('barometer', 'hPa', 4, 1013) for name, hall_id, unit, readingstores hPa as the hall and 4 as the unitvalues in the order of the columns
DELETE FROM halls ... with gauges pointing at itleaves orphansPRAGMA foreign_keys = ON; first

A way to change data safely

  1. Write the WHERE first, and run it in a SELECT *: read every row it finds.
  2. Change SELECT * to UPDATE ... SET or DELETE, and keep the WHERE exactly as it was.
  3. Turn on .changes, or add RETURNING, and compare the count with the rows the SELECT found.
  4. Run a SELECT afterwards, and read the changed rows.
  5. Keep PRAGMA foreign_keys = ON at the top of any script that deletes rows others point at.

The debugging corner: a copy to practise on

A database in SQLite is one file. Before a risky change, copy it, cp ledger.db ledger-before.db, and try the change on the copy, sqlite3 ledger-before.db < change.sql. If the result is right, run the same file on the real one.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

query.sql (ledger.db holds halls and gauges, with the Registrar's rules)

INSERT INTO gauges (name, hall_id, unit, reading) VALUES ('barometer', 4, 'hPa', 1013);
UPDATE gauges SET reading = 91.5 WHERE name = 'chimney';
DELETE FROM gauges WHERE name = 'valve';
SELECT name, hall_id, reading FROM gauges WHERE name IN ('barometer', 'chimney', 'valve');

Terminal: sqlite3 ledger.db < query.sql

╭───────────┬─────────┬─────────╮
│   name    │ hall_id │ reading │
╞═══════════╪═════════╪═════════╡
│ barometer │       4 │  1013.0 │
│ chimney   │       3 │    91.5 │
╰───────────┴─────────┴─────────╯
To do thisWrite this
Add a rowINSERT INTO gauges (name, unit) VALUES ('lamp', 'lux');
Add several rows... VALUES ('lamp', 'lux'), ('clock', 's');
See what changed... RETURNING id, name
Change rowsUPDATE gauges SET reading = 91.5 WHERE name = 'chimney';
Change two columnsSET reading = 2.1, unit = 's'
Remove rowsDELETE FROM gauges WHERE name = 'valve';
Count the rows a change touched.changes on
Require a valuename TEXT NOT NULL
Forbid repeatsname TEXT UNIQUE
Fill a missing valueunit TEXT DEFAULT 'C'
Test every rowCHECK (reading >= 0)
Change the tableALTER TABLE gauges ADD COLUMN status TEXT;
Remove the tableDROP TABLE IF EXISTS gauges;

Words to know: INSERT, VALUES, RETURNING, UPDATE, SET, DELETE, constraint, NOT NULL, UNIQUE, DEFAULT, CHECK, orphan, ALTER TABLE, ADD COLUMN, RENAME, DROP COLUMN, DROP TABLE, IF EXISTS, migration.

Self-check

Say each answer aloud before you open it.

What happens to an UPDATE or DELETE that has no WHERE?Tap to reveal
  1. How many rows pass a missing test?

It changes, or removes, every row of the table.

How do you separate two new values in SET?Tap to reveal
  1. Not AND.

With a comma: SET reading = 2.1, unit = 's'.

Which rule lets a NULL through, and why?Tap to reveal
  1. Not known is not false.

CHECK: it refuses a row only when its test is false, and a test on NULL is not known.

What does a new NOT NULL column need, and why?Tap to reveal
  1. The rows already there.

A DEFAULT, so that the rows already in the table have a value for it.

What is the safe way to write a DELETE?Tap to reveal
  1. Look first.

Run the WHERE in a SELECT * first, then change SELECT * to DELETE with the same WHERE, and check the count.

The story: Rules at the top of the page

By evening the changes are in. The compass stands in the Archive, the chimney reads 91.5, the pendulum's reading is right, and the valve is gone. A clerk tries to write a gauge with no name and the ledger refuses; another tries a second fan and is refused again.

One clerk nearly struck out every line by forgetting the WHERE. The Registrar had asked for a SELECT with the same WHERE first, and the clerk saw nine rows where one was meant.

The Registrar blots the page. "Changes are easy," she says. "Changes you meant are the hard part. Tomorrow we ask questions inside questions."

Reagents gathered: INSERT, UPDATE, DELETE, NOT NULL, UNIQUE, CHECK.

Sources