What this course is, and how to use it
This is the eighth course in University Computer Science: databases 数据库. It covers how to describe a real situation as tables (relations), ask exact questions of them, keep them consistent when many users work at once, and control who may see what.
A limit, stated once: this is a study course, not a degree. The teaching schema is an original university-enrolment database, and every query and output in this handout was run against it (in SQLite, with the same result every time).
- Units 8.1–8.3 model and shape the data: ER diagrams, relational algebra and SQL, and normalisation.
- Units 8.4–8.5 make it fast and safe: indexes and query plans, transactions and concurrency.
- Unit 8.6 controls it: security and data governance.
The habit to build: every claim about data is a query you can run. Each unit's numbers come from the sample schema described here.
Relational modelling
Why it matters. The model decides everything that follows: what can be asked, what must be checked, and what can go wrong. A good schema is a set of true sentences about the situation it describes.


The idea.
- An entity 实体 is a kind of thing we keep records of (a Student).
- A relationship 联系 connects entities (a Student enrolls in a Course).
- The cardinality 基数 of each end, one or many, decides the keys and tables. A many-to-many relationship becomes its own table of foreign-key pairs.

Why keys exist. A primary key 主键 identifies each row uniquely,
for example student_id in Student. A foreign key 外键 refers to a
primary key: Enrollment.student_id must name a real student. The
database enforces this referential integrity 引用完整性, so no
enrolment can point to a student who does not exist. Our teaching
schema:
Department(dept_id PK, name, building)
Student(student_id PK, name, dept_id FK)
Course(course_id PK, title, dept_id FK, credits)
Enrollment(student_id FK, course_id FK, term, grade,
PRIMARY KEY (student_id, course_id, term))
Worked example 1: putting a rule in the schema. Rule: a student may
enrol in a course at most once per term. The rule lives in the key:
Enrollment has PRIMARY KEY (student_id, course_id, term), so a second
insert of the same three values is refused by the database itself, not
by the application. A rule in the schema is a rule the database keeps.
Worked example 2: the join path. Which students take a department's courses?
- Join Student to Enrollment on
student_id. - Join Enrollment to Course on
course_id. - Join Course to Department on
dept_id.
That is three joins, each following a foreign key. The sample data has 8 students, 6 courses and 14 enrolments, so the join path gives 14 rows before any filtering.
Common mistakes.
- Storing a student's name inside Enrollment. The name is then repeated, and a change must be made in many places.
- Using a column in one of the tables for a many-to-many relationship, instead of a separate junction table.
- Choosing a key that can change. Email addresses change; generated ID numbers do not.
Summary. Entities become tables. Relationships become foreign keys or junction tables, and the cardinality decides which. Keys carry the rules, and the database then enforces them.
Relational algebra and SQL
Why it matters. SQL is the everyday working language of the data industry. At its heart are five algebra operators with exact meanings. If you know the algebra, you can read every query as a pipeline.

The idea. The five operators:
| operator | symbol | what it does |
|---|---|---|
| selection 选择 | σ | keeps rows, e.g. $\sigma_{\text{credits} = 15}$ |
| projection 投影 | π | keeps columns, e.g. $\pi_{\text{name}}$ |
| join 连接 | ⋈ | combines two tables on a condition |
| union | ∪ | rows in either table |
| set difference | − | rows in the first table but not the second |
Many SELECT statements can be represented using these operators, but queries may also require grouping, aggregation, ordering or outer joins.

Why WHERE comes before GROUP BY, and HAVING after. SQL clauses run in a fixed order:
- FROM builds the set of rows;
- WHERE filters rows;
- GROUP BY puts rows into groups;
- HAVING filters groups;
- SELECT chooses the columns;
- ORDER BY sorts.
So WHERE grade = 'A' keeps rows before grouping, and
HAVING COUNT(*) >= 2 keeps whole groups. A filter on an aggregate in
WHERE makes no sense (the groups do not exist yet), and the database
rejects it.
Worked example 1: one query, read as algebra.
SELECT c.title, COUNT(*) AS n
FROM Course c JOIN Enrollment e ON c.course_id = e.course_id
WHERE c.credits = 15
GROUP BY c.title
HAVING COUNT(*) >= 2
ORDER BY n DESC;
As algebra: join Course and Enrollment, select credits = 15, group by
title, keep groups of size $\ge 2$, and project the title with the
count. On the sample data the result is Databases | 3: one 15-credit
course, with three enrolments.
Worked example 2: the outer join keeps the blanks. List every
course with its number of enrolments. A plain join drops the 2 courses
that have no enrolments. A LEFT JOIN keeps them, with NULLs: 6 rows,
2 of them with n = 0 (COUNT(e.student_id) counts only values that
are present). The type of join decides the meaning of the answer; it is
not a matter of style.
Common mistakes.
- Filtering on an aggregate in WHERE. Use HAVING.
- Counting rows when you meant values.
COUNT(*)counts rows;COUNT(col)skips NULLs. - Forgetting DISTINCT when projecting a column from the "many" side. The 14 enrolment rows give 14 student ids, with some repeated.
Summary. Five operators, one pipeline. The clause order has meaning: WHERE filters rows, HAVING filters groups. The type of join decides which rows survive.
Normalisation
Why it matters. A table that is not normalised invites three kinds of problem (anomalies):
- an insert anomaly 插入异常: a fact cannot be stored without an unrelated one;
- an update anomaly 更新异常: a fact stored many times must be changed everywhere;
- a delete anomaly 删除异常: deleting one fact deletes another.
Normalisation removes them by splitting tables along their dependencies.

