TCL Commands in MySQL

Transaction Control Language (TCL) commands in MySQL are used to manage transactions in the database. Transactions allow you to execute a series of SQL statements as a single unit of work, ensuring that the database remains in a consistent state. The primary TCL commands in MySQL are START TRANSACTION, COMMIT, ROLLBACK, and SAVEPOINT.

1.START TRANSACTION
Begins a new transaction.

START TRANSACTION;

2. COMMIT

Saves all changes made during the current transaction. Once a COMMIT is issued, the changes are permanent and visible to other transactions.

COMMIT;

3. ROLLBACK

Reverts all changes made during the current transaction. This command is used to undo changes if an error occurs or if the transaction needs to be aborted.

ROLLBACK;

4. SAVEPOINT

Sets a point within a transaction to which you can later roll back. This is useful for creating sub-transactions or checkpoints within a larger transaction.

SAVEPOINT savepoint_name;


5. ROLLBACK TO SAVEPOINT

Rolls back the transaction to the specified savepoint, undoing changes made after that savepoint was set.

ROLLBACK TO SAVEPOINT savepoint_name;


6. RELEASE SAVEPOINT

Removes a previously defined savepoint. Once a savepoint is released, you cannot roll back to it.

RELEASE SAVEPOINT savepoint_name;


Example
-- Begin a new transaction
START TRANSACTION;

-- Insert a new customer
INSERT INTO Customers (name, age) VALUES ('Tom Hardy', 40);

-- Create a savepoint
SAVEPOINT sp1;

-- Insert a product for the new customer
INSERT INTO Products (customer_id, name) VALUES (LAST_INSERT_ID(), 'Product X');

-- Rollback to the savepoint
ROLLBACK TO SAVEPOINT sp1;

-- Insert another product for the new customer
INSERT INTO Products (customer_id, name) VALUES (LAST_INSERT_ID(), 'Product Y');

-- Commit the transaction
COMMIT;

Explanation
START TRANSACTION: Begins a new transaction.
INSERT INTO Customers: Inserts a new customer into the Customers table.
SAVEPOINT sp1: Creates a savepoint named sp1.
INSERT INTO Products: Attempts to insert a product for the newly added customer.
ROLLBACK TO SAVEPOINT sp1: Rolls back the transaction to the savepoint sp1, undoing the insertion of the first product.
INSERT INTO Products: Inserts a different product for the newly added customer.
COMMIT: Commits the transaction, saving all changes made since the transaction started.

Using TCL commands allows you to ensure that a series of operations either complete successfully as a whole or leave the database unchanged if any part of the transaction fails. This is crucial for maintaining data integrity and consistency in your database.

Comments

Popular posts from this blog

KTU DBMS LAB CSL 333 BTech S5 - Dr Binu V P

Procedures in PL/SQL

Cursors in PL/SQL