Writing data in transactions
Write rows with INSERT, UPDATE and DELETE, read back results, and group changes into transactions.
- Insert, update and delete rows using a where clause.
- Read back the changed rows with returning.
- Wrap related changes in begin and commit.
- Use savepoints to undo only part of a transaction.
In plain English
INSERT adds rows, UPDATE changes existing rows, and DELETE removes rows. RETURNING lets any of these statements send back the rows they changed, so you can read the result without a second query. A transaction groups several statements into one all-or-nothing unit: BEGIN starts it, COMMIT saves everything, and ROLLBACK undoes it. A savepoint is a named marker inside a transaction that you can roll back to without discarding the whole transaction.
Step by step
- 1Start a transaction with begin.
- 2Insert a row and read its id with returning.
- 3Update rows using a where clause to target them.
- 4Mark a savepoint and roll back to it if a later step goes wrong.
- 5Finish with commit to keep the changes, or rollback to discard them.
begin;
insert into courses (slug, title)
values ('postgresql', 'PostgreSQL Foundations')
returning id;
savepoint inserted;
update courses
set title = 'PostgreSQL Foundations: Revised'
where slug = 'postgresql';
rollback to savepoint inserted;
commit;Common mistakes
- Running an UPDATE or DELETE without a WHERE clause changes every row in the table, which is rarely what you intended.
- Forgetting to commit leaves a transaction open, which can hold locks and block other work.
- Assuming an error automatically saves the good parts is wrong, because in PostgreSQL an error aborts the whole transaction until you roll back.
- Expecting DELETE ... RETURNING to show what remains is a mistake, because it returns the rows that were deleted.
Make an atomic update
Start a transaction, insert a course and return its id, update its title, then commit.
insert into courses (slug, title) values ('sql', 'SQL Basics');What does RETURNING do after an INSERT, UPDATE or DELETE?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.