All Revision Notes

COM6002 Big Data Management · Week 3

(Centralized) Relational Database Management Systems (RDBMS): Theories and Concepts

COM6002 · Week 3 · Source: 3-RDBMS.pptx (81 slides)

Contents · 13 sections

🎯 本講重點 (Learning outcomes)

  • 理解 relation (table) 同 join 的概念
  • 用 Big O notation 分析成本(O(1)O(1), O(lg⁡n)O(\lg n), O(n)O(n), O(n2)O(n^2)),識 Big O rules 同 best / worst / average case
  • 掌握 B tree 同 B+ tree 的結構、point search、range query 同成本;index 的 overhead;query plan 同 query optimizer
  • 認識其他 index:R-tree、HNSW、Inverted index
  • 理解 transaction、concurrency control(serial execution、locks、Two-Phase Locking、deadlock、rollback / cascading rollback)
  • 理解 log-based recovery(undo / redo)、blocking vs fuzzy checkpoints,以及 ACID

⭐ 考試必溫 Top-5

  1. B+ tree:結構特點(pointers 只喺 leaf、separator、sibling pointer、balanced)、search 同 range query 步驟、O(lg⁡n)O(\lg n) search & update
  2. Two-Phase Locking (2PL):growing / shrinking phase、readlock / writelock conflict table、deadlock = precedence graph 有 cycle
  3. Log-based recovery:undo incomplete、redo committed;用 log 計 recovery 後的 database 值
  4. Blocking vs fuzzy checkpoints;scan backward 去到邊度停
  5. ACID 四個 property(slide 標明 Very important!)

1. RDBMS overview

Latest trend(db-engines.com ranking):RDBMS dominates the market! 重要 RDBMS:Oracle、MySQL / MariaDB、Microsoft MS SQL、PostgreSQL、IBM DB2、SQLite;Microsoft Access(Not a real powerful RDBMS)。

RDBMS 用 tables 管理 data,Table is called "relation"。Slide 3 例子有三個 tables:

StudentResultModule
Student IDNameMajorStudent IDModule CodeGradeModule CodeModule Name
101101AmyBBA101101COM2006BCOM2103Database Design and Management
101103BobCS101101COM2103ACOM2006Database Management Systems
101106CathyCS101103COM2103A
101106COM2103B

Search & Join

Q:What are the names of students who get A in the module "Database Design and Management"? 資料散落三個 table,所以要 "join" the tables together(用 Student ID 同 Module Code 配對):

Student IDNameMajorModule CodeModule NameGrade
101101AmyBBACOM2006Database Management SystemsB
101101AmyBBACOM2103Database Design and ManagementA
101103BobCSCOM2103Database Design and ManagementA
101106CathyCSCOM2103Database Design and ManagementB

答案:Amy、Bob。(Week 4 會寫成 SQL。)

💡 點解要拆成三個 table?

如果將 module name 寫入每一行 Result,"Database Design and Management" 會重複好多次(redundancy),改名時要改晒所有行,漏改就 inconsistent——即 Week 1 File-based 的問題。拆 table 每樣嘢只記一次,要用時先 join。

2. Efficient search 與 Big O notation

Slide 6 問題:IG 有 3 billion MAU (2026),你的程式每秒可以 loop 100M records,login 時逐個搵要幾耐?

3,000,000,000100,000,000 records/s=30 s (worst case),average≈15 s\frac{3{,}000{,}000{,}000}{100{,}000{,}000\ \text{records/s}} = 30\ \text{s (worst case)},\quad \text{average} \approx 15\ \text{s}

Login 要等 15–30 秒明顯唔接受得 → 需要 index。

2.1 Big O notation

In computer science, we usually use complexity:Big O notation measures the order of the running cost (time / space etc.)。

