Preparing your workspace
Transactions group related database operations into a controlled unit that maintains consistency when multiple changes belong together.
PostgreSQL provides strong transactional support. BEGIN starts a transaction, COMMIT makes the changes permanent, and ROLLBACK removes the changes made during the transaction. Transactions are useful when several operations must succeed together. PostgreSQL's transaction model also includes isolation levels that control how concurrent transactions interact. Choosing an appropriate transaction boundary is important because long-running transactions can create contention and affect system performance.
Creating an enrollment and recording a payment reference may need to happen together according to the application's business rules.
BEGIN;
INSERT INTO enrollments (student_id, course_id)
VALUES ('student-1', 'course-1');
INSERT INTO audit_logs (action)
VALUES ('course_enrollment_created');
COMMIT;Both inserts become permanent together when the transaction commits successfully.