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

Mr.*_*r.Y 37 sql oracle

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

ALTER TABLE Person
ADD(CONSTRAINT personpk PRIMARY KEY(PersonId))
Run Code Online (Sandbox Code Playgroud)

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

e.g: 
CREATE TABLE Person(
PersonId NUM(20) NOT NULL,
...
Run Code Online (Sandbox Code Playgroud)

eao*_*son 41

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        
Run Code Online (Sandbox Code Playgroud)

所以,不,您不需要将主键列指定为NOT NULL.


wol*_*lφi 15

是的,正如@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
Run Code Online (Sandbox Code Playgroud)

正如所料,col1可以为空,col2为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
Run Code Online (Sandbox Code Playgroud)

如果禁用或删除主键,则两列都将恢复为原始状态,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
Run Code Online (Sandbox Code Playgroud)