Creating a Primary Key on a temp table - When?

后端 未结 9 639
一个人的身影
一个人的身影 2020-12-29 04:16

I have a stored procedure that is working with a large amount of data. I have that data being inserted in to a temp table. The overall flow of events is something like

9条回答
  •  天涯浪人
    2020-12-29 04:48

    When you add PK on table creation - the insert check is O(Tn) (where Tn is "n-th triangular number", which is 1 + 2 + 3 ... + n) because when you insert x-th row, it's checked against previously inserted "x - 1" rows

    When you add PK after inserting all the values - the checker is O(n^2) because when you insert x-th row, it's checked against all n existing rows.

    First one is obviously faster since O(Tn) is less than O(n^2)

    P.S. Example: if you insert 5 rows it is 1 + 2 + 3 + 4 + 5 = 15 operations vs 5^2 = 25 operations

提交回复
热议问题