SQL & Databases·Database skills from the start

Transactions and locking

Group statements into safe, all-or-nothing transactions and understand why the database locks rows.

Beginner 12 min read Lesson 5 of 480 Challenge included
What you will be able to do
  • Use BEGIN, COMMIT, and ROLLBACK to group statements
  • Explain ACID in plain language
  • Describe why the database locks rows
  • Explain what a deadlock is and how to avoid one

In plain English

A transaction is a group of statements that are treated as one unit: either they all succeed or none of them do. You start one with BEGIN, save the work with COMMIT, or undo it all with ROLLBACK. ACID is the set of guarantees a database gives you: Atomicity (all-or-nothing), Consistency (a valid state), Isolation (transactions do not interfere), and Durability (committed work survives). When one transaction changes a row, the database can lock that row so other transactions wait, which prevents conflicting writes. A deadlock happens when two transactions each wait on a row the other holds; keeping transactions short makes deadlocks much less likely.

Step by step

  1. 1Start a transaction with BEGIN.
  2. 2Run the related statements, like moving money from one account to another.
  3. 3Check the result, then COMMIT to save it or ROLLBACK to undo it.
  4. 4Keep the transaction short so row locks are released quickly.
transfer.sqlSQL
CREATE TABLE accounts (
  id SERIAL PRIMARY KEY,
  balance NUMERIC(12, 2) NOT NULL DEFAULT 0
);

INSERT INTO accounts (balance) VALUES (1000.00), (500.00);

BEGIN;

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

COMMIT;

BEGIN;

UPDATE accounts SET balance = balance - 9999 WHERE id = 1;

ROLLBACK;

Common mistakes

  • Forgetting to COMMIT, which leaves a transaction open and its row locks held.
  • Assuming a failed statement automatically rolls back everything in every database.
  • Wrapping unrelated, slow work in one big transaction and blocking other users.
  • Ignoring deadlock errors instead of retrying the transaction.
Your turn

Transfer money safely

Medium

Write a transaction that moves 50 from account id 1 to account id 2, so the money is never lost or duplicated. The accounts table has id and balance columns.

SQL · starter
BEGIN;

COMMIT;
Check your understanding before moving on.
Knowledge checkQuestion 1

What does ROLLBACK do?

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: Debugging queries
Lesson 5 of 480 · 0% of course