Sobes.tech
Middle

If a transaction is rolled back, will the log table record made via a regular INSERT be preserved?

sobes.tech AI

Answer from AI

If a transaction is rolled back, all changes made within that transaction, including INSERTs into the log table, will also be undone and not saved in the database.

This is because operations within a transaction are atomic: either all changes are committed or all are rolled back.

If you need to save a log entry regardless of the main transaction rollback, you typically use:

  • External logging mechanisms (e.g., writing to a file or a separate logging system).
  • Separate transactions for logging, which are committed independently.

Example:

BEGIN TRANSACTION;

INSERT INTO main_table VALUES (...);

-- Logging in a separate transaction
BEGIN TRANSACTION;
INSERT INTO log_table VALUES (...);
COMMIT TRANSACTION;

-- If the main transaction is rolled back, the log_table entry will remain
ROLLBACK TRANSACTION;

Thus, a regular INSERT into a log table within a rollbacked transaction will not be saved.