我们是否需要为主键指定“not null”?甲骨文/ SQL

时间:2012-12-02 00:56:26

标签: sql oracle

CREATE TABLE Person(
    PersonId NUM(20),
    ...
    )

ALTER TABLE Person
ADD(CONSTRAINT personpk PRIMARY KEY(PersonId))

作为标题,我是否需要为PersonId指定“not null”?或者,如果我将其设置为主键,默认情况下它自动不为空?

e.g: 
CREATE TABLE Person(
PersonId NUM(20) NOT NULL,
...

4 个答案:

答案 0 :(得分:35)

create table mytable (
  col1 number primary key,
  col2 number,
  col3 number not null
);

table MYTABLE created.

select table_name, column_name, nullable 
from user_tab_cols where table_name = 'MYTABLE';

TABLE_NAME                     COLUMN_NAME                    NULLABLE
------------------------------ ------------------------------ --------
MYTABLE                        COL1                           N        
MYTABLE                        COL2                           Y        
MYTABLE                        COL3                           N        

所以,不,你不需要将主键列指定为NOT NULL。

答案 1 :(得分:13)

是的,正如@eaolson所说,你不需要为主键列指定NOT NULL,它们会自动设置为NOT NULL。

但是,如果以后禁用或删除主键,Oracle会跟踪您未明确指定NOT NULL:

create table mytable (
  col1 number,
  col2 number not null
);

select table_name, column_name, nullable
  from user_tab_columns where table_name = 'MYTABLE';

TABLE_NAME   COLUMN_NAME  NULLABLE
------------ ------------ ---------
MYTABLE      COL1         Y
MYTABLE      COL2         N

正如所料,col1可以为空,col2为NOT NULL。主键将两列都更改为NOT NULL:

alter table mytable add primary key (col1, col2);

select table_name, column_name, nullable
  from user_tab_columns where table_name = 'MYTABLE';

TABLE_NAME   COLUMN_NAME  NULLABLE
------------ ------------ ---------
MYTABLE      COL1         N
MYTABLE      COL2         N

如果禁用或删除主键,两列都将恢复为原始状态,co1将再次变为可为空:

alter table mytable disable primary key;

select table_name, column_name, nullable
  from user_tab_columns where table_name = 'MYTABLE';

TABLE_NAME   COLUMN_NAME  NULLABLE
------------ ------------ ---------
MYTABLE      COL1         Y
MYTABLE      COL2         N

答案 2 :(得分:3)

根据定义,主键永远不能为空。 主要目的是唯一地标识记录。 主键是唯一指定行的列的组合。

Null值表示缺乏价值。即使两个记录在同一列中具有NULL,也不会将列值视为相等。

答案 3 :(得分:2)

在大多数DBMS中,由于它是一个主键(并且定义在表中必须是唯一的),因此它肯定不能为空。