Same thing when you forget the WHERE on a DELETE FROM.
Same thing when you forget the WHERE on a DELETE FROM.
(Of course every effort not to be on the SQL shell of a production server in the first place should be taken, but sometimes you need a sledgehammer and nothing else will work.)
I find I remember to do that because of the direct benefit (getting a sneak preview of what I'm going to delete), but it also means I end up thinking twice about the WHERE statement, so I'm much less likely to miss it out or get it dramatically wrong.
select *
-- delete x
from Table x
where x.whatever = 1
That way by default it's just a select, and then AFTER you verify the result set you can highlight from the delete on and then run the query (as long as you're in a shell that will run only the highlighted part. I was working in SMS.) This was a common idiom where I worked.Unfortunately when I was working as a PHP programmer, I once made a typo in a variable name, a variable that had my WHERE clause in DELETE...
Back then I fixed it with a box of chocolates and flowers.
Even if you add the WHERE, but put it on a second line and only run the first, the transaction will help...
Of course, if it's going to lock the data, do all of the statements together: BEGIN TRAN UPDATE ... WHERE ... SELECT ... WHERE .... -- show that the update worked ROLLBACK
Then run the actual statement
BEGIN TRAN
DELETE FROM ...
SELECT FROM ...
ROLLBACK TRAN -- things look bad, itchy finger, etc
COMMIT TRAN -- things look good, skip previous line
That, and I have 15-minute backups for all databases I care about."Only let me update 5 rows at a time." or somesuch.
I now usually type the command out-of-order.
So I'll type:
where user_id = $f00 limit 10;
then prepend the "update foo set bar = " to it...
Thank goodness for daily backups.
For starters, DELETE FROM should never be allowed without a WHERE clause. DBs should simply define that as malformed sql.