Using Transactions in SQL


  Transactions allow you to group multiple operations into a single unit of work. This ensures that all operations complete successfully before committing the changes to the database.


Syntax


The basic syntax for using transactions in SQL is:

  BEGIN
  INSERT INTO Students (NAME, YEAR) VALUES (‘E’,40);
  END


Transactions are important for maintaining data integrity.

In this example, we insert a value into the Students table, but you can add any operation.


Purpose


Transactions are essential to ensure data consistency. For example, they allow:


  • Reverting changes in case of an error.
  • Grouping related operations to ensure all of them complete.
  • Maintaining referential integrity in the database.


Exercises



Interactive Test 1: Drag and Drop

Arrange the transaction statements in the correct order. Drag the items to the corresponding spaces.

Drag in the corresponding order.


Drag the options:

BEGIN
INSERT INTO Students (NAME, YEAR) VALUES (JOHN,40);
END

Completa el código:

______
______
______

Interactive Test 2: Fill in the Blanks

Complete the following SQL code using the appropriate terms.

Fill the Blanks.


BEGIN;
INSERT  Students (NAME, YEAR)  (‘JOHN’,40);
END

Which of the following statements is used to commit a transaction in SQL?