The idea. A functional dependency 函数依赖 $A \to B$ means that each value of A determines exactly one value of B.
| normal form | condition |
|---|---|
| second normal form 第二范式 (2NF) | first normal form, and no non-key attribute depends on only part of a candidate key |
| third normal form 第三范式 (3NF) | in every nontrivial dependency, the left side is a superkey or the right side is part of a candidate key |
| Boyce–Codd BC 范式 (BCNF) | in every nontrivial dependency, the left side is a superkey |

Why 3NF removes the anomalies. Take the table
Enroll(student, course, title, dept, building), with key
(student, course). It has these dependencies:
course → title: depends on part of the key;title → dept → building: a chain (a transitive dependency).
Update anomaly: a course's title appears in every enrolment row, so if you change it in one row, you may miss ten others. Split by the dependencies:
Course(course, title, dept),Dept(dept, building)andEnroll(student, course). This removes the part-key dependency from Enroll.- Because
title → deptstill holds, Course is not yet in 3NF. Split it intoCourse(course, title)andTitle(title, dept).
With the stated dependencies, the four tables that result are in BCNF.
Worked example 1: grading the form. Take
Room(building, room, capacity, projector_type) with key
(building, room). If all rooms in a building have the same projector
type, then building → projector_type. This breaks 2NF, and so 3NF: a
non-key attribute depends on only part of the candidate key. Split the
table into Building(building, projector_type) and
Room(building, room, capacity). The projector fact is then stored
once.
Worked example 2: when to stop. A warehouse report table stores each
order_line and also a running total for each order. The total can be
calculated from the lines, but calculating it for every view costs more
than the risk of storing it. Planned denormalisation, with a trigger
that keeps the total up to date, is a fair engineering choice once you
understand the normal form. Normalise to reason clearly; denormalise
when measurements justify it.
Common mistakes.
- Calling a table 3NF while one non-key column still determines another.
- Splitting so finely that every query joins five tables, without measuring the cost.
- Forgetting that the anomalies are symptoms. The real problem is the repeated fact.
Summary. Functional dependencies decide the split. For 2NF, remove part-key dependencies; for 3NF in simple single-key examples, remove chains. For BCNF, every nontrivial dependency has a superkey on the left. State the dependencies before you judge a decomposition.
Indexes and query plans
Why it matters. A query that reads a million rows to find ten is a design failure. The fix is not more hardware; it is an index the planner can use.
The idea. A B-tree B 树 index keeps keys sorted in a balanced tree where each node has many children. Our teaching tree (order 4, 15 keys) finds any key in $\lceil \log_4 15 \rceil = 2$ node reads, against up to 15 reads for a scan. The query plan 查询计划 is the pipeline the database chooses to run: a scan or an index, the order of the joins, and the method for each step.

The fan-out arithmetic. A node with $k$ keys points to $k + 1$ children, so a tree of order $m$ has a fan-out of about $m$. A tree of height $h$ holds about $m^h$ keys. With a fan-out of 100, three levels hold $100^3 = 10^6$ keys: one row in a million found in 3 node reads. Every insert keeps the tree balanced (full nodes split, and the split moves upwards), so this limit holds for every key, not just lucky ones.
Worked example 1: reading a plan.
EXPLAIN QUERY PLAN SELECT title FROM Course WHERE credits = 20;
- Without an index, the plan reads
SCAN Course. - After
CREATE INDEX idx ON Course(credits), it readsSEARCH Course USING INDEX idx (credits=?).
On 6 rows, both are instant. On 6 million rows, the scan reads 6 million rows, while the search reads about 4 nodes (a fan-out of 100 covers $10^6$ keys in 3 levels, so six million keys need 4). The plan, not the text of the query, decides the cost.
Worked example 2: the cost on writes. Every index adds work to every insert and delete. Our schema with 3 indexes updates 4 structures for each insert (the table and 3 trees). A log table with 5 indexes and 10 million inserts a day maintains $5 \times 10^7 = 50$ million index entries every day. Index what you query, drop what you do not, and measure.
Common mistakes.
- Indexing every column. Writes pay for reads that never happen.
- Expecting the planner to use an index on a calculated value.
WHERE UPPER(name) = …cannot use a plain index onname. - Reading the query instead of the plan.
Summary. A B-tree trades fan-out for height: $m^h$ keys in $h$ reads. The plan shows what really happens. Every index is a loan that the writes pay back.
Transactions and concurrency
Why it matters. Two bank clerks update one balance at the same time. Without transactions, the database can keep parts of two different transfers, and money is lost without anyone noticing.
The idea. A transaction 事务 happens completely or not at all. Its guarantees are called ACID:
| letter | property | meaning |
|---|---|---|
| A | atomicity 原子性 | all or nothing |
| C | consistency 一致性 | the rules (constraints) still hold afterwards |
| I | isolation 隔离性 | transactions running together do not see each other's half-done work |
| D | durability 持久性 | a committed change survives a crash |
Under serializability 可串行化, the result of running transactions together equals the result of running them in some order, one after another. Weaker isolation levels 隔离级别 allow more anomalies in return for more concurrency: read uncommitted, read committed, repeatable read and serializable.

