SQL Tip: How to Avoid Fundamental Mistakes by Using Transactions
When you plan to apply a big change to a database table, you should always triple check your queries, so nothing will get screwed.
I always use the following approach, in order to preview data before and after a change that’s going to be made over records without having this change committed, so I can refine my queries if I did something wrong:
MySQL
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
SQL Server
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Description
- A transaction is opened
- All current rows are selected, to preview data before change
- The change is being done
- All altered rows are selected, to preview data after change
- The transaction is rollbacked, the change is undone
After you’re sure the change is OK, you can perform it without a transaction, or use COMMIT; (MySQL) / COMMIT TRAN (SQL Server).