⭐ 考試重點:Slide 的四個 Big O 例子
ExampleTaskComplexity
1For each student, mark his/her assignmentO(n)O(n) — workload grows linearly with n
2每個學生寫 peer evaluation 俾每個其他學生,老師 mark 晒所有報告O(n2)O(n^2) — n(n−1)n(n-1) 份報告
3Knock-out tournament:每兩個 player 比賽,贏的留低;同時進行的比賽叫一個 roundRounds = O(lg⁡n)O(\lg n);Games = O(n)O(n)(剛好 n−1n-1 場)
4Find any ONE student in the classO(1)O(1) — constant time regardless of n

Note:lg is binary log (base 2);log is base 10。

Worked example(Example 3):n=16n = 16 players → round 1: 8 games, round 2: 4, round 3: 2, round 4: 1 → 4 rounds = lg⁡16\lg 16;games = 8+4+2+1=15=n−18+4+2+1 = 15 = n-1。

🖼️ 圖片內容

Slide 9 有一張 tournament 圖,文字擷取不到。

2.2 Big O rules

⭐ 考試重點:Big O rules
  • 3n2+4n+100⇒O(n2)3n^2 + 4n + 100 \Rightarrow O(n^2):We only care about the highest order term;We don't care about the coefficient
  • We usually consider the average case or the worst case
  • 例子:逐個學生搵 Tom,搵到就停 → Best case O(1)O(1)(第一個就係);Worst case O(n)O(n);Average O(n)O(n)(平均要查一半,n/2n/2 仍然係 O(n)O(n))

3. Index on RDBMS:B tree

Common method:B tree (and its variants)(Bayer et al., 1972)。不同版本概念相近,細節有別;本科講 B tree 同 B+ tree。ExamCost complexity of search:O(lg⁡n)O(\lg n)。

以 IG 為例:log⁡10(3×109)=9.38\log_{10}(3\times10^9) = 9.38(slide 數字);用 binary log,lg⁡(3×109)≈31.5\lg(3\times 10^9) \approx 31.5。即係由 30 秒 linear scan 變成大約幾十步——幾乎即時。

3.1 Structure of B tree(slide 13)

                    [ 11 ]                      ← Root node
             /                 \
        [ 5 | 8 ]           [ 15 | 20 ]         ← Non-leaf nodes
       /    |    \          /    |    \
   [1 3] [6 7] [9 10]  [12 14] [17 19] [21 23]  ← Leaf nodes

Key properties:Items on the left are all smaller;items on the right are all larger。Note:There could be multiple records for each value。喺 B tree,每個 node(包括 root 同 non-leaf)的值本身都係 data。

Example: Finding 15:15 > 11 → go right → 喺 [15 | 20] 搵到,Bingo!(未去到 leaf 已經搵到)
Example: Finding 22:22 > 11 → right;22 > 20 → right;leaf [21 23] 冇 22 → 22 does not exist。

Cost analysis:Best scenario O(1)O(1)(例如搵 11,root 就係);Worst scenario O(lg⁡n)O(\lg n)(slide 寫 O(ln⁡(n))O(\ln(n)),同一個 order)——n 係 distinct values 數目(≤ records 數)。

4. B+ tree

                    [ 13 ]
             /                 \
        [ 5 | 9 ]           [ 17 | 20 ]          ← separators only
       /    |    \          /    |    \
   [1 3]→[5 7]→[9 11]→[13 15]→[17 19]→[21 23]    ← leaf level, → = sibling pointer
⭐ 考試重點:B+ tree 特點(同 B tree 的分別)
  • Record pointers are always at leaf level
  • Values at non-leaf level are separators only:左邊全部 < separator,右邊全部 ≥ separator
  • There is a sibling pointer to the sibling leaf node(方便 range query)
  • Separator 唔一定要存在於 database:例如 20 並唔存在,但仍可做 separator

Finding 15:15 ≥ 13 → right;15 < 17 → left → leaf [13 15],Bingo。(B+ tree 一定要去到 leaf,因為 pointer 只喺 leaf。)

