Field note
ch2
The Relational Model
Outline:
- Structure of Relational Databases
- Database Schema
- Keys
- Schema Diagrams
- Relational Query Languages
- The Relational Algebra
Basic Structure
Formally, given sets a relation is a subset of . This, a relation is a set of n-tuples () where rach .
!!! example
- name = {Wu, Mozart, Gold, Singh, ...} // set of all instructor names
- dept_name = {Music, Physics, Finance, ...} // set of all department names
- salary = {40000, 80000, 87000, 90000, ...} // set of all salaries
Then r = {
(Wu, Music, 40000),
(Mozart, Music, 80000),
(Gold, Physics, 87000),
(Singh, Finance, 90000) }
is a relation over $name \times dept\_name \times salary$
Relation Schema and Instance
- are attributes
- is a relation schema
- Example:
- A relation instance defined over schema is denoted by
- The current values a relation are specified by a table
- An element of relation is called a tuple is represented ny a in a table.
Attributes
- The set of allowed values for each attribute is called the domain(域) of the attribute.
- Attribute values are (normally) required to be atomic (indivisible)
- The special value NULL is a member of every domain and represents an unknown or undefined value.
- The null value causes complications in the definition of operations.
??? note “Atomic”
An attribute value is atomic means it cannot be divided into smaller components. For example, a name attribute must be of type string instead of a structure containing first name and last name.
??? note “NULL value”
In C language, how do we define a NULL value? For ```int age```, we may say ```age = -1``` to represent a NULL value. For ```int temperature```, we may say ```temperature = -999``` to represent a NULL value. But we don't have a universal way to represent NULL value.
So in SQL, we use the keyword ```NULL``` to represent a NULL value for any type of data.
Relations are Unordered
Order of tuples is irrelebant (tuples may be stored in an arbitrary order)
Database Schema
- Database schema is the logical structure of the database.
- Database instance is a snapshot of the data in the database at a given instant in time.
Example:
- Schema:
- Instance:

Keys

- Let
- K is a superkey(超键) of R if values for K are sufficient to identify a unique tuple of each possible relation .超键可以唯一确定一个元组。
- Example: and are both superkeys of
- Superkey K is a candidate key(候选键) if K is minimal.
- Example: is a candidate key of
- One of the candidate keys is selected to be the primary key(主键).
- Foreign key(外键) constraint from attributes A of relation r1 to the priamry key B of relation r2 states that on any datebase instance, the value of A for each tuple in r1 must also be the value of B for some tuple in r2.
- 在任何数据库实例中,r1 中每个元组对 A 的取值必须是 r2 中某个元组对 B 的取值。
- 如上图大学数据库模式图中, 的 是一个外键,它指向 的 。
- Another example:

- Referential integrity(参照完整性) constraint requires that values appearing in specified attribute(s) A of any tuples in the referencing relation r1 also appear in specified attribute(s) B of at least one tuple in the referenced relation r2.
- 引用关系的任意元组中的指定属性 A 的值也必须出现在被引用关系的至少一个元组的指定属性 B 中。

Schema Diagrams
We can draw a schema diagram to represent the schema of a database.

Relational Query Languages
- Procedural vs. non-procedural, or declarative
- “Pure” languages:
- Relational algebra(关系代数)
- Tuple relational calculus(元组关系演算)
- Domain relational calculus(域关系演算)
- The above 3 pure languages are equivalent in computing power.
- We will concentrate on relational algebra.
- Not Turing-machine equivalent
- Consist of 6 basic operations
Relational Algebra
Six basic operators:
- select:
- project:
- union:
- set difference:
- Cartesian product(笛卡尔积):
- rename:
Select Operation
!!! example
<font size = 5>relation r:</font>

<font size = 5>$\sigma_{A = B \ \wedge \ D > 5}(r)$</font>

- Notation:
- is called the selection predicate
- Defined as:
- where is a formula in propositional calculus consisting of terms connected by: (and), (or), (not)
- Each term is one of: =, , , , ,
- Example of selection:
Project Operation
!!! example
<font size = 5>relation r:</font>

<font size =5>$\pi_{A, B}(r)$</font>

- Notation:
- are attributes of
- Note that the result of a projection is a set, so duplicate tuples are eliminated.
- Example of projection:
Union Operation
!!! example
<font size =5>relation r, s:</font>

<font size = 5>$r \cup s$</font>

- Notation:
- Defined as:
- For to be valid.
- must have the same arity(元数)(same number of attributes)
- The attribute domains must be compatible(兼容)(example: column of deals with the same type of values as does the column of )
- Example: to find all courses taught in the Fall 2009 semester, or in the Spring 2019 semester, or in both
Set difference
!!! example
<font size = 5>relation r, s:</font>

<font size = 5>$r - s$</font>

- Notation:
- Defined as:
- Set difference must be taken between compatible relations.
- and must have the same arity.
- Attribute domains of and must be compatible.
- Example: to find all courses taught in the Fall 2009 semester, but not in the Spring 2019 semester
Cartesian-Product
!!! example
<font size = 5>relation r, s:</font>

<font size = 5>$r \times s$</font>

- The Cartesian-product operation(denoted by ) allows us to combine information from any two relations.
- Nitation:
- Defined as:
- Assume that attributes of and are disjoint.(That is, )
- If attributes of and are not disjoint, then renaming must be used.
Composition of Operations


