Understanding Transaction Management in Netezza
In database systems like Netezza, transaction management plays a crucial role in maintaining data consistency. This article will guide you through the basics of transaction management, including BEGIN, COMMIT, and ROLLBACK statements.
What are Transactions?
A transaction is a logical unit of work that consists of one or more SQL statements. Each transaction follows an ACID (Atomicity, Consistency, Isolation, Durability) property to ensure data integrity.
BEGIN Statement
The BEGIN statement marks the beginning of a new transaction in Netezza. All subsequent DML statements within this transaction are executed as part of that specific transaction until either a COMMIT or ROLLBACK command is issued.
BEGIN TRANSACTION;
COMMIT Statement
The COMMIT statement saves all changes made within the current transaction to the database and releases the lock on the data, making it accessible to other transactions.
COMMIT TRANSACTION;
ROLLBACK Statement
The ROLLBACK statement discards all changes made within the current transaction, restoring the database to its state before the transaction began.
ROLLBACK TRANSACTION;
Example Scenario
Consider a table named emp
with two columns: id
and salary
. Suppose we want to transfer half of the salary from employee A to employee B, but we want this operation to be atomic - either both changes should occur together or none at all. Here's how you can do it using transactions in Netezza:
BEGIN TRANSACTION;
-- Transfer half of the salary from employee A to employee B
UPDATE emp SET salary = salary - 500 WHERE id = 'A';
UPDATE emp SET salary = salary + 500 WHERE id = 'B';
IF ROWCOUNT() <> 2 THEN
ROLLBACK TRANSACTION;
ELSE
COMMIT TRANSACTION;
END IF;
Transaction Parameters
The BEGIN/COMMIT/ROLLBACK
commands take the optional input parameters, WORK or TRANSACTION
– and have no effect on the transactions.