4.1 Range query:find 10–16

  1. Step 1:search the smaller value (10):10 < 13 → left;10 ≥ 9 → right → leaf [9 11],由 11 開始(9 < 10 唔要)
  2. Step 2:Go to siblings:沿 sibling pointer 去 [13 15] → 13、15 都喺範圍;最大值係 16,可能仲有 >15 且 ≤16 的值,所以再去下一個 sibling [17 19];最細已經係 17 > 16 → 停

結果:11, 13, 15。Total number of nodes visited: 5(root, [5|9], [9 11], [13 15], [17 19])。

💡 點解 range query 用 B+ tree?

B tree 的值散落喺唔同 level,range query 要上上落落咁 traverse。B+ tree 所有值都喺 leaf,而且 leaf 已排序 + 有 sibling pointer,搵到起點之後只需要「向右行」,好似喺一本已排序的電話簿揭頁。

4.2 Other key characteristics

  • ExamThe update cost is also O(lg⁡n)O(\lg n)。對比:Binary tree(a well-known data structure)has a linear update cost(樹可以變得唔平衡,worst case 似一條 linked list)
  • Balanced tree:由 root 去任何 leaf 的 path length 都一樣
  • B / B+ tree is for one-dimensional search;可以將多個 attributes 合成一個 attribute(composite key)再用 B+ tree
  • 可以用 USFCA 的 B+ tree visualization 睇 maintenance 同 search 動畫

5. Index design & Query plan

Discussion:要 list 喺某 module 攞 A 的 student IDs,index 應該點建?用 slide 23 的 Result table:

RecordStudent IDModule CodeGrade
R1101101COM6002B
R2101101COM6104A
R3101103COM6104A
R4101106COM6104B
IndexLeaf entries (key → record pointers)
On module codeCOM6002 → R1;COM6104 → R2, R4, R3(同一 key 下的 pointers 次序不受控制;但 leaf 的 keys 係有序的)
On gradeA → R2, R3;B → R4, R1
On (module code, grade)(COM6002, B) → R1;(COM6104, A) → R2, R3;(COM6104, B) → R4

Yes! We can have multiple indices on the same table!

5.1 The overhead of indexing

  • Index requires additional space and maintenance effort
  • Additional space < space of records,因為 index 只存 pointers;record 內容永遠只有一份
  • Is the maintenance effort worth it? Depends on your usage! How often is your index used? Is it necessary?(每次 INSERT/UPDATE/DELETE 都要更新所有相關 index)

5.2 Query plans(Query: Students who get A in COM6104)

⭐ 考試重點:同一 query 有多個 query plan
Plan做法要檢查的 records(本例)
1No index, scan all recordsR1–R4 全部 4 個
2Index on module code → 拎 COM6104 所有 records 再 check gradeR2, R4, R3(3 個)
3Index on grade → 拎所有 A 再 check moduleR2, R3(2 個)
4Index on (module code, grade) → 直接搵 (COM6104, A)R2, R3 — 全部都係答案,冇浪費

5.3 Query optimizer

  • RDBMS 會嘗試搵 optimal query plan:keeps statistics about the database(例如 number of records),automatically pick the "best" plan
  • Note:Don't rely on query optimizer。佢識 rewrite 簡單 pattern(e.g., filter-join query),但 complex queries 好難 rewrite
  • Recommendations:Try to write efficient SQL queries;Build index! Based on your usage

6. Other indices

Index用途重點
R-tree (Guttman, SIGMOD 1984)Multi-dimensional spatial query:Find the object closest to me;objects within 1kmWorst case:Search O(n)O(n)、Update O(n)O(n)
HNSW (Hierarchical Navigable Small World, Malkov et al. 2016)Top-k cosine similarity search on a vector database(approximate nearest neighbor)Example application:RAG in LLM
Inverted indexFull-text (keyword-based) searchThe reverse of a document-to-term mapping

Inverted index 例子:D1 = "He wins",D2 = "She wins",D3 = "I lose":

