Autocommit in SQL: A Quick Overview
Introduction
In relational databases, which we’re discussing here, every query that modifies data is wrapped in a transaction. If you weren’t aware of this, take a look at the following query:
Even though this example doesn’t explicitly use START TRANSACTION and COMMIT, the query is still placed within a transaction and is automatically committed.
This happens thanks to the “autocommit” option, which automatically wraps your query in a transaction and commits it.
Remember, when the “autocommit” option is enabled, you cannot use the ROLLBACK operation. Of course, if your query encounters an error, the database will automatically perform a rollback, so changes won’t be saved.
Did you know that DML stands for Data Manipulation Language? It refers to a set of SQL commands used to modify data in a database, such as INSERT, UPDATE, and DELETE.
Information on the autocommit option
You don’t need to worry about manually starting and committing transactions because autocommit is enabled by default .
In PostgreSQL autocommit is disabled by default.
The autocommit setting works at the session level, meaning that enabling or disabling it won’t affect queries executed by another user.
How to enable autocommit
You can enable autocommit with the following statement:
How to disable autocommit
You can disable autocommit with this statement:
Starting a transaction will also disable autocommit, like this:
How to enable or disable autocommit in PHPStorm
During development, we often use database clients. Here’s an example using the PHPStorm IDE. As shown in the screenshot below, there is a “TX: ...” selection option.
Auto - the autocommit mode described in this article.
Manual - equivalent to autocommit = 0, where we need to manually execute COMMIT or ROLLBACK to save or undo changes.
Summary
Even though autocommit is a basic concept, it's essential to understand how your database handles transactions by default. Knowing these fundamentals helps maintain data consistency and control, especially during error handling and development.