/* 创建表 */
create table course
course_id varchar(20),
title varchar(20) not null,
price numeric(5,2) default 100.00,
primary key(course_id));
/* 删除表 */
drop table course;
/* 增加列 */
alter table course add credits numeric(2,0);
/* 删除列 */
alter table course drop credits;
/* 创建视图 */
create view v as <query expression>
/* 插入数据 */
insert into course
values('CS-437', 'Database Systems', 'Comp.Sci.', 4);
/* 删除数据 */
delete from course
where course_id = 'CS-445';
/* 更新数据 */
update instructor
set salary = salary * 1.05
where salary < 70000;
/* 查询数据 */
select distinct dept_name
from instructor
where salary > 80000 and dept_name <> 'Biology';
/* 用 as 给属性别名(as 可以省略)*/
select name as instructor_name from instructor;
/* 用 as 给关系别名(as 可以省略)*/
select * from instructor as T, instructor as S
where T.sarary > S.sarary and S.dept_name = 'Biology';
/* 创建索引 */
create index sid on student(ID);
/* 授予 */
grant <权限列表>
on <关系名或视图名>
to <用户/角色列表>
/* 收回 */
revoke <权限列表>
on <关系名或视图名>
from <用户/角色列表>
/* 创建角色 */
create role instructor;
%
:匹配任意字符串_
:匹配一个字符||
:串联trim()
:去掉后面的空格upper()
、lower()
:转大小写select * from department
where buidling like '%cat\_room%' escape '\';
select * from instructor
order by salary desc, name asc; /* asc 可以省略 */
select * from instructor
where salary between 9000 and 10000;
/* 等价于 salary >= 9000 and salary <= 10000;
也有 not between */
union
intersect
except
(select course_id from section where year = 2009)
union
(select course_id from section where semester = 'Spring')
去并集,会自动去重(union all 不去重)
涉及空值的比较,返回 unknown
判断空值用 is null,不能用 = null
min
、max
、sum
、avg
、count
count(distinct ID)
group by
分组聚集having
分组的限定条件in
集合成员资格, not in
> some
至少比某个大,< all
, >=
, <=
, <>
exists
空关系测试not exists(B except A)
“关系 A 包含关系 B”unique
重复元组存在性测试with
定义临时关系select * from a join b on a.id=b.id;
select * from a natural left outer join b where course_id is null;
create table section
(
course_id varchar(8),
sec_id varchar(8),
/* check 约束,not null 约束*/
semester varchar(6), check (semester in('Fall','Spring')),
year numeric(4,0), check (year>1759 and year < 2100),
room_number varchar(7) not null,
primary key (course_id, sec_id, semester, year),
foreign key (course_id) references course,
)
候选码用 unique 或者 primary key 约束。
create table course(
...
foreign key(dept_name) references department
on delete cascade
on update cascade,
);
cascade代表级联,当删除 department 元组时,course 的对应元组也会被级联删除。 类似的还有 set null、set default。
varchar(n)
char(n)
int
numeric(p,d)
real
double precision
float(n)
时间相关date
time
timestamp
timestamp with timezone
interval
current_date()
当前日期currrent_time()
current_timestamp()
带时区localtime()
本地时间extract(filed from d)
从 date 或 time 类型的 d 中提取year,month,day,hour,minute,second的任意一种select A1, A2, sum(A3)
from r1, r2, ..., rm
where P
group by A1, A2
等价于 \(_{A_1,A_2}\mathcal{G}_{sum(A_3)}(\Pi_{A_1,A_2,\cdots,A_n}(\sigma_P(r_1\times r_2\times \cdots \times r_m)))\)
可以将关系分解为 BCNF 模式集合。