Transaction Control Language (TCL): Managing Data Safely

UPI Study › Courses › Database Programming › Free lessons › Lesson 6.5 Free with a free account

Transaction Control Language (TCL): Managing Data Safely

Database Programming · Chapter 6: Data Retrieval and ModificationSection 6.5 · lesson 39 of 7610 min · free with a free account

← Removing Records with the DELETE StatementNext lesson: Trimming Text with SQL TRUNCATE String →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Using COMMIT, ROLLBACK, savepoints, and isolation levels to protect data changes.

  • Explain the four ACID properties of a transaction
  • Group related changes with BEGIN, COMMIT, and ROLLBACK, including savepoints for partial undo
  • Compare transaction syntax and default isolation levels in MySQL and SQL Server
  • Identify dirty, non-repeatable, and phantom reads and the isolation levels that prevent them

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,200 words). Read along, or search it.

Opening Question

A Points Transfer Interrupted by a Crash

Leo Park develops the application for Lantern Books, our fictional bookstore. Elena transfers fifty reward points to Dara, requiring two updates. What if a crash follows the deduction, before the credit? Transactions protect the operation; our code must still implement the correct arithmetic.

Table Setup

A Combined Balance of 370 Points

Our disposable database uses the canonical customers. These points and transfers are fictional teaching values. Dara has sixty points and Elena has three hundred ten. Their combined balance is three hundred seventy, which a correct transfer must preserve. Run the setup. Constraints protect declared rules; they do not automatically enforce this combined total.

Definition

Atomicity, Consistency, Isolation, and Durability

ACID names four guarantees. Atomicity accepts the unit together, or undoes it together. Consistency means moving between valid states. Constraints help, while correct application logic must preserve business rules such as the combined balance. Isolation controls interaction with concurrent work, according to the chosen level. It is not a promise that every possible reading is protected. Durability preserves acknowledged committed work under configured storage guarantees. A transaction log or journal supports recovery; durability does not replace a backup.

Worked Example

A Trial Transfer Rolled Back

Begin opens our explicit SQLite transaction. Both changes belong to that unit, rather than two independently committed statements. Our own connection can read its pending work. Commit would accept the unit; rollback discards its changes instead. Run this trial. Before rollback, Dara has one hundred ten and Elena has two hundred sixty. The later query restores sixty and three hundred ten. Rollback abandons this trial; we have not crashed the database. The transaction keeps both updates provisional until that decision.

Dialect Comparison

START TRANSACTION and BEGIN TRANSACTION

These reference spellings differ by server. MySQL uses start transaction; SQL Server uses begin transaction. Both offer commit and rollback. MySQL requires transactional tables, normally InnoDB. Changes to a nontransactional engine such as MyISAM cannot be undone by rollback. Transaction control language, or TCL, names these boundary commands. Grouping statements does not automatically validate their business meaning.

Autocommit

Standalone Statements Commit Themselves

In default autocommit operation, each successful standalone statement ends its own transaction. A later rollback cannot undo that already committed work. An explicit transaction groups statements without changing the permanent session setting. These other switches request transactions automatically; always finish them deliberately. MySQL reports its autocommit setting, and switching it back on commits pending work. SQL Server implicit mode starts a transaction for qualifying statements. Do not leave a transaction open while waiting for user input. Pending work can retain resources and block other sessions; gather decisions first, then keep the unit short.

DDL and Nesting

Implicit Commits and Nested Transaction Counts

Ordinary MySQL table definition commands commonly commit implicitly. Temporary creation and dropping are exceptions, yet those operations still cannot be rolled back. Many SQL Server definition statements are transactional. Its nested begin statements increase a counter; an inner commit reduces it, without independently saving the work. Here the counts are one, two, one, then zero. The full rollback undoes the unit; only an outermost commit would make it permanent.

Savepoints

Partial Rollback to a Named Marker

A savepoint is a named marker inside a transaction. We grant Asha ten points, then place the marker after that bonus. The next update incorrectly deducts points across Pune. Rollback to the marker undoes that later work, while keeping the earlier bonus provisional. Release removes the marker, not the surrounding transaction. Commit is still needed to accept the retained change. Run it. Asha finishes with one hundred thirty; Chen and Farid remain at two hundred forty and ninety-five. Partial undo kept the intended bonus.

Dialect Comparison

Savepoint Commands in MySQL and SQL Server

MySQL spells these commands savepoint, rollback to savepoint, and release savepoint. SQL Server uses save transaction and rollback transaction with the marker name. Rollback to leaves the transaction open. Commit or full rollback clears markers; a missing marker errors. SQL Server has no release equivalent. In SQLite and MySQL, rollback to removes later markers. MySQL replaces a reused name; SQL Server rolls back to its most recent matching name.

Quick Check

Release Does Not Commit

Ben starts with eighty-five points. This fresh script adds two adjustments, releases a marker, then requests a full rollback. What will the final query print? Pause and predict. Eighty-five points. Releasing an inner marker did not commit the surrounding transaction, so the full rollback removes both adjustments. Ninety-five would require keeping both additions. Eighty-eight would keep only the second addition; the rollback here keeps neither.

Concurrency Problems

Dirty, Non-Repeatable, and Phantom Reads

A dirty read uses another transaction's uncommitted value. If that writer rolls back, a report has relied on work that never became committed data. A non-repeatable read sees a changed value when reading the same row again, after another transaction commits an intervening update. A phantom read sees a changed matching set, after another transaction commits an insertion or deletion. These are different concurrency problems.

Isolation Levels

Four Standard Isolation Levels

The standard minimum for read uncommitted permits all three anomalies. Starting a transaction at that level does not prevent dirty reads. Read committed prevents dirty reads, but another committed change can alter a later reading within the same transaction. Repeatable read also prevents non-repeatable reads, while its standard minimum still permits phantoms. A product may provide stronger guarantees. Serializable also prevents phantoms, making concurrent work equivalent to some serial ordering. Greater protection can increase waiting or require retries.

Server Defaults

Default Isolation in MySQL and SQL Server

MySQL InnoDB defaults to repeatable read; plain consistent reads share a snapshot. SQL Server defaults to read committed, using locks or versions according to configuration. Set MySQL's next-transaction level before beginning; the session form affects subsequent transactions. SQL Server's setting persists for the session, and its user-options command reports it. SQL Server also offers snapshot isolation, requiring database enablement. Read committed snapshot enables versioned read-committed reads; SQLite does not expose this four-level server switch.

Locking

Shared Locks, Exclusive Locks, and Versions

In a basic locking model, shared data locks can coexist. An exclusive request conflicts with another session's shared or exclusive lock on that resource. A reader may wait for a writer, or read an earlier committed version. Versioned reads avoid many data-lock waits, while schema conflicts can still block them. Write protection lasts until the transaction finishes, though mechanisms differ. Other sessions may read a committed version or wait, according to their isolation and configuration.

Deadlocks

Two Sessions Waiting on Each Other

Imagine session A holds Asha's row and waits for Dara. Session B holds Dara's row and waits for Asha: a cycle, called a deadlock. The database detects that cycle and aborts a victim transaction. Ordinary waiting can end when a holder finishes; the cycle needs intervention. Acquire rows in a consistent order and keep transactions short. Retry the entire aborted unit with bounded backoff, accounting for side effects outside the database.

Quick Check

A Committed Transfer That Loses Points

A different transfer starts with Farid at ninety-five and Ben at eighty-five. Their application runs this script, and both updates succeed. What combined balance will the query print? Add up both balances after the script finishes. Pause and predict. One hundred seventy-five points. The deduction and credit differ, so five points disappear even though the whole transaction commits. One hundred eighty is the intended invariant, not the result. Atomicity kept the statements together; correct business logic still required equal transfer amounts.

Key Takeaways

Transactions Need Correct Business Logic

Group related changes into one transaction, and choose commit or rollback deliberately. Savepoints allow partial undo without silently accepting the surrounding unit. Choose isolation for the concurrency problem, then keep lock-holding work short. A deadlock retry must repeat the aborted unit, with appropriate limits. Leo can protect a transfer and check its arithmetic. Transactions enforce guarantees; the application must still express the intended business rule.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Transaction Control Language (TCL): Managing Data Safely

What are the ACID properties of a database transaction?
ACID stands for atomicity, consistency, isolation, and durability. Atomicity means all of a transaction's changes take effect or none do. Consistency means a committed transaction moves the database from one valid state to another under its declared rules. Isolation keeps concurrent transactions from seeing each other's unfinished work, to a degree set by the isolation level. Durability means committed changes survive a crash, typically through a transaction log.
What is a savepoint in SQL?
A savepoint is a named marker inside a transaction that allows a partial rollback. In MySQL, SAVEPOINT after_bonus sets the marker, and ROLLBACK TO SAVEPOINT after_bonus undoes only the later changes while the transaction stays open. SQL Server uses SAVE TRANSACTION after_bonus and ROLLBACK TRANSACTION after_bonus. The kept work still needs a final COMMIT, and a full ROLLBACK discards everything, including work done before the savepoint.
What is the difference between read committed and repeatable read?
Read committed prevents dirty reads but allows non-repeatable reads, so rereading a row in the same transaction can show another session's newly committed change. Repeatable read also prevents non-repeatable reads, although the SQL standard still allows phantom rows to appear in range queries. SQL Server defaults to read committed, MySQL's InnoDB defaults to repeatable read, and serializable is the standard level that also prevents phantoms.
Can ROLLBACK undo a statement that already ran in autocommit mode?
No, in autocommit mode each standalone statement commits as soon as it succeeds, so a later ROLLBACK has nothing to undo. Start an explicit transaction first: START TRANSACTION in MySQL, BEGIN TRANSACTION in SQL Server, or BEGIN in SQLite. Even inside a transaction, MySQL DDL statements such as CREATE TABLE commit implicitly, and changes to nontransactional MyISAM tables cannot be rolled back.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →