约束是对表中数据的强制规定,可以删除不符合的数据。常用的三种约束条件:
— not null
— unique
—primary key
1、非空约束 not null
非空约束是为了保证表中数据不要为空(在添加数据时空值是加不进去的呦),not null只能定义在列中。
not null使用语法:
1)、在创建表的时候:
SQL>create table 表名 (列名 数据类型 not null);
SQL> create table t5 (bu number(9) not null);
Table created.
SQL>create table 表名 (列名 数据类型 constraint 约束名 not null);
2)、在创建后:
SQL>alter table 表名 modify (列名 数据类型 constraint 约束名 not null);
2、唯一性 约束 unique
唯一性约束是把重复的数据删掉,保证数据唯一性(添加数据时要是表里面有的话 就不行喽),unique可以在表中和列中定义。
unique使用语法:
1)、创建表时:
SQL> create table 表名(列名 数据类型 constraint 约束名 unique);
SQL> create table t4 (ni number(10) constraint t4_ni_uk unique);
Table created.
SQL> create table 表名 constraint 约束名 unique (列名);
2)、创建后:
SQL>alter table 表名 add constraint 约束名 unique (列名);
3、主键约束primary key
主键约束(非空且唯一)保证数据非空且唯一(添加数据时要不是空值且没有重复值),primary key可以在表中和列中定义。
primary key使用语法:
1)、创建表时:
SQL>create table 表名(列名 数据类型 constraint 约束名 primary key);
SQL> create table t3 (noo number(9) constraint t3_no_pk primary key);
Table created.
SQL>create table 表名 constraint 约束名 primary key (列名);
2)、创建后:
SQL>alter table 表名 add constraint 约束名 primary key (列名);