UPDATE

UPDATE and DELETE

SQLite in your browser
Lesson concept What you'll do
1 / 4

Change or remove the rows that match a test.

UPDATE ... SET changes values and DELETE removes rows. Always add a WHERE.

The database
11 rows
loan_idbook_idmember_idloan_datereturned
111022026-01-022026-01-22
231012026-02-102026-02-17
3101062026-03-052026-03-21
481012026-04-072026-04-28
561022026-05-202026-06-03
641042026-06-222026-06-29
741062026-08-022026-08-20
871042026-08-112026-09-01
921042026-09-09NULL
1051052026-09-15NULL
1131062026-10-28NULL
Click a name to type it
Your query
 
Hint: click the green edit button on the board, or type it yourself
loans after your query Ready to run

Run your query to see the result table.

Press the green Run button or Ctrl+Enter.

Study notes

How UPDATE, DELETE works

UPDATE changes the genre, but only in the rows WHERE picks: books before 1900.

UPDATE books
SET genre = 'Classic'
WHERE year < 1900;

books before

book_idtitlegenreyear
1FrankensteinHorror1818
2EmmaRomance1815
3DuneScience Fiction1965
4CarrieHorror1974

Highlighted: the rows WHERE picks

books after (2 rows changed)

book_idtitlegenreyear
1FrankensteinHorrorClassic1818
2EmmaRomanceClassic1815
3DuneScience Fiction1965
4CarrieHorror1974
  • How do I change values?

    UPDATE books SET genre = 'Classic' WHERE year < 1900;

    SET says the new value; WHERE says which rows. Several columns at once: SET genre = 'Classic', pages = 300.

  • How do I remove rows?

    DELETE FROM loans WHERE returned IS NOT NULL;

    It removes every row the WHERE picks. There's no column list: whole rows go.

  • What if I forget WHERE?

    UPDATE changes every row and DELETE empties the table. In real databases there's no undo button, so this is the classic expensive mistake.

  • How do I stay safe?

    Run a SELECT * ... WHERE with the same condition first and check the rows. In real work, wrap changes in BEGIN ... COMMIT, so ROLLBACK can undo them.

  • Is anything saved here?

    No: every run starts again from the original table, so practise freely.

Other databases

How other databases do it

The lessons run on SQLite. Most of SQL is the same everywhere; these are the places where this lesson's SQL differs.

Do changes save straight away?
DatabaseHowNote
SQLite (these lessons)YesUnless you start with BEGIN; then COMMIT saves and ROLLBACK undoes.
PostgreSQLYesUnless you start with BEGIN; then COMMIT or ROLLBACK.
MySQL / MariaDBYesautocommit is on. START TRANSACTION, then COMMIT or ROLLBACK.
SQL ServerYesUnless you start with BEGIN TRANSACTION; then COMMIT or ROLLBACK.
OracleNoChanges wait for COMMIT, and ROLLBACK undoes them. Most tools don't commit for you.
Sybase ASEYesUnless you start with BEGIN TRANSACTION (or turn chained mode on).

Know someone fighting with a spreadsheet? Send them this page.