🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › SQL and PostgreSQL Database Development › Lesson 7
TEC-WEB46-04 · Lesson 7 · 13 clock hours · demo

Transactions, Constraints, and Data Integrity

Objective. Students will use BEGIN, COMMIT, ROLLBACK, and SAVEPOINT to manage transactions and explain how ACID properties protect data integrity.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

What Is a Database Transaction?

A transaction is a sequence of one or more SQL statements that PostgreSQL treats as a single unit of work. Either every statement in the unit succeeds and its changes are permanently saved, or none of them are. This all-or-nothing behavior is what makes transactions essential for any application where related changes must stay consistent—bank transfers, order processing, seat reservations, and so on.

In PostgreSQL you mark the boundaries of a transaction with three core commands:

If a fatal error occurs inside a transaction block before you issue `COMMIT`, PostgreSQL automatically rolls back the entire block when the session ends or when you issue `ROLLBACK`.

ACID Properties

The acronym ACID describes the four guarantees a reliable database engine must provide.

Atomicity — All statements in a transaction succeed together or fail together. No partial updates are visible. In the bank-transfer example, debiting one account and crediting another must both succeed; a failure in the middle leaves neither change applied.

Consistency — A transaction moves the database from one valid state to another valid state. CHECK constraints, NOT NULL constraints, foreign key constraints, and UNIQUE constraints enforce the rules that define "valid." PostgreSQL checks constraints at the end of each statement (or at the end of the transaction for deferred constraints).

Isolation — Concurrent transactions do not interfere with each other in unexpected ways. PostgreSQL provides several transaction isolation levels (READ COMMITTED, REPEATABLE READ, SERIALIZABLE) that control how much one transaction can see of another's uncommitted work. The default is READ COMMITTED, meaning a transaction sees only data committed before each individual statement runs.

Durability — Once PostgreSQL confirms a `COMMIT`, the changes survive crashes, power failures, and restarts. PostgreSQL achieves this through its write-ahead log (WAL).

Using SAVEPOINT

A savepoint creates a named checkpoint inside an open transaction. You can roll back to that checkpoint without discarding work done before it.

```sql

BEGIN;

INSERT INTO orders ...; -- step 1

SAVEPOINT after_order; -- checkpoint

INSERT INTO order_items ...; -- step 2, may fail

ROLLBACK TO SAVEPOINT after_order; -- undo only step 2

INSERT INTO order_items ...; -- retry step 2

COMMIT; -- save step 1 and corrected step 2

```

Savepoints are especially useful in longer scripts where you want to recover from a specific error without restarting the entire transaction.

Constraints and Data Integrity

Constraints are rules enforced by PostgreSQL at the table level. They are the first line of defense for data integrity, independent of application code.

When a constraint violation occurs inside a transaction, PostgreSQL raises an error. In psql the entire transaction block is then in an aborted state; no further statements execute until you issue `ROLLBACK` (or `ROLLBACK TO SAVEPOINT` if you set one before the violation).

A Bank-Transfer Scenario

Consider transferring $200 from account 101 to account 202. Without a transaction:

```sql

UPDATE accounts SET balance = balance - 200 WHERE id = 101;

-- crash here leaves 101 debited and 202 uncredited

UPDATE accounts SET balance = balance + 200 WHERE id = 202;

```

With a transaction:

```sql

BEGIN;

UPDATE accounts SET balance = balance - 200 WHERE id = 101;

UPDATE accounts SET balance = balance + 200 WHERE id = 202;

COMMIT;

```

If anything fails between `BEGIN` and `COMMIT`, a `ROLLBACK` (explicit or automatic) restores both accounts to their original balances.

Isolation Levels and Concurrent Access

Isolation problems have standard names:

Set the isolation level immediately after `BEGIN`:

```sql

BEGIN;

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

...

COMMIT;

```

Safety and Best Practices

Key terms9

TransactionA sequence of SQL statements executed as a single unit of work; either all statements commit or none do.
ACIDThe four properties—Atomicity, Consistency, Isolation, Durability—that a reliable database must guarantee for transactions.
COMMITThe SQL statement that permanently saves all changes made within the current transaction block to the database.
ROLLBACKThe SQL statement that discards all changes made within the current transaction block, restoring the prior database state.
SAVEPOINTA named checkpoint inside an open transaction; allows partial rollback to that point without discarding earlier work in the same transaction.
Isolation LevelA setting that controls how much a transaction can see of concurrent uncommitted changes; PostgreSQL levels include READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.
ConstraintA rule defined on a table column or set of columns (NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK) that PostgreSQL enforces to maintain data validity.
Dirty ReadReading data written by another transaction that has not yet committed; prevented by PostgreSQL's default READ COMMITTED isolation level.
Write-Ahead Log (WAL)PostgreSQL's mechanism for durability: changes are recorded to a log before being applied to data files, ensuring committed data survives a crash.
In class: Instructor demonstrates a bank-transfer scenario (debit one account, credit another) with and without transaction wrapping; students reproduce the demo and intentionally simulate a mid-transaction failure to observe the rolled-back state. · Students write a transaction script that inserts records across three related tables and includes a SAVEPOINT; they deliberately trigger a constraint violation after the savepoint and roll back only to the savepoint, then commit the valid portion. · Complete a written ACID worksheet: for each of 10 real-world scenarios (e.g., double-booking a seat, concurrent balance reads), identify which ACID property is at risk and which PostgreSQL feature (constraint, transaction isolation level, lock) addresses it.
Materials: Bank-transfer demo script (instructor-provided), PostgreSQL Transaction Isolation documentation, ACID worksheet, psql
Check: Students demonstrate a live transaction scenario chosen at random from a set of five; they must execute it correctly, trigger and handle a rollback, and verbally explain what each statement does; pass = all steps executed correctly with correct verbal explanation.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Database concepts / data integrity
1. A bank-transfer script debits account A and then crashes before crediting account B. Which ACID property ensures neither change persists?
SQL fundamentals
2. Which SQL statement permanently writes all changes made since BEGIN to the database?
SQL fundamentals / transaction management
3. A developer sets a SAVEPOINT named 'sp1' after inserting a header record, then attempts to insert a detail record that violates a FOREIGN KEY constraint. What is the correct next step to preserve the header record?
Database concepts / transaction isolation
4. PostgreSQL's default transaction isolation level is READ COMMITTED. Which anomaly does this level specifically prevent?
Database concepts / transaction isolation
5. A user re-runs the same SELECT inside a single transaction and gets a different result because another session committed a new row in between. Which isolation level would prevent this phantom read?
SQL fundamentals / transaction management
6. A constraint violation occurs inside an open transaction block in psql. What is the state of the transaction after the error message appears?
Database concepts / data integrity
7. Which PostgreSQL feature most directly provides the Durability guarantee for committed transactions?
Database concepts / data integrity and concurrency
8. An airline reservation system must prevent two concurrent transactions from both booking the last available seat. Which combination of PostgreSQL features best addresses this?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.