Yesterday I was trying to update a status flag on a couple MySQL records. I've learned to always select the dataset first to make sure the correct records are going to be updated. When writing the SQL update I copied and pasted the WHERE part of the select and ran the command. It errored out and so a quick review made it look like I had missed an AND. So the SQL looked something like this:
UPDATE table SET flag = 1 AND m = 123 AND s = 888 which updated nearly 5 years worth of data and 100K records by nuking the actual flag value. I was able to essentially restore the flag from a backup but it got me thinking about strategies to prevent oneself from being your own worst enemy. Doesn't have to be SQL related. Thanks!
People screw up. I think it is better to make sure that you are always working over a safety net.<p>Safety nets for developers include automated tests, rolling out upgrades to a 'pre-production' clone of your real server before doing the real upgrade, and keeping your code in version control so you can reverse mistakes quickly.<p>For database work, not working on the production database, lots of backups, and using transactions all work for me, but some databases support Point In Time recovery if you have it turned on.<p>But what works best is doing code reviews, including reviews of SQL that is going to be executed against the database. Two heads are better than one.
Missing the condition on the UPDATE statement is a classic. I blame the SQL standard which has most of its syntax backwards. It should be FROM <table> WHERE <conds> UPDATE <variables>.<p>Anyway I dont think you can prevent screwups in general. The only thing you can do is have systems in place which mitigate the consequences of screwups. Like unit tests and backups.
I often do a SELECT first using the same WHERE to make sure I am updating the correct rows. Also on my staging system I use a subset of the production database so that I can test destructive queries like this before running them on the production database.