您的两个陈述的组合:
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