我使用以下查询将“DEPARTMENT”列添加到表'EMPLOYEE'。
ALTER TABLE EMPLOYEE ADD DEPARTMENT varchar(15);
然后使用以下查询将DEPARTMENT更新为“技术”
update EMPLOYEE set DEPARTMENT = 'Technology' where DEPARTMENT is null;
由于记录数量有限,这似乎在开发环境中运行良好,但是在Prod之类的环境中花费了近1个小时,因为在Prod中有大约2000万条记录需要更新,这是不可接受的。
我们正在考虑修改更新查询以删除where条件,如下所示。
update EMPLOYEE set DEPARTMENT = 'Technology';
这会有帮助吗?或者有其他方法来优化此查询吗?
注意:使用oracle 11g数据库
答案 0 :(得分: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 null
时,Oracle维护该列的默认值在数据字典中,每行都不再需要更新。此外,新添加的那个具有默认值的方式列不会消耗空间,直到您开始插入新行或更新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