TermDocument
HeD1
WinD1, D2
SheD2
ID3
LoseD3

搜尋 "win" → 直接得 D1, D2,唔使逐份文件睇。(留意 wins → Win:做咗 stemming / normalization。)

🖼️ 圖片內容

Slide 30 R-tree 有一張空間示意圖,文字擷取不到。

7. Database transaction

Transaction = the basic unit in RDBMS,each transaction may contain several commands。例子:轉帳——(1) Deduct $5,000 from your account;(2) Add $5,000 to your friend's account。Both actions 1 and 2 are done or none is — All or nothing。試想部電腦喺 step 1 後、step 2 前 hang 機:錢就憑空消失。

Transaction structure:Transaction begins → … (all actions) → Commit。Once committed,DBMS 確保 transaction 真係完整做咗;否則 transaction should have no effect to the database。

Challenges:Concurrency control(多個 users 同時用同一 data items,要避免出錯)同 Recovery(系統 fail,例如 power outage,要 recover database contents)。

8. Concurrency control

8.1 Why concurrent execution?

多部 ATM 同時 access central database。如果唔支援 concurrent execution:電腦一次只做一個 transaction → 所有人排隊用一部 ATM,連銀行職員都要等。

8.2 The ATM example(slides 37–47)

Initial:X=100X = 100,Y=100Y = 100。ATM 1 的 transaction:X=X+100X = X + 100, Y=Y−100Y = Y - 100。ATM 2:Y=Y+100Y = Y + 100, X=X−100X = X - 100。(每次 update 要等 database 回 "OK",因為 network 可能 drop message;長時間收唔到 OK 就 resend。)

StepActionXY
1ATM 2 reads Y → 100;ATM 1 reads X → 100100100
2ATM 1: Update X to 200200100
3ATM 1 reads Y → 100200100
4ATM 2: Update Y to 200200200
5ATM 1: Update Y to 0(用舊值 100 − 100)2000
6ATM 2 reads X → 2002000
7ATM 2: Update X to 1001000

Something wrong? Final X=100X = 100, Y=0Y = 0。正確應該係兩個轉帳互相抵銷:X=100X = 100, Y=100Y = 100。ATM 2 對 Y 的 +100 被 ATM 1 覆蓋咗(lost update),總金額由 200 變 100。

8.3 Correct execution = Serial execution

⭐ 考試重點:Definition of a correct execution

Assumption:each transaction is itself correct(brings the DB from a consistent state to another consistent state)。Serial execution:transactions executed one by one → serial execution is correct。不同 serial order 可以有不同結果,但 都算正確。

例子:X=1000X = 1000;T1:X increases by 1%;T2:X decreases by 100。

  • T1 then T2:1000 → 1010 → 910
  • T2 then T1:1000 → 900 → 909

910 同 909 都係 correct results。

點樣確保 correct execution?Two phase locking(Eswaran et al., 1976):ensure multiple transactions executing simultaneously do not corrupt shared data。Other methods:Timestamp ordering、Multi-Version Concurrency Control (MVCC)、Raft algorithm。

8.4 Locking

Make sure no other (active) transaction has a conflict action at the same time。兩種 lock:Readlock(read 之前要攞)同 Writelock(write 之前要攞)。

Transaction 1 (ATM 1):          加 lock 後:
Read(x)                          Readlock(x)  Read(x)
Write(x)                         Writelock(x) Write(x)
Read(y)                          Readlock(y)  Read(y)
Write(y)                         Writelock(y) Write(y)
                                 Releaselocks()

Q:做完 Write(x) 之後已經冇 x 的 action,可唔可以即刻 release x 的 lock?
A(lecturer notes):No. Another transaction may be done between Write(x) and Read(y). If this transaction also has actions on x and y, the result will be incorrect.(佢會見到「X 已轉、Y 未轉」的中間狀態。)

⭐ 考試重點:Lock conflict table

(同一個 variable、由不同 transactions 申請)

