Sub topic 3
Wrapping changes in a transaction
This chapter assumes you can write SELECT with WHERE, know primary and foreign keys, and have run INSERT, UPDATE, and DELETE. Examples use the customers and orders tables from earlier in the tutorial. They are written for PostgreSQL and SQLite, and the differences are noted.
Grouping statements with a transaction
A transaction is a group of statements that either all take effect or all get undone. Start one with BEGIN, then finish with COMMIT to keep the changes or ROLLBACK to discard them.
BEGIN;
DELETE FROM orders WHERE status = 'cancelled';
SELECT COUNT(*) FROM orders;
ROLLBACK; -- use COMMIT; to keep the deletionMySQL and SQL Server start transactions with START TRANSACTION and BEGIN TRANSACTION respectively.
When a change is rejected: constraint errors
When a statement breaks a constraint, the database rejects that statement and changes nothing from it. In PostgreSQL, an error inside a transaction also blocks every later statement until you run ROLLBACK.
INSERT INTO orders (id, customer_id, total)
VALUES (101, 999, 25.00);
-- ERROR: foreign key constraint rejects customer_id 999Foreign keys and deleting parent rows
Deleting a customer who still has orders violates the foreign key on orders.customer_id, so the delete fails by default. ON DELETE CASCADE removes the child orders automatically. This is convenient, but it can delete more data than you expect.
DELETE FROM customers WHERE id = 1;
-- ERROR: update or delete on table "customers" violates foreign key constraintUpdating and deleting based on other tables
PostgreSQL and SQL Server use UPDATE ... FROM, while MySQL uses UPDATE ... JOIN. Standard SQL has no single form, so check your dialect.
UPDATE orders
SET status = 'vip'
FROM customers
WHERE orders.customer_id = customers.id
AND customers.email = '[email protected]';DELETE versus TRUNCATE
DELETE removes only the rows that match a WHERE clause. TRUNCATE empties the whole table. In PostgreSQL and SQL Server, TRUNCATE runs inside a transaction and can be rolled back. In MySQL it commits immediately and cannot be rolled back. SQLite has no TRUNCATE statement.
Getting changed rows back with RETURNING
PostgreSQL and SQLite 3.35 or later accept RETURNING, which sends back the affected rows. SQL Server uses an OUTPUT clause for the same purpose. MySQL has no equivalent.
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING id, customer_id;Insert-or-update with upsert
An upsert inserts a row, or updates it when the key already exists. PostgreSQL and SQLite use ON CONFLICT, MySQL uses ON DUPLICATE KEY UPDATE, and standard SQL uses MERGE.
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada King', '[email protected]')
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name;Exercise
Inside a transaction, DELETE FROM customers WHERE id = 2 fails because orders still reference that customer. In PostgreSQL, what must you do before running more statements, and what are two ways to fix the problem?
Show answer
Run ROLLBACK first, because PostgreSQL blocks later statements in a failed transaction. Then either delete the matching orders first in the same transaction and COMMIT, or, if the design calls for it, add ON DELETE CASCADE to the foreign key.