EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Transactions in SQL

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » SQL Tutorial » Transactions in SQL

Transactions in SQL

Introduction to Transactions in SQL

Transactions in SQL are a single or consecutive set of processes completed in a rational definite flow that can be performed manually or by creating an automatic database programming. Every transaction in SQL starts as a flow from a particular job and should complete with another working job. If any or all of the jobs are incomplete, the transaction status is said to be ‘fail’. A Transaction is said to be ‘complete’ or ‘success’ if and only if all the jobs are completed successfully.

The transaction, once committed, cannot be a rollback; it can be a rollback only if the transaction is not committed. MYSQL automatically commits the changes to the database if all the queries are executed successfully. To explicitly commit the changes into the database, first, need to disable the auto-commit through the command –

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax: SET autocommit = 0;

Properties of the Transaction

Following are the important properties of the transactions; every transaction must follow these properties.

1. Atomicity

A transaction must be atomic; mean data manipulation should be completed for a certain logical unit. This property ensures that data changes taken place completely; otherwise, roll back the transaction.

2. Consistency

Once the Transaction finishes, All the available records will be consistent throughout the transaction. This property ensures that the database property switched state after a successful commit or not.

3. Isolation

Isolation refers to data changes at a certain logical unit that should not affect on another unit. It allows a transaction to execute independently.

Popular Course in this category
Sale
SQL Training Program (7 Courses, 8+ Projects)7 Online Courses | 8 Hands-on Projects | 73+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (8,975 ratings)
Course Price

View Course

Related Courses
JDBC Training (6 Courses, 7+ Projects)PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

4. Durability

Changes made during transactions should be permanent in the system. In case of a system error, this property also ensures that data changes take place or not.

The above-given property of the transaction is also known as ACID property.

Steps of Transaction

Below are the steps:

1. Begin

A transaction may occur in multiple SQL executions, but all SQL should run at once. If any of the transactions fails, then the whole transaction would be reverted. The statement for starting the transaction is “START TRANSACTION”,, .begins the acronym for the START TRANSACTION.

Syntax: START TRANSACTION;

2. Commit

Commits permanently reflect the changes to the database. The statement for starting the transaction is “COMMIT”.

Syntax: COMMIT;

3. Rollback

Rollback is used to revert the changes, i.e. record will not be changed, It would be in the previous state. The statement for starting the transaction is “ROLLBACK”.

Syntax: ROLLBACK;

4. Savepoint

SAVEPOINT is also a transaction statement. This statement used to create a store point in the system so that the ROLLBACK operation can achieve the state of the savepoint.

5. Release Savepoint

RELEASE SAVEPOINT is a statement to release the savepoint & memory consumed by the system in creating a save point.

Syntax: RELEASE SAVEPOINT SP

Notes – SP was the name of the savepoint when this savepoint was created before the transaction start.

6. Set Transaction

The SET TRANSACTION command is used to specify the transaction attribute, such as the given transaction is a read-only or read-write session.

Syntax: SET TRANSACTION [ READ-WRITE | READ ONLY ];

The transaction is used to perform complex changes in the database. Its mainly used in banking-related information changes into a relational database.

The transaction is supported by the MYSQL engine InnoDB. By default, auto-commit remains enabled; that’s why whenever any SQL executes after execution, commits automatically take place.

Transactions using SQL

Example #1

Banking Transaction: An account debited for 50000 amount from person A saving account & submitted this amount to the loan account of A.

Start Transaction: This start transaction will convert all the SQL queries to a single unit of transaction.

UPDATE `account` SET  `balance` = `balance` - 50000 WHERE user_id = 7387438;

This SQL query deducts the amount from the existing account balance.

UPDATE `loan_account` SET  `paid_amount` = `paid_amount` + 50000 WHERE user_id = 7387438;

This SQL query adds the amount to the user loan account.

Insert into `transaction_details`(`user_id`, ‘amount’)  values (7387438, ‘50000’);

This SQL query inserts a new record into the transaction details table; this table holds the details of all the transactions of the users. If all the query executed successfully, then the COMMIT command needs to be executed as changes need to be permanently stored in the database.

Commit: This commit statement saves changes invoked by a transaction to the database. If any of the transaction fails during the execution, then the ROLLBACK command should be executed to revert the complete transaction.

Rollback: Rollback takes place once any query fails during execution.

Example #2

Inventory Transaction: In the given Items table, 6 items are available.

Inventory Transaction

Executing the following START TRANSACTION statement to start the transaction.

Start Transaction

Now run command SET AUTOCOMMIT = 0;to disable the auto-commit

Set Auto Commit

Now executing the following statement to remove the record from the items table

Transaction in SQL

Now Available record in the table is 4, i.e. records temporary removed from the table items

Available Record

Now executing command ROLLBACK to revert the changes, the deleted record would be available in the table items like as previously before starting the transaction

RollBack

Again if applying the same delete operation, then COMMIT operation after it would be saved permanently in the database

COMMIT

Now we can see that after the ROLLBACK command still, the record was in a new state; it means once the COMMIT operation is performed, changes can not be reverted because it permanently makes changes into the database;

Benefits of using Transaction in SQL

a) Using Transaction improves the performance; when inserting 1000 records using transactions, in that case, time taken would be lesser than normal insertion. As in a normal transaction, every time COMMIT would take place after each query execution & it would increase the time of execution every time while in a transaction, no need to execute COMMIT statement after each SQL query. COMMIT at the end would reflect all the changes to the database permanently at once. Also, If using a transaction, then reverting the changes would be much easier than the normal transaction. ROLLBACK will revert all the changes at once & keep the system in the previous state.

b) The transaction ensures data integrity in the relational database. Most of the database uses multiple tables to maintain the data, and while making updates, there may have been changes in the multiple tables at that time; if any of the SQL queries fail, then the transaction would keep the data unchanged.

Conclusion

Using Transactions is a best practice in information update for a logical unit in a relational database. For transaction implementation database engine should support the transaction like the InnoDB engine. The transaction, as a unit of SQL statements, can be reverted at once using a single ROLLBACK statement. The transaction ensures data integrity & improves database performance.

Recommended Articles

This is a guide to Transactions in SQL. Here we discuss the introduction, properties, steps, examples of transactions in SQL, along with the benefits of using transactions in SQL. You may also have a look at the following articles to learn more –

  1. What is SQL
  2. SQL Management Tools
  3. SQL Views
  4. Types of Joins in SQL Server

SQL Training Program (7 Courses, 8+ Projects)

7 Online Courses

8 Hands-on Projects

73+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Server Versions
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
    • SQL Super Key
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL Window Functions
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite?functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL MOD()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Server Permission
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ADD Column
    • SQL Ranking Function
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • SQL Formatter
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • NoSQ
    • NoSQL Databases List
    • NoSQL Injection
    • NoSQL vs SQL Databases
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

4th of July Offer - SQL Training Program (7 Courses, 8+ Projects) Learn More