START TRANSACTION - MySQL
Overview
START TRANSACTION
initiates a new database transaction. It establishes a savepoint that marks the beginning of a group of database operations that should be treated as a single logical unit. If the transaction is successful, all changes made within it will be committed to the database; otherwise, they will be rolled back.
Syntax
START TRANSACTION [WITH CONSISTENT SNAPSHOT]
Options
- WITH CONSISTENT SNAPSHOT: Ensures that the data read during the transaction is consistent even if other transactions are modifying the same data concurrently.
Examples
Simple Transaction:
START TRANSACTION;
INSERT INTO users (name) VALUES ('John Doe');
COMMIT;
Transaction with Consistent Snapshot:
START TRANSACTION WITH CONSISTENT SNAPSHOT;
SELECT * FROM users WHERE name = 'John Doe'; -- Reads consistent data
...
COMMIT;
Transaction with Rollback:
START TRANSACTION;
INSERT INTO users (name) VALUES ('John Doe');
ROLLBACK; -- Undoes the changes
Common Issues
- Deadlocks: Transactions can deadlock if they try to acquire the same locks in different orders. Use
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
to reduce the risk of deadlocks. - Transaction Aborts: Transactions can abort due to errors, such as duplicate key violations or constraint violations. Handle these errors gracefully and provide informative error messages.
- Long-Running Transactions: Keep transactions as short as possible to avoid the accumulation of locks and potential performance issues.
Integration
- Stored Procedures: Transactions can be used within stored procedures to ensure data consistency across multiple queries.
- Database Triggers: Transactions can be automatically started and committed when triggers are fired.
- Replication: Transactions are replicated to slave servers to ensure data consistency across the cluster.
Related Commands
COMMIT
: Commits the changes made within a transaction.ROLLBACK
: Undoes the changes made within a transaction.SAVEPOINT
: Creates a named savepoint within a transaction.RELEASE SAVEPOINT
: Releases a named savepoint.