How to test an SQL Update statement before running it?

前端 未结 9 1220
野趣味
野趣味 2020-12-23 20:29

In some cases, running an UPDATE statement in production can save the day. However a borked update can be worse than the initial problem.

Short of using a test datab

相关标签:
9条回答
  • 2020-12-23 20:57

    In addition to using a transaction as Imad has said (which should be mandatory anyway) you can also do a sanity check which rows are affected by running a select using the same WHERE clause as the UPDATE.

    So if you UPDATE is

    UPDATE foo
      SET bar = 42
    WHERE col1 = 1
      AND col2 = 'foobar';
    

    The following will show you which rows will be updated:

    SELECT *
    FROM foo
    WHERE col1 = 1
      AND col2 = 'foobar';
    
    0 讨论(0)
  • 2020-12-23 20:57

    Not a direct answer, but I've seen many borked prod data situations that could have been avoided by typing the WHERE clause first! Sometimes a WHERE 1 = 0 can help with putting a working statement together safely too. And looking at an estimated execution plan, which will estimate rows affected, can be useful. Beyond that, in a transaction that you roll back as others have said.

    0 讨论(0)
  • 2020-12-23 20:58

    I know this is a repeat of other answers, but it has some emotional support to take the extra step for testing update :D

    For testing update, hash # is your friend.

    If you have an update statement like:

    UPDATE 
    wp_history
    SET history_by="admin"
    WHERE
    history_ip LIKE '123%'
    

    You hash UPDATE and SET out for testing, then hash them back in:

    SELECT * FROM
    #UPDATE
    wp_history
    #SET history_by="admin"
    WHERE
    history_ip LIKE '123%'
    

    It works for simple statements.

    An additional practically mandatory solution is, to get a copy (backup duplicate), whenever using update on a production table. Phpmyadmin > operations > copy: table_yearmonthday. It just takes a few seconds for tables <=100M.

    0 讨论(0)
提交回复
热议问题