1

我正在使用以下查询将列“DEPARTMENT”添加到表“EMPLOYEE”中。

ALTER TABLE EMPLOYEE ADD DEPARTMENT varchar(15);

然后使用以下查询将 DEPARTMENT 更新为“Technology”

update EMPLOYEE set DEPARTMENT = 'Technology' where DEPARTMENT is null;

由于记录数量有限,这在开发环境中似乎运行良好,但在 Prod like Environment 中需要将近 1 个小时,因为在 Prod 中有大约 2000 万条记录要更新,这是不可接受的。

我们正在考虑修改更新查询以删除 where 条件,如下所示。

update EMPLOYEE set DEPARTMENT = 'Technology';

这会有帮助吗?还是有另一种方法来优化这个查询?

注:使用oracle 11g数据库

4

1 回答 1

6

您的两个陈述的组合:

ALTER TABLE EMPLOYEE ADD DEPARTMENT varchar(15);

                  +

update EMPLOYEE 
    set DEPARTMENT = 'Technology' 
  where DEPARTMENT is null;

等于

 ALTER TABLE EMPLOYEE ADD DEPARTMENT varchar(15) default 'Technology' not null;

当您使用 Oracle 11g 时,您将几乎在眨眼之间添加一个新列并为该列分配一个默认值,因为当新列被定义为not nullOracle 在数据字典中维护该列的默认值时,它不再是需要更新每一行。此外,在您开始插入新行或更新列值之前,新添加的具有默认值的列不会占用空间department

简单演示:

SQL> create table big_table(
  2    col_1 number,
  3    col_2 varchar2(100)
  4  )
  5  ;
Table created

/* x2 for the sake of demonstration we just insert 600000 rows*/
SQL> insert into big_table(col_1, col_2)
  2    select level
  3         , dbms_random.string('l', 11)
  4      from dual
  5     connect by level <= 300000
  6  ;
300000 rows inserted

SQL> commit;
Commit complete

SQL> exec dbms_stats.gather_table_stats(user, 'BIG_TABLE');

PL/SQL procedure successfully completed

SQL> select count(*) from big_table;

  COUNT(*)
----------
    600000

添加新列 + 使用默认值更新

SQL> alter table big_table add department varchar2(10);
Table altered


SQL> set timing on;

SQL> update big_table set department='Technology';

600000 rows updated

Executed in 28.719 seconds

添加NOT NULL具有默认值的新列

SQL> alter table big_table 
  2    add department2 varchar2(15) default 'Technology' not null;

Table altered


Executed in 0.015 seconds
于 2013-10-22T11:19:15.857 回答