Part 3: Introduntion to SQL¶
1 SQL Parts¶
1.1 DDL (Data-definition language)¶
Domain Types in SQL¶
- char(n): fixed length character string
- varchar(n): variable length character strings, with maximum length n
- int
- smallint
-
numeric(p, d): fixed point number with p digits and d decimal point
numeric(3, 1) 44.5
-
real, doubke precision: machine-dependent precision
- float(n): user-specified precision of at least n digits
Create Table Construct¶
Integrity Constraints in Create Table¶
primary key(a, ...,b)
foreign key(a, ...,b) references r (on delete/update cascate | set null | restrict | set default)
not null
1.2 DML (Data-Manipulation language)¶
Updates to tables¶
-
insert
insert into instructor values('1001', 'John', 'Computer Science', 50000)
-
delete
delete from student
-
drop table
drop table instructor
-
alter
alter table r add A D
alter table r drop A
Basic Query Structure¶
- result of an SQL query is a relation - The selectclause can contain arithmetic expressions involving the operation, +, –, , and /:selectID, name, salary/12
String Operations¶
- %: The % character matches any substring
- _: The _character matches any character
- supports:
- concatenation ("||")
- converting from upper to lower case ("lower()") and vice versa ("upper()")
- finding string length, extracting substrings, etc.
Ordering the Display of Tuples¶
order by name desc/asc //默认asc(升序)
Set Operations¶
默认去重,若不需要:union all
- union: 并
- intersect: 交
- except: 差
NULL Values¶
null 被视为未知量,如 true and unknown = unknown
Aggregate Functions¶
- avg
- min
- max
- sum
-
count: number of values
-
group by
select dept_name, avg(salary) as avg_salary from instructor group by dept_name; having avg(salary) > 42000;
Set Membership¶
-
in / not in
Set Comparison¶
等价于 -
all: 比任何一个都...
!!! hint "some" =some \(\equiv\) in \(\neq\)some \(\not \equiv\)not in
$\neq$all $\equiv$ not in
=all $\not \equiv$ in
- exists / not exists: The exists construct returns the value true if the argument subquery is nonempty / empty.
- unipue: evaluates to “true” if a given subquery contains no duplicates
Subqueries in the From Clause¶
-
With Clause(定义临时表)
-
Scalar Subquery
- a single value is expected
Modification of the Database¶
-
deletion
-
insertion
-
update