PostgreSQL Foundations·A database you can operate

Writing data in transactions

Write rows with INSERT, UPDATE and DELETE, read back results, and group changes into transactions.

Intermediate 12 min read Lesson 3 of 300 Challenge included
What you will be able to do
  • 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

  1. 1Start a transaction with begin.
  2. 2Insert a row and read its id with returning.
  3. 3Update rows using a where clause to target them.
  4. 4Mark a savepoint and roll back to it if a later step goes wrong.
  5. 5Finish with commit to keep the changes, or rollback to discard them.
transaction.sqlSQL
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.
Your turn

Make an atomic update

Easy

Start a transaction, insert a course and return its id, update its title, then commit.

SQL · starter
insert into courses (slug, title) values ('sql', 'SQL Basics');
Check your understanding before moving on.
Knowledge checkQuestion 1

What does RETURNING do after an INSERT, UPDATE or DELETE?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Backups and restore
Lesson 3 of 300 · 0% of course