1、一致性
一致性包括not null、unique、check
a)Not null
name varchar(20) not null
b)Unique
若是A1, A2...等构成了候选键,能够用unique(A1, A2...)来保证其惟一性,但这些字段仍然可为空,而为空值与任何值都不相等。
c)Check
限制semester的值:
check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)
d)Referential Integrity参照完整性
若是course.dept_name做为外键引用department表,为了保证course.dept_name的取值都存在于department.dept_name,添加参照完整性约束为:
e)foreign key (dept name) references department
2、数据类型和Schemas
a)Date和time
SQL标准规定的time相关类型有:
date ’2001-04-25’
time ’09:30:00’
timestamp ’2001-04-25 10:29:01.45’
字符串形式的日期可使用cast e as t的方式来转换;也可使用extract year/month/day/hour/minute/second from d的方式来单独提取年月日等数据;
还有current_day, current_timestamp(包含时区), localtimestamp(不包含时区的本地时间);
interval类型表示时间的差
b)Default value
create table student
(ID varchar (5),
name varchar (20) not null,
dept name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID));
这里设置了tot_cred的默认值为0
c)建立索引
create index studentID index on student(ID)表示建立了名为studentID的索引,有的数据库产品又进一步区分了汇集索引(clustered)与非汇集索引(nonclustered)
d)大对象类型Large-Object Type
若是要存储声音、图像等数据,数据量可能为KB甚至MB, GB级别,为此SQL提供了两种大对象类型 clob(character large object)和blob(binary...)。不一样数据库的具体实现会有区别,并且实际使用中不推荐使用这些类型,而每每将数据保存在文件系统,并在数据库保存其存放位置。
e)用户自定义类型
容许基于现有的类型来自定义数据类型,好比:
create type Dollars as numeric(12,2);
create type Pounds as numeric(12,2);
自定义类型Dollars和Pounds虽然都是numeric(12,2)类型,但在业务上被认为是不一样的数据类型。
还有一种定义方式为:
create domain DDollars as numeric(12,2) not null;
type和domain的细微的区别在于domain能够同时添加约束如not null,;并且domain也不是彻底的强类型,只要值是兼容的,就能够赋值给domain定义的类型,而type却不行。
e)Create table的扩展
create table temp instructor like instructor;建立了一个与sinstructor有相同结构的表
在编写SQL时,有时会建立临时表并存入数据,这时能够用简化写法:
create table t1 as
(select *
from instructor
where dept name= ’Music’)
with data;
t1表结构与查询结果集相同,若是去掉with data,则只建立schema而不插入数据。
3、受权
权限控制能够针对用户或角色进行数据操纵、schema更新等的控制。
a)分配、撤销受权
分配权限的语法为:
grant <privilege list>
on <relation name or view name>
to <user/role list>;
privilege list包括select, insert, update, delete
对于update,能够设定容许更新某些属性:
grant update (budget) on department to Amit, Satoshi;
相似地,撤销受权语法为:
revoke <privilege list>
on <relation name or view name>
to <user/role list>;
b)角色
基于角色的权限控制不是SQL的专利,不少共享型应用都采用这种受权方式。
create role instructor;
grant select on takes to instructor;
grant dean to Amit;
前面的语句建立了角色instructor,为期分配select from takes权限,而后将Amit纳入instructor角色。在Amit执行查询前,SQL根据它所属角色具备的权限来作控制。
c)关于schema的受权
由于外键会影响后续的更新、删除等操做,因此有必要为外键的建立作权限控制:
grant references (dept name) on department to Mariano;
学习资料:Database System Concepts, by Abraham Silberschatz, Henry F.Korth, S.Sudarshan
数据库