Avoiding errors when running SQL update queries

When working on an update query, I prefer to run it first on a test database to make sure it does what I think it’s going to do—and to make sure I haven’t made a simple mistake. When that’s not possible, however, there is another approach that works pretty well, too: select, then update.

First, I run a query like this with the update portions commented out:

FROM customers
--UPDATE customers
--SET title = 'Mr.'
WHERE id > 123 and id < 150

After I’ve checked the results to ensure I’ll be affecting only the records I intend to change, I comment out the select, from, and order by bits, and uncomment the update and set lines:

--FROM customers
UPDATE customers
SET title = 'Mr.'
WHERE id > 123 and id < 150

By taking this approach, I’m less likely to accidentally update records I didn’t intend to touch.