ReadlockWritelock
ReadlockNo conflictConflict
WritelockConflictConflict

Lock upgrade:writelock 係 readlock 的 upgraded version;持有 writelock 的 transaction 唔需要再持有 readlock。

8.5 Two-phase locking (2PL)

⭐ 考試重點:2PL
  • Phase 1: growing phase — 只可以攞新 lock,No lock is released
  • Phase 2: shrinking phase — 只可以 release lock,No new lock can be obtained
  • Transaction commits(之後 release locks)

即係:一旦放咗任何一個 lock,就唔可以再攞新 lock。

8.6 2PL example → Deadlock

T1:Read(x), Write(x), Read(y), Write(y)。T2:Read(y), Read(x), Write(x), Write(y)。

StepRequestResultLocks held
1T1 已攞 Writelock(x)、Readlock(y)—W(x) by T1, R(y) by T1
2T2 Readlock(y)OK — readlock does not conflict with another readlock+ R(y) by T2
3T2 Readlock(x)No — readlock conflicts with writelock → T2 waiting
4T1 Writelock(y)(upgrade)No — writelock conflicts with T2's readlock(y) → T1 waiting

T1 等 T2 放 y,T2 等 T1 放 x → 永遠完唔到:呢個就係 deadlock。

有 conflict 時點做?Option 1: wait(等其他 transaction 放 lock);Option 2: rollback(Undo what the transaction has done;declare it failed;retry later)。

⭐ 考試重點:Deadlock detection & rollback
  • 用 precedence graph(wait-for graph):T1 → T2 表示 T1 等緊 T2 持有的 lock
  • A deadlock means that there is a cycle in the graph
  • Slide 60 練習(lecturer notes 答案):Yes — T3 waits for T4, T4 waits for T2, T2 waits for T3 → cycle
  • Rollback 的用途:To resolve a deadlock(揀一個 transaction rollback,打破 cycle)
  • Cascading rollback:其他 transactions 可能已經讀咗呢個 transaction 更新的值,佢哋都要 rollback。例:T1 將 X 1000 → 1010,T2 讀 1010 再減 100 → 910;If T1 rollbacks, T2 must rollback too
🖼️ 圖片內容

Slide 60 precedence graph 的箭咀方向係圖形,只擷取到 node 名(T1–T5);上面答案引用 lecturer notes。請對照原 slide 第 60 頁睇完整的圖。

9. Database recovery

點解要 recovery?Cancelled transaction(user 撳 cancel)、System failure(disk failure, system crash, system errors)。

ExamLog-based recovery is the mainstream method。Core principle:Save to the log before writing to the database system(write-ahead)。

Challenges:How to perform backup without stopping the database? How to make sure all contents before the crash can be recovered?

9.1 What do we put in the log?

Log 成個 database?(唔理 efficiency 都)唔得——the snapshot of a database may be inconsistent:snapshot 嗰刻可能有 T1、T2 的 partial updates。

Failure 發生時:所有 working transactions 同 database 斷聯 → stop processing、rollback、report failure。Slide 65 例子中只有已 commit 的 T3 的效果應該留喺 database。

⭐ 考試重點:Contents of the log
  • Clear record about the start of a transaction
  • Clear record about the commit of a transaction
  • The update contents,兩種做法:
    • Before-after values(e.g., x, 10, 15 — x 由 10 變 15):More storage;more straightforward recovery
    • Delta values(e.g., x, +5):Less storage;need a mechanism to tell if the value on the harddisk is before or after the update

9.2 Example logs(slide 67–69)

Log entry 意思:T3 = start of T3;T3, X, 12 = T3 sets X to 12;T3 commit = end of T3 (commit)。

T3
T3, X, 12
T1
T3, Y, 10
T2
T1, A, 60
T1, B, 30
T3, Z, 8
T2, M, 100
T3 commit
--- Crash ---
Initial database: A=0 B=0 C=0 M=0 N=0 P=0 X=0 Y=0 Z=0