Rename Operation
- Allows us to name, and therefore to refer to, the results of relational-algebra expressions.
- Example: renames the result of expression as .
- If a relation-algebra expression has arity , then
returns the result of expression under the name , and with the attributes renamed to .
Example Queries
-
Find the names of all instructors in the Physics department, along with the course_id of all courses they have taught
- Query 1:
- Query 2:
-
Find the names of all instructors in the Physics department, along with the course_id and title of all courses they have taught
- Query:
-
Find the largest salary in the university
- Step 1:find instructor salaries that are less than some other instructor salary(i.e. not maximum)
- Using a copy of instructor under a new name d.
- Step 2:Find the largest salary
- 我们想比较薪水,就需要能够两两比较。则薪水相乘,然后选择小于的部分,再从原来的薪水中减去这部分,就得到最大的薪水。
- Step 1:find instructor salaries that are less than some other instructor salary(i.e. not maximum)
Additional Operations
- Set intersection:
- Natural join:
- Semijoin:
- Assignment:
- Outer join: ⟕ , ⟖ , ⟗
- Division Operator:
Set-Intersection Operation
!!! example
<font size = 5>relation r, s:</font>

<font size =5>$r \cap s$</font>

- Notation:
- Defined as:
- Assume:
- have the same arity
- Attribute domains are compatible
- Note:
- 只是方便了我们表达,并不能增加数据库的查询能力
Natural Join Operation
!!! example
<font size = 5>relation r, s:</font>

<font size = 5>$r \Join s$</font>

- Notation:
- Let and be relations on schemas and respectively.Then, is a relation on schema obtained as follows:
- Consider each pair of tuples from and from
- If and have the same value on each of the attributes in , add a tuple to the result, where
- has the same value as on attributes of
- has the same value as on attributes of
- Example:
- Result schema =
- 实际上就是将两张表中自动匹配相等的字段,然后将这两张表合并成一张表
- 同样只能简化表达,不能增加查询能力
??? info “Natural Join and Theta Join”
=== "Natural Join"
- Natural join is associative:$r \Join (s \Join t) = (r \Join s) \Join t$
- Natural join is commutative:$r \Join s = s \Join r$
=== "Theta Join"
- Theta join is a generalization of natural join
- In theta join, we can specify any condition
- $r \Join_{\theta} s = \sigma_{\theta}(r \times s)$
- Example: $r \Join_{r.A = s.B} s$
Outer Join
- An extension of the join operation that avoids loss of information.
- Computes the join and then adds tuples form one relation that does not match tuples in the other relation to the result of the join.
- Uses null values:
- null signifies that the value is unknown or does not exist
- All comparisons involving null are(roughly speaking) false by definition.
!!! example
<font size = 5>instructor</font>

<font size = 5>teaches</font>

<font size = 5>$instructor \Join teaches$</font>

<font size = 5>$instructor$ ⟕ $teaches$</font>

<font size = 5>$instructor$ ⟖ $teaches$</font>

<font size = 5>$instructor$ ⟗ $teaches$</font>

- ⟕ =
- ⟖ =
- ⟗ ⟕ ⟖
- 只是简化表达,不能增加查询能力
Semijoin Operation(半连接)
- Notation:
- Is a subset of , in which every tuple matches at least ont truple in under the condition
- Defined as:
- 计算两个关系 和 之间的连接,但他只返回满足连接条件的**左表()**中的元组。
select name
from instructor
where exists ( select *
from teaches
where teaches.ID = instructor.ID and teaches.year = 2022)
select name
from instructor
where ID in (select teaches.ID
from teaches
where teaches.year = 2022)
Assignment Operation
- The Assignment operation() provides a convenient way to express complex queries.
- Write query a a sequential program consisting of
- a series of assignments
- followed by an expression whose value is displayed as a result of the query
- Assignment must always be made to a temporary relation variable.
- Write query a a sequential program consisting of
Division Operation
!!! example
<font size = 5>relation r, s:</font>

<font size = 5>$r \div s$</font>

中有1,2两个元组,我们到 中查看 列,找到包含 中所有元组的 值。然后返回 值。
- We can write as:
!!! example “Another Example”
<font size = 5>relation r, s:</font>

<font size = 5>$r \div s$</font>

Extened Relational-Algebra-Operations
- Generalized Projecttion
- Aggregate Functions
Generalized Projection
我们可以在投影操作中加入算数运算,如下:
Example:
Aggregate Functions and Operations
- Aggregate functions are functions that take a collection of values as input and return a single value.
- Common aggregate functions:
- COUNT
- SUM
- AVG
- MIN
- MAX
- Aggregate operation in relational algebra
- is a list of attributes on which to group (can be empty)
- Each is an aggregate function
- Each is an attribute name.
!!! example
=== "sum"
<font size = 5>relation r:</font>

<font size = 5>$\mathcal{G}_{sum(c)}(r)$</font>

=== "avg"
<font size = 5>relation r:</font>

<font size = 5>$\mathcal{G}_{avg(salary)}(instructor)$</font>

- Result of aggregation does not have a name
- Can use rename operation to give it a name
- For convenience, we permit renaming as part of aggregate operation
Modification of the Database
- Deletion
- Insertion
- Updating
Multiset Relational Algebra
- Pure relational algebra removes all duplicates
- Multiset(多重集) relational algebra retains duplicates, to match SQL semantics.
- SQL duplicate retention was initially for efficiency, but is now a feature.
- Multiset relational algebra defined as follows
- Selection: has as many duplicates of a tuple as in the input, if the tuple satisfies the selection.
- projection: ont tuple per inpur tuple, even if it is a duplicate.
- cross product:If there are copies of in , and copies of in , there are copies of in .
- Set operators:
- Union: copies
- Intersection: copies
- Difference: copies
SQL and Relational Algebra
select A1, A2, ..., An
from r1, r2, ..., rm
where P
is equivalent to
select A1, A2, sum(A3)
from r1, r2, ..., rm
where P
group by A1, A2
is equivalent to
select A1, sum(A3)
from r1, r2, ..., rm
where P
group by A1, A2
is equivalent to