0
0
MysqlHow-ToBeginner · 3 min read

How to Use COMMIT in MySQL: Syntax and Examples

In MySQL, use the COMMIT statement to save all changes made during the current transaction permanently to the database. After executing COMMIT, the changes cannot be undone by a rollback.
📐

Syntax

The COMMIT statement has a simple syntax:

  • COMMIT; — Saves all changes made in the current transaction.

It ends the current transaction and makes all changes permanent.

sql
COMMIT;
💻

Example

This example shows how to use COMMIT to save changes after inserting a new row into a table.

sql
START TRANSACTION;
INSERT INTO employees (name, position) VALUES ('Alice', 'Developer');
COMMIT;
Output
Query OK, 1 row affected (0.01 sec) Query OK, 0 rows affected (0.00 sec) Query OK, 0 rows affected (0.00 sec)
⚠️

Common Pitfalls

Common mistakes when using COMMIT include:

  • Forgetting to start a transaction with START TRANSACTION; or BEGIN;, so COMMIT has no effect.
  • Not committing after making changes, which leaves the transaction open and locks the affected rows.
  • Assuming COMMIT undoes changes — it actually finalizes them.
sql
/* Wrong: No transaction started, COMMIT does nothing */
INSERT INTO employees (name, position) VALUES ('Bob', 'Manager');
COMMIT;

/* Right: Start transaction, then commit */
START TRANSACTION;
INSERT INTO employees (name, position) VALUES ('Bob', 'Manager');
COMMIT;
📊

Quick Reference

CommandDescription
START TRANSACTION;Begin a new transaction
COMMIT;Save all changes made in the current transaction
ROLLBACK;Undo all changes made in the current transaction
SET autocommit=0;Disable automatic commit mode
SET autocommit=1;Enable automatic commit mode (default)

Key Takeaways

Use COMMIT to save all changes made during a transaction permanently.
Always start a transaction with START TRANSACTION; before making changes you want to commit.
Without COMMIT, changes remain uncommitted and can be rolled back or cause locks.
Remember that COMMIT finalizes changes; it does not undo them.
Use ROLLBACK to undo changes before committing.