'Can I use Postgres transactions only for write queries and use read queries without transaction?

What happens if I use transactions for write operations but don't use those for read operations? My use case:

  1. get some data1 from db (without transaction)
  2. create some data2 using data1 (with transaction)
  3. get some data3 from db (without transaction)
  4. create some data4 using data2 and data3 (with transaction)
  5. If no error commit otherwise rollback.

Is it something wrong that I am not using transaction for the 2 read queries?



Solution 1:[1]

Edit/Add/Delete Records

A Transaction is used when you want to ensure that a bunch of row edit/add/delete queries are committed together to the db. In other wards, you want to ensure that all sql commands in that bunch runs successfully or don't commit any of the commands. E.g. you are saving a new record for a users table and a users address table together, but you might not want to write to the users table if the address table record fails for some reason. In this case you would use a transaction for both commands.

Read Records

If you understand the above, you know you don't need transactions for read sql commands.

Was the answer helpful? Consider marking the answer tick and upvoting. Thanks ?

Solution 2:[2]

If that sequence is fine or not depends on your requirements. With your current procedure, the following could happen:

  • if you encounter an error before step 2 finishes, nothing has changed

  • if you encounter an error before step 5 finishes, you have only data2, but not data4

  • if no error happens before step 5 has completed, you have data2 and data4

If that is fine for you, there is no problem with what you are doing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nazim
Solution 2 Laurenz Albe