…
…
SQL and Database Fundamentals · Lesson 37 / 41 · Transactions and views
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The registrar's office must move 10 seats from the Quantitative Reasoning II section (52) to the Academic Writing section (48). If the job stops halfway, one section loses 10 seats and the other never gains them. On the same day, student 6 must move from the closing Data Structures section (13) to the Introduction to Programming section (10), and in this lesson you will do both jobs so that they happen completely or not at all.
In lessons 34, 35 and 36 you added, updated and deleted rows. Each command ran on its own and its result was permanent right away. That was enough until now, because each job was a single command. But most real jobs have two or more steps, and those steps cannot be separated from each other.
Let's look at the goal first. Before and after the seat transfer, the two sections should look like this:
| offering | course | before | after |
|---|---|---|---|
| 48 | Academic Writing | 40 | 50 |
| 52 | Quantitative Reasoning II | 60 | 50 |
| total | 100 | 100 |
The total does not change: 10 seats leave one section and enter the other. For this table to come out right, both UPDATE commands must run.
In this lesson you will:
Think of the seat transfer as two steps: first the capacity of offering 52 goes down by 10, then the capacity of offering 48 goes up by 10. What happens if the power goes out after the first step, the connection drops, or the second command fails? Offering 52 now has 50 seats but offering 48 still has 40. The total fell from 100 to 90, and 10 seats vanished. No command was written wrong. The problem is that half of the job happened and half did not.
A bank transfer has the same problem. $200 leaves Ali's account and $200 enters Maya's account. If only the first happens, the money disappears. If only the second happens, money appears from nowhere. The two steps must count as one job.
A transaction is a mechanism that runs several commands as one unit of work. Either all the commands in it become permanent, or none of them do.
First, let's see what happens without a transaction. In PostgreSQL, unless you write BEGIN, each command runs in its own small transaction and becomes permanent as soon as it finishes. This is called autocommit. Writing two commands one after the other does not tie them together. Each one stands alone.
Let's see this in the section change. Student 6 wants to leave the Data Structures section (13), which is closing, and join the Database Systems section (15). That means two commands: delete the old record and insert the new one.
Example 1 (case): The section change stops halfway
BEGIN; DELETE FROM enrollment WHERE student_id = 6 AND offering_id = 13; INSERT INTO enrollment (student_id, offering_id, enrolled_on) VALUES (6, 15, DATE '2026-09-25');
OutputERROR: duplicate key value violates unique constraint "enrollment_student_id_offering_id_key"The DELETE ran, but the INSERT was rejected. You know this error message from lesson 29: in the enrollment table the pair (student_id, offering_id) is unique, and student 6 is already enrolled in offering 15. The request was entered wrongly. Luckily, the two commands are inside a transaction that started with BEGIN. When the transaction is rolled back, the deleted record for offering 13 comes back too. But what if there had been no BEGIN?
If the same two commands had run without BEGIN and the INSERT had still been rejected, what would have happened to student 6's record for offering 13?
DELETE FROM enrollment WHERE student_id = 6 AND offering_id = 13; INSERT INTO enrollment (student_id, offering_id, enrolled_on) VALUES (6, 15, DATE '2026-09-25');
This is the typical cost of not using a transaction. No error message says "you left the student without a course". The table follows the rules, but it does not match reality. Thinking that two commands in a row count as "together" is a common mistake: without BEGIN, every command stands alone.
Three commands control a transaction:
BEGIN; starts the transaction. The changes after it are temporary.COMMIT; confirms the transaction. All changes made since BEGIN become permanent together.ROLLBACK; undoes the transaction. All changes made since BEGIN are removed together, and the database returns to its state before BEGIN.While the transaction is open, you see your own changes in your session, so you can check them with SELECT. Other users keep seeing the old data until COMMIT. This lets you check the result first, commit if it is right, and roll back if it is wrong. It is the safest form of the "SELECT first, then change" habit from lessons 35 and 36: change, check, then decide.
Example 2 (case): The seat transfer in one transaction
BEGIN; UPDATE course_offering SET capacity = capacity - 10 WHERE id = 52; UPDATE course_offering SET capacity = capacity + 10 WHERE id = 48; SELECT id, capacity FROM course_offering WHERE id IN (48, 52) ORDER BY id; COMMIT;
| id | capacity |
|---|---|
| 48 | 50 |
| 52 | 50 |
(2 rows)
The SELECT ran inside the transaction, before COMMIT: you saw the changes before confirming them. The total of the two offerings is 100 before and after. Because the numbers were right, COMMIT was written. If you had seen something wrong, you would have written ROLLBACK instead of COMMIT. Put the lines in order yourself to practice the pattern:
Put the lines of the transaction that moves 10 seats from offering 52 to offering 48 in order: start the transaction, first subtract from 52, then add to 48, check the result, and commit.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now let's see how undoing works. Someone ran a command that deletes all enrollments of the Entrepreneurship section (31), but the command was inside a transaction.
Example 3 (case): Undoing a delete
BEGIN; DELETE FROM enrollment WHERE offering_id = 31; ROLLBACK; SELECT COUNT(*) AS enrollments FROM enrollment WHERE offering_id = 31;
| enrollments |
|---|
| 16 |
(1 row)
All 16 records are still there. ROLLBACK undoes not just the last command but everything done since BEGIN. If the transaction had ten commands, the effect of all ten would be removed. Thinking that "ROLLBACK undoes the last command" comes from comparing it to the undo button in a text editor. ROLLBACK undoes the whole transaction.
Let's do the section change again, this time with the right section. The right section for student 6 is Introduction to Programming (10):
Example 4 (case): The section change in one transaction
BEGIN; DELETE FROM enrollment WHERE student_id = 6 AND offering_id = 13; INSERT INTO enrollment (student_id, offering_id, enrolled_on) VALUES (6, 10, DATE '2026-09-25'); COMMIT; SELECT e.offering_id, c.name FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id WHERE e.student_id = 6 AND o.term_id = 3 ORDER BY e.offering_id;
| offering_id | name |
|---|---|
| 10 | Introduction to Programming |
| 15 | Database Systems |
| 48 | Academic Writing |
(3 rows)
The student's records for this term were 13, 15, 48. Now they are 10, 15, 48. Offering 13 is gone and offering 10 has arrived, both at the same moment. The transaction is ready in the cell below. Run it, then:
1. Change the 10 in the VALUES line to 15 and run it again. Which error do you get? This time the DELETE is also void.
2. Change 15 back to 10; the result table should come back.
Try it now· not graded; doesn't affect progress
In the cells and exercises of this course, code that contains BEGIN runs on a clean copy of the case database. You can also write COMMIT; you see the result in the same run, with a SELECT after the COMMIT. When the run ends, the copy is deleted. The shared database does not change, and the next run starts with clean data again. So act as you would in a real system: check the result, write COMMIT if it is right, and ROLLBACK if it is wrong. In a real system, COMMIT cannot be undone. A committed change comes back only from a backup.
Now let's see what happens when a command inside a transaction fails. After the seat transfer, the registrar's office wants to enter the finals of the Entrepreneurship section (31) in the same transaction. Each student's final will be their midterm plus 5:
OutputBEGIN;
UPDATE course_offering SET capacity = capacity - 10 WHERE id = 52;
UPDATE course_offering SET capacity = capacity + 10 WHERE id = 48;
UPDATE enrollment SET final_exam = midterm + 5 WHERE offering_id = 31;
ERROR: new row for relation "enrollment" violates check constraint "enrollment_final_exam_check"One student in the section has a midterm of 100 (student 64). Their final would be 105, and the final_exam BETWEEN 0 AND 100 rule rejected it. The capacity updates ran without errors. What happens to them?
The third UPDATE failed. In PostgreSQL, what happens next to the commands written in the same transaction and to the two earlier capacity updates?
In a real PostgreSQL session, every command you write after the error gets this reply:
OutputSELECT id, capacity FROM course_offering WHERE id IN (48, 52);
ERROR: current transaction is aborted, commands ignored until end of transaction block
COMMIT;
ROLLBACKThe message on the first line says "the transaction is broken, commands are ignored until the transaction block ends". Look at the last line: COMMIT was written, but PostgreSQL's reply is ROLLBACK. A broken transaction cannot be committed. The COMMIT command closes it by rolling it back. On this site, execution stops at the command that fails and you see only the first error message. The current transaction is aborted message does not appear, but the result is the same: none of the changes in the transaction remain.
This strictness is on purpose. If the printer jams while a receipt is printing, a half receipt is not given to the customer. The receipt is canceled and printed again. The database also does not make half a job permanent. The example teaches a second lesson too: the seat transfer and the grade entry are two unrelated jobs. Putting them in the same transaction meant that an error in the grade entry also rolled back the seat transfer. Put only the changes that must happen together in one transaction.
Sometimes you want to undo only the last steps of a transaction, not all of it. The registrar's office entered the finals of the Entrepreneurship section. Then it moved on to letter grades and by mistake wrote 'A' for all of them. If it writes ROLLBACK, the finals go too. What it wants is to keep the finals and undo only the letter grades.
SAVEPOINT name puts a savepoint in the middle of a transaction. ROLLBACK TO SAVEPOINT name undoes only the changes after that point. The earlier ones stay, and the transaction remains open. Think of a save point in a game: when you lose, you go back to the last save point, not to the start of the game, and the game goes on.
Example 5 (case): Going back to a savepoint
BEGIN; UPDATE enrollment SET final_exam = CASE WHEN midterm + 5 > 100 THEN 100 ELSE midterm + 5 END WHERE offering_id = 31; SAVEPOINT finals; UPDATE enrollment SET letter_grade = 'A' WHERE offering_id = 31; ROLLBACK TO SAVEPOINT finals; COMMIT; SELECT COUNT(final_exam) AS finals_entered, COUNT(letter_grade) AS letters_entered FROM enrollment WHERE offering_id = 31;
| finals_entered | letters_entered |
|---|---|
| 16 | 0 |
(1 row)
This time the finals went in without an error: the CASE from lesson 8 keeps a final that would pass 100 at 100. 16 finals remain, and all the wrong letter grades were undone. Notice that the transaction is still open after ROLLBACK TO SAVEPOINT. To make the finals permanent, a COMMIT was needed at the end. Thinking that "ROLLBACK TO SAVEPOINT ends the transaction" is a common mistake. It only rewinds and does not close the transaction. Only COMMIT or ROLLBACK ends a transaction.
If you try to go back to a savepoint that does not exist, PostgreSQL objects, and because this is an error, the transaction is broken:
OutputROLLBACK TO SAVEPOINT missing;
ERROR: savepoint "missing" does not existExample 5 is ready in the cell below. Run it and see the result 16, 0. Then change the line ROLLBACK TO SAVEPOINT finals; to just ROLLBACK; and run it again. What happened to the number of finals? Why?
Try it now· not graded; doesn't affect progress
In the second try, the number of finals is 0: a plain ROLLBACK does not know the savepoint. It undoes everything since BEGIN and ends the transaction. The COMMIT after it finds no transaction to confirm.
The guarantees that transactions give are summed up in four letters: ACID. Atomicity means a transaction is applied completely or not at all. Consistency means all constraints hold when the transaction ends. Isolation means transactions running at the same time do not see each other's half-finished changes. Durability means data that was committed is not lost, even if the power goes out right after.
Match each letter of ACID with the guarantee it gives.
For each row, pick its match from the list, then check.
Isolation has a side effect. If two people try to update the same row at the same time, the second one waits until the first one's transaction ends with COMMIT or ROLLBACK. The row is locked. If two staff members at the registrar's office try to change the capacity of offering 48 at the same time, the second command does not move until the first transaction closes. This is why transactions are kept short: writing BEGIN and then going for coffee stops everyone who is waiting for those rows.
Transactions are most often taught with money, because there an unfinished job shows up right away. Let's build a simple account table: each account has an owner and a balance, and the balance cannot go below zero.
Example 6 (outside the case): A transfer
CREATE TABLE account ( id INTEGER PRIMARY KEY, owner VARCHAR(20) NOT NULL, balance INTEGER NOT NULL CHECK (balance >= 0) ); INSERT INTO account VALUES (1, 'Ali', 300), (2, 'Maya', 100); BEGIN; UPDATE account SET balance = balance + 200 WHERE id = 2; UPDATE account SET balance = balance - 200 WHERE id = 1; COMMIT; SELECT owner, balance FROM account ORDER BY id;
| owner | balance |
|---|---|
| Ali | 100 |
| Maya | 300 |
(2 rows)
$200 moved from Ali to Maya. The total is 400 before and after. Now suppose Ali tries to send $500. Ali's account has only $300. The first command of the transaction raises Maya's balance to 600. The second tries to bring Ali's to -200 and hits the account_balance_check rule:
OutputERROR: new row for relation "account" violates check constraint "account_balance_check"In the $500 transfer, the second UPDATE failed. After the transaction is closed, what is Maya's balance?
BEGIN; UPDATE account SET balance = balance + 500 WHERE id = 2; UPDATE account SET balance = balance - 500 WHERE id = 1; COMMIT;
The cell below has the table setup and the transfer ready. First run it as it is: the $200 transfer goes through. Then change both 200 values in the UPDATE lines to 500: you see the rule error and no change remains. Finally try 300: Ali's balance becomes exactly 0, and this is accepted because the rule says >= 0.
Try it now· not graded; doesn't affect progress
The real protection here comes from the rule and the transaction together. The rule catches the negative balance. The transaction cleans up the half-done job when the rule catches it. One alone is not enough. Without the rule, Ali's balance would be -200. Without the transaction, Maya's balance would stay at 600.
A transaction is used not only for permanent changes but also to safely try "what happens if I do this?". Let's see what entering the Entrepreneurship finals does to the section average, and leave without changing anything:
BEGIN; UPDATE enrollment SET final_exam = CASE WHEN midterm + 5 > 100 THEN 100 ELSE midterm + 5 END WHERE offering_id = 31; SELECT ROUND(AVG(final_exam), 1) AS average, MIN(final_exam) AS lowest, MAX(final_exam) AS highest FROM enrollment WHERE offering_id = 31; ROLLBACK;
| average | lowest | highest |
|---|---|---|
| 79.8 | 50 | 100 |
(1 row)
The average would be 79.8. After ROLLBACK, the section still has no finals. If you liked the result, writing COMMIT instead of ROLLBACK
Leaving a transaction open. You write BEGIN, do not write COMMIT or ROLLBACK, leave the session open, and go on to other work. The changes do not become permanent: when the session closes, all of them are undone. Worse, the rows you changed stay locked until the transaction ends, and everyone who wants to update the same rows waits. The same mistake happens after ROLLBACK TO SAVEPOINT: you think the rewind ended the transaction and forget COMMIT. Make sure every BEGIN has a COMMIT or a ROLLBACK, and keep transactions short.
BEGIN, COMMIT makes everything permanent, and ROLLBACK undoes everything done since BEGIN. Without BEGIN, every command is permanent right away on its own (autocommit).COMMIT rolls it back. So put only changes that depend on each other in one transaction.SAVEPOINT puts a savepoint in the middle of a transaction. ROLLBACK TO SAVEPOINT undoes only what came after that point and leaves the transaction open. Only COMMIT or ROLLBACK ends it.Next lesson: you will save the queries you use often as views (VIEW) and query them like a table.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Let's add COMMIT to the end of the transaction in step 5 and then look at the offerings. This code stops at the failing command, so we give the flow of a real session as text:
OutputBEGIN;
UPDATE course_offering SET capacity = capacity - 10 WHERE id = 52;
UPDATE course_offering SET capacity = capacity + 10 WHERE id = 48;
UPDATE enrollment SET final_exam = midterm + 5 WHERE offering_id = 31;
ERROR: new row for relation "enrollment" violates check constraint "enrollment_final_exam_check"
COMMIT;
ROLLBACK
SELECT id, capacity FROM course_offering WHERE id IN (48, 52) ORDER BY id;| id | capacity |
|---|---|
| 48 | 40 |
| 52 | 60 |
The capacities are as they were before the transfer. The right way is to fix the grade entry with CASE and do the two jobs in two separate transactions: first the seat transfer (Example 2), then the grade entry (Example 5).