In SQL, is UPDATE always faster than DELETE+INSERT?

前端 未结 15 2187
梦谈多话
梦谈多话 2020-11-29 20:01

Say I have a simple table that has the following fields:

  1. ID: int, autoincremental (identity), primary key
  2. Name: varchar(50), unique, has unique index<
15条回答
  •  清酒与你
    2020-11-29 20:42

    Delete + Insert is almost always faster because an Update has way more steps involved.

    Update:

    1. Look for the row using PK.
    2. Read the row from disk.
    3. Check for which values have changed
    4. Raise the onUpdate Trigger with populated :NEW and :OLD variables
    5. Write New variables to disk (The entire row)

      (This repeats for every row you're updating)

    Delete + Insert:

    1. Mark rows as deleted (Only in the PK).
    2. Insert new rows at the end of the table.
    3. Update PK Index with locations of new records.

      (This doesn't repeat, all can be perfomed in a single block of operation).

    Using Insert + Delete will fragment your File System, but not that fast. Doing a lazy optimization on the background will allways free unused blocks and pack the table altogether.

提交回复
热议问题