The lost update, again. T1 reads the balance, 100. T2 reads 100. T1 writes 90 (a withdrawal of 10). T2 writes 120 (a deposit of 20). The withdrawal of 10 has disappeared: this is the banking version of the race in unit 7.3.
Two-phase locking 两段锁 (2PL) has two phases: first a transaction only takes locks; once it releases its first lock, it may not take any new one. This guarantees conflict serializability for transactions that follow the protocol. Strong strict 2PL also holds every lock until the transaction commits or aborts. Transactions can still deadlock; a detector may then abort one of them so that it can try again.
Worked example 1: is the schedule allowed?
R1(A) R2(A) W2(A) W1(A): T1's write overwrites T2's. This is a lost update, and the schedule is not serializable.R1(A) W1(A) R2(A) W2(A): this equals T1 then T2, run one after the other, so it is allowed.
Worked example 2: the dirty read. At read uncommitted, T2 reads the value 90 that T1 has written but not yet committed. T1 then rolls back. T2 has acted on a value that never really existed.
- Read committed prevents this: reads see only committed data.
- Repeatable read also makes a second read of the same row return the same value.
- Serializable also prevents phantoms (new rows that appear between two reads of the same query).
Each level is a promise about which anomalies can still happen.
Common mistakes.
- Long transactions that hold locks while waiting for user input. They invite deadlock.
- Treating isolation and consistency as the same thing. C is about the constraints; I is about running together.
- Leaving out the retry loop because deadlock happens "rarely". It happens at the busiest times.
Summary. ACID: all or nothing; constraints kept; transactions isolated from one another; commits survive a crash. Serializable isolation makes concurrent execution equivalent to some serial order. Isolation levels name the anomalies you accept. 2PL gives serializability, at the cost of waiting.
Security and data governance
Why it matters. A database holds information that people cannot afford to leak. Most large data breaches of recent years came from weak access control, not from broken encryption.
The idea.
- Authentication 认证 proves who you are.
- Authorisation 授权 decides what you may do.
- The principle of least privilege 最小权限原则 shapes both: each account gets only the permissions its job needs.

SQL injection, and how to stop it. Suppose a query is built by pasting in the user's text:
"... WHERE name = '" + input + "'"
With the input ' OR '1'='1, the query matches every row, and worse
inputs can delete tables. Parameterised statements 参数化语句 send
the values separately from the SQL text, so a value can never change
the structure of the query. Table names, column names and other dynamic
SQL need separate controls: parameters do not protect SQL that is still
built by joining strings.
Worked example 1: grants that fit the job. The teaching grants:
GRANT SELECT ON Student TO reader;
GRANT SELECT, INSERT ON Enrollment TO clerk;
The clerk account can read and add enrolments, but cannot delete one or read any other table. If someone steals a clerk session, the damage is limited to what the grant allows. Remove grants when a person's job changes, not on audit day.
Worked example 2: governance is a loop. Data governance 数据治理 means four things, repeated:
- classify the data (public, internal, sensitive);
- give each set of data an owner;
- decide how long to keep it;
- audit who uses it.
For example, the sensitive grade column is encrypted on disk, every
access is logged, and a review every three months removes grants that
are no longer needed. The access model stays correct in real life only
because this loop keeps running.
Common mistakes.
- Connecting the application as the owner account. Every bug then runs with full power.
- Auditing reads but not grants. Permissions slowly pile up.
- Treating encryption as access control. It protects data on disk, not against someone with a valid login.
Summary. Authenticate, then authorise with least privilege. Parameterise every query. Classify, give owners, set retention and audit: governance is the loop that keeps the model true.