Crash 嗰刻:memory 入面係 A60 B30 M100 X12 Y10 Z8,但 disk 上可能只有 X12 Y10(其他仲喺 memory 未寫落 disk)。

⭐ 考試重點:Recovery actions

Undo incomplete transactions;Redo committed transactions

  • T3 committed → redo:X=12X = 12, Y=10Y = 10, Z=8Z = 8
  • T1、T2 冇 commit → undo:A=0A = 0, B=0B = 0, M=0M = 0

Recovery 後:A=0,B=0,C=0,M=0,N=0,P=0,X=12,Y=10,Z=8A=0, B=0, C=0, M=0, N=0, P=0, X=12, Y=10, Z=8。

9.3 Recovery algorithm

由 log 尾開始,scan the log backwards 搵出 incomplete 同 completed transactions。Q:When do we stop? 要確保所有 completed transactions 都搵到 → scan until the starting point of the log——即成個 log!(如果 log 由 30 年前開始?!)→ 需要 checkpoints。

10. Database checkpoints

⭐ 考試重點:Blocking vs Fuzzy checkpoints
Blocking checkpointFuzzy checkpoint (Non-blocking)
做法Stop all the updates to the database,create a snapshotDo NOT stop the updates;create a snapshot and keep records about what transactions are running
Recovery只需 scan 到最近的 checkpointScan 到最近 checkpoint,再追查 checkpoint 記錄中仍在 running 的 transactions
缺點做 checkpoint 時 database 要停Worst case recovery cost O(n)O(n)(scan 到第一條 log),但實際上幾乎唔會發生——除非 log 好短或者 transaction 長得離譜

10.1 Fuzzy checkpoint example(slides 73–77)

Checkpoint 101 記錄 running:T1, T2;Checkpoint 102:T2, T3, T4;Checkpoint 103:T2, T5;之後 Failure。

  • Scan backwards until Checkpoint 103;All committed transactions before Checkpoint 103 are already in the checkpoint image
  • Only need to chase further for T2 and T5(checkpoint 103 時仍 running)
  • 去到 checkpoint 102:要唔要追 T2 / T3 / T4?T2:Maybe yes;T3: No! T4: No!(佢哋喺 checkpoint 103 已經唔喺 running list,即已完成,效果喺 image 入面)
  • T5 喺邊度開始?喺 checkpoint 102 同 103 之間(102 冇 T5,103 有)
  • T2 / T5 有冇 commit?Depends on whether we see "T2 / T5 commit" in the latest log(checkpoint 103 之後)

10.2 Full example(slides 78–79)

T1
T1, X, 10
T2
            ← Checkpoint 101 (running: T1, T2)
T1 commit
T3
T4
T2, X, 15
T3, Y, 5
T4, Z, 70
            ← Checkpoint 102 (running: T2, T3, T4)
T3 commit
T5
T2, A, 10
T4 commit
T5, Z, 30
            ← Checkpoint 103 (running: T2, T5)
T6
T6, Z, 50
T2, B, 30
T2 commit
T5, X, 10
--- crash ---
🖼️ 圖片內容

原 slide 的 checkpoints 係畫喺時間線上的標記,上面 checkpoint 插入的位置係按每個 checkpoint 記錄的 running transactions 推斷(例如 102 有 T4 冇 T5、103 冇 T4),某條 log 確實落喺 checkpoint 前定後(例如 T5, Z, 30)請對照原 slide 第 78–79 頁的紅 / 綠標示。

分析:

  • T1、T3、T4 喺 checkpoint 103 前 commit → 已在 checkpoint image,唔使理
  • T2:checkpoint 103 後見到 "T2 commit" → committed → redo T2, B, 30。T2 喺 checkpoint 前的 action(T2, X, 15;T2, A, 10)本應 redo,但 as this action is before the checkpoint, the update is always on the harddisk,唔需要真係 redo
  • T5、T6:冇 commit → undo(T5, X, 10;T6, Z, 50;T5, Z, 30)。T5 喺 checkpoint 102–103 之間開始,所以要 scan 返去 T5 的 start 先可以停(slide 79 "We stop here")

Recovery 後(假設 undo 有 before values 可用):X=15X = 15(T2),Y=5Y = 5(T3),Z=70Z = 70(T4),A=10A = 10,B=30B = 30。

⚠️ 常見錯誤

Undo 需要知道 舊值。如果 log 只記新值(例如 "T5, Z, 30"),就要靠 before-after logging("Z, 70, 30")先知 undo 去返 70。呢個就係 slide 66 講 before-after values「more straightforward recovery」的原因。

11. ACID property of database

⭐ 考試重點:ACID(Very important!)
PropertyDefinition (slide)由乜機制保證
AtomicityTransaction is handled in an "all-or-nothing" manner:either the entire transaction is done, or none is doneLog + undo / rollback
ConsistencyAny transaction will bring the database from one valid state to another。例:X=X−50X = X - 50, Y=Y+50Y = Y + 50;Before X=100,Y=100X=100, Y=100 → After X=50,Y=150X=50, Y=150(總和 200 不變)Transaction 本身正確 + 其他三個 property
IsolationIt appears like transactions are executed independentlyConcurrency control(2PL 等),效果等同 serial execution
DurabilityOnce a transaction is committed, its effect stays in the database foreverLog + redo、checkpoints

自我測驗 Self-test

Q1. 一個演算法成本係 5n3+2n2log⁡n+10005n^3 + 2n^2\log n + 1000,Big O 係乜?Knock-out tournament 有 64 個 players,要幾多 rounds、幾多 games?

O(n3)O(n^3)(只取最高次項、忽略係數)。Rounds = lg⁡64=6\lg 64 = 6;Games = n−1=63n - 1 = 63(O(n)O(n))。

Q2. 用 slide 17 的 B+ tree(root 13;[5|9]、[17|20];leaves 1 3 / 5 7 / 9 11 / 13 15 / 17 19 / 21 23),寫出 range query 6–14 的步驟同 visit 了幾多個 nodes。

6 < 13 → left;5 ≤ 6 < 9 → middle child → leaf [5 7],攞 7。Sibling → [9 11]:9, 11;sibling → [13 15]:13(15 > 14,停)。結果 7, 9, 11, 13。Visited:root, [5|9], [5 7], [9 11], [13 15] = 5 nodes(喺 [13 15] 已見到 15 > 14,唔使再去下一個 sibling)。

Q3. B tree 同 B+ tree 有咩分別?點解 B+ tree 更適合 range query?

B+ tree:record pointers 只喺 leaf level;non-leaf values 只係 separators(左 <,右 ≥,可以唔存在於 DB);leaf 之間有 sibling pointers。B tree 每個 node 的值都係 data,搜尋可以喺 non-leaf 停(best case O(1)O(1))。Range query 用 B+ tree 只要搵到起點 leaf,再沿 sibling pointers 向右掃,唔使上落 traverse。兩者 search 同 update 都係 O(lg⁡n)O(\lg n),都係 balanced。

Q4. 要搵「COM6104 攞 A 的學生」,列出四個 query plan,邊個最有效率?Index 有咩代價?

(1) 全表 scan;(2) 用 module code index 再 check grade;(3) 用 grade index 再 check module;(4) 用 composite index (module code, grade) 直接搵——最有效率,冇多餘 records。代價:額外空間(只存 pointers,比 records 細)同每次更新資料的 maintenance effort;值唔值得視乎 usage。Query optimizer 會根據 statistics 揀 plan,但複雜 query 唔好倚賴佢。

Q5. 喺 2PL 下,T1 持有 Writelock(x)。T2 申請 Readlock(x)、T3 申請 Readlock(y)(冇人持有 y 的 lock),結果點?一個 transaction 放咗 lock 之後可唔可以再攞新 lock?

T2 被拒(readlock 同 writelock conflict)→ wait 或 rollback。T3 成功。2PL 下一旦開始 release(shrinking phase)就唔可以再攞新 lock。

Q6. Wait-for graph 有 edges:T1→T2、T2→T3、T3→T1、T4→T1。有冇 deadlock?點解決?

有,T1→T2→T3→T1 形成 cycle。解決:揀 cycle 入面一個 transaction(例如 T3)rollback、undo 佢的 actions、稍後 retry;如有其他 transaction 讀過佢寫的值,要 cascading rollback。T4 只係等緊,唔喺 cycle。

Q7. Log:T1 / T1,A,5 / T2 / T2,B,7 / T1 commit / T3 / T3,A,9 / T2,C,4 / crash。Initial 全部係 0。Recovery 後 A、B、C 係幾多?

T1 committed → redo A=5A = 5。T2、T3 冇 commit → undo:B=0B = 0、C=0C = 0、A 嘅 T3 update 撤回 → A=5A = 5(T1 的值)。結果 A=5,B=0,C=0A = 5, B = 0, C = 0。

Q8. Fuzzy checkpoint 103 記錄 running:T2, T5。Scan backwards 時,喺 checkpoint 102(running: T2, T3, T4)需唔需要追 T3、T4?Worst-case recovery cost 係幾多?

唔使追 T3、T4:佢哋喺 checkpoint 103 已唔喺 running list,即已完成並包含喺 checkpoint image。只需追 T2、T5(T2 視乎有冇見到 commit)。Worst case O(n)O(n)(scan 到第一條 log),但實際極少發生。

Q9. 解釋 ACID,並說明 ATM lost-update 例子違反咗邊個 property。

Atomicity(all-or-nothing)、Consistency(valid state → valid state)、Isolation(好似獨立執行)、Durability(commit 後永久)。ATM 例子 interleaving 令 Y 的 +100 被覆蓋,結果唔等於任何 serial execution → 違反 Isolation(亦令 Consistency 破壞:總額由 200 變 100)。

一頁總結 Cheat sheet

⭐ 考前速記
  • Table = relation;join tables 搵跨表資料
  • Big O:只取最高次項、忽略係數;看 average / worst case;lg⁡=log⁡2\lg = \log_2
  • O(1)O(1) 搵任何一個;O(lg⁡n)O(\lg n) tournament rounds / B tree search;O(n)O(n) 逐個 mark;O(n2)O(n^2) peer review
  • B tree:左細右大;值喺所有 level;best O(1)O(1),worst O(lg⁡n)O(\lg n)
  • B+ tree:pointers 只喺 leaf;non-leaf = separators(左 <,右 ≥);sibling pointers;range query = 搵起點 + 行 siblings
  • B/B+ tree:balanced;search & update O(lg⁡n)O(\lg n)(binary tree update linear);one-dimensional
  • Multiple / composite indices;overhead = space (pointers) + maintenance;Query plan / optimizer(用 statistics;唔好完全依賴)
  • R-tree(spatial,worst O(n)O(n));HNSW(vector cosine top-k,RAG);Inverted index(full-text)
  • Transaction = all or nothing;begin … commit
  • Correct = equivalent to serial execution;不同 serial order 結果唔同都算正確(910 / 909)
  • Locks:R–R OK;R–W、W–W conflict;writelock = upgraded readlock
  • 2PL:growing(只攞)→ shrinking(只放)
  • Conflict → wait 或 rollback;deadlock = wait-for graph 有 cycle;cascading rollback
  • Log-based recovery:write log before DB;log 有 start、commit、updates(before-after 或 delta)
  • Recovery:undo incomplete, redo committed;scan backwards
  • Blocking checkpoint(停 update)vs Fuzzy(不停,記 running transactions;worst O(n)O(n))
  • ACID:Atomicity / Consistency / Isolation / Durability