Archive for the ‘SQL’ Category
SQL Tip: How to Avoid Fundamental Mistakes by Using Transactions
Tuesday, July 27th, 2010When 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
START TRANSACTION; -- select the data before change SELECT * FROM table_name WHERE some_id=5; -- change the data UPDATE table_name SET quantity=quantity+1 WHERE some_id=5; -- select the data after change, and see if everything went alright SELECT * FROM table_name WHERE some_id=5; -- undo the change ROLLBACK;
SQL Server
BEGIN TRAN; -- select the data before change SELECT * FROM table_name WHERE some_id=5; -- change the data UPDATE table_name SET quantity=quantity+1 WHERE some_id=5; -- select the data after change, and see if everything went alright SELECT * FROM table_name WHERE some_id=5; -- undo the change ROLLBACK TRAN;
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).