Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Changing data and transactions

By the end of this chapter, you'll be able to

  • Add, change and delete rows with INSERT, UPDATE and DELETE
  • Get back the changed rows with RETURNING
  • Insert or update in one statement with ON CONFLICT
  • Group changes into a transaction with BEGIN, COMMIT and ROLLBACK

INSERT, UPDATE, DELETE

The shop manages a small catalogue of items with their stock:

INSERT INTO items (name, price, stock) VALUES ('50 W panel', 70.0, 5) RETURNING id, name;
UPDATE items SET price = ROUND(price * 1.10, 2) WHERE name = 'Water bottle';
UPDATE items SET stock = stock - 3 WHERE id = 2 RETURNING name, stock;
DELETE FROM items WHERE stock = 0;
SELECT id, name, price, stock FROM items ORDER BY id;
id | name
4 | 50 W panel
name | stock
Water filter | 0
id | name | price | stock
1 | Solar lamp | 25 | 12
3 | Water bottle | 9.9 | 30
4 | 50 W panel | 70 | 5
  • INSERT INTO table (columns) VALUES (…) adds a row. Missing columns take their default value (DEFAULT) or, for the primary key, a new identifier.
  • RETURNING returns the inserted or changed rows: handy to learn the assigned id without a second query.
  • UPDATE … SET column = expression WHERE condition changes the rows that meet the condition. The expression can use the old value: stock = stock - 3.
  • DELETE FROM … WHERE condition deletes the targeted rows. Here, the water filter, down to 0.

Insert or update: ON CONFLICT

A delivery arrives: some items already exist (their stock must go up), others are new (they must be created). ON CONFLICT does both in one statement, often called an upsert:

INSERT INTO items (name, price, stock) VALUES ('Water bottle', 9.0, 10), ('Kettle', 15.0, 4)
ON CONFLICT (name) DO UPDATE SET stock = stock + excluded.stock;
SELECT name, stock FROM items ORDER BY name;
name | stock
Kettle | 4
Solar lamp | 12
Water bottle | 40
Water filter | 3

The name column is UNIQUE: inserting a second "Water bottle" causes a conflict, and SQLite then runs the DO UPDATE. excluded refers to the row we were trying to insert: 30 + 10 = 40.

Transactions

A transaction groups several statements into a whole: either all of them are applied (COMMIT), or none (ROLLBACK). A transfer of €200 from the cooperative to its supplier:

BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
UPDATE accounts SET balance = balance + 200 WHERE id = 2;
COMMIT;
SELECT holder, balance FROM accounts;
holder | balance
Cooperative | 300
Supplier | 320

And if you change your mind before the end, ROLLBACK cancels everything done since BEGIN:

BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
UPDATE accounts SET balance = balance + 200 WHERE id = 2;
ROLLBACK;
SELECT holder, balance FROM accounts;
holder | balance
Cooperative | 500
Supplier | 120

The application cancels the whole transaction. The provisional credit disappears: no money was created.

Step 4 of 4
Text description of the animation
  1. The transaction starts: nothing is final yet.
  2. The credit goes through, but only inside the transaction.
  3. Debiting 800 would make the balance negative: the constraint refuses it.
  4. The application cancels the whole transaction. The provisional credit disappears: no money was created.

This last scenario has a subtlety. In SQLite, a violated constraint cancels the offending statement, but the transaction stays open, with the credit already applied:

BEGIN;
UPDATE accounts SET balance = balance + 800 WHERE id = 2;
UPDATE accounts SET balance = balance - 800 WHERE id = 1;
CHECK constraint failed: balance >= 0

So it's up to the program driving the database to run ROLLBACK as soon as a statement fails. Database access libraries do it for you: in Python, with connection: automatically rolls back the transaction on an exception.

Your turn

Mini-lab: a till saleSQLite

Result

Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.

A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Solved exercise: the till sale

Write the mini-lab's transaction: a customer buys 2 solar lamps; the stock drops by 2 and the cooperative's account (id 1) goes up by the sale amount, computed from the item's price. Then display the lamps' stock and the cooperative's balance.

Hint 1
The price is read with a subquery: balance + 2 * (SELECT price FROM items WHERE name = 'Solar lamp').
Hint 2
Check each WHERE: forgetting one would change every item or every account.
Show the solution and common mistakes
BEGIN;
UPDATE items SET stock = stock - 2 WHERE name = 'Solar lamp';
UPDATE accounts SET balance = balance + 2 * (SELECT price FROM items WHERE name = 'Solar lamp') WHERE id = 1;
COMMIT;
SELECT name, stock FROM items WHERE name = 'Solar lamp';
SELECT holder, balance FROM accounts WHERE id = 1;
name | stock
Solar lamp | 10
holder | balance
Cooperative | 550

If the stock were insufficient (5 water filters requested when 3 remain), the CHECK (stock >= 0) constraint would make the first update fail, and the program would roll back the transaction: no payment without goods.

Common mistakes:

  • Hard-coding the price (balance + 50): the day the price changes, the till collects the wrong amount.
  • Doing both updates outside a transaction: a failure between them leaves a reduced stock with no payment.

Summary

  1. 1INSERT adds, UPDATE changes, DELETE removes: always with a precise WHERE for the last two.
  2. 2RETURNING returns the changed rows; ON CONFLICT … DO UPDATE inserts or updates in one statement.
  3. 3A transaction (BEGIN … COMMIT) applies several changes together, or none with ROLLBACK.
  4. 4After an error inside a transaction, the program must run ROLLBACK.
  5. 5Before an UPDATE or a DELETE, check the targeted rows with a SELECT.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.