Home >Database >Mysql Tutorial >SQL Transactions: Ensuring Data Integrity and Consistency
A transaction in SQL is a sequence of one or more SQL operations that are executed as a single, logical unit of work. Transactions ensure data consistency, integrity, and reliability within a database, even in the face of system failures or errors. They follow the ACID properties to maintain database stability.
Atomicity:
Ensures that all operations within a transaction are completed successfully. If any operation fails, the entire transaction is rolled back to its initial state.
Consistency:
Ensures the database transitions from one valid state to another. Transactions must respect all defined rules, such as constraints and triggers.
Isolation:
Ensures that multiple transactions occurring simultaneously do not interfere with each other. Each transaction operates as if it were the only one in the system.
Durability:
Ensures that once a transaction is committed, its changes are permanent, even in the event of a system crash.
BEGIN TRANSACTION;
COMMIT;
ROLLBACK;
SAVEPOINT SavePointName;
ROLLBACK TO SavePointName;
BEGIN TRANSACTION; -- Deduct from Account A UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1; -- Add to Account B UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2; -- Check for errors and commit the transaction IF @@ERROR = 0 COMMIT; ELSE ROLLBACK;
Transactions can be nested, but only the outermost COMMIT will finalize the changes. Each ROLLBACK, however, affects the entire transaction hierarchy.
BEGIN TRANSACTION;
COMMIT;
ROLLBACK;
Isolation:
Transactions don’t interfere with each other. Isolation levels include:
Durability:
Once committed, changes are permanent. A COMMIT ensures data is saved, even in a crash.
Transactions are a cornerstone of database systems, ensuring data reliability, consistency, and correctness across critical operations.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of SQL Transactions: Ensuring Data Integrity and Consistency. For more information, please follow other related articles on the PHP Chinese website!