Unit 6 · Database Management Systems & SQL
Imagine library with 10 lakh books. To find book without index you check all 10 lakh shelves full scan slow. With index like dictionary you find fast. That's Indexing.
B+ Tree = Balanced tree like family tree where all leaves at same depth, internal nodes hold keys and pointers to children, leaf nodes hold keys and data pointers plus next pointer linked list for range queries fast. MySQL InnoDB uses B+ Tree for indexes. Like phone book sorted gives equality search and range search 20-50 fast.
Hashing = Hash function h(key) maps to bucket O(1) average fast like magic box: key 12 h(12)=12%10=2 bucket 2. Collision when two keys map to same bucket: chaining linked list 12→22→32 in bucket 2, open addressing linear probing next slot (h+1)%N. Static hashing fixed buckets, Dynamic hashing grows: Extendible hashing directory with global depth gd local depth ld bucket split when full directory doubles, Linear hashing no directory round-robin split split pointer moves 0→1→2→3... wraps. Hashing fast O(1) but no range queries not ordered.
Query Processing = Steps to execute SQL query: SQL Query → Parser & Translator checks syntax to relational algebra → Optimizer cost estimation chooses cheapest plan using statistics → Evaluation Plan → Execution Engine fetches data → Result. Cost components Disk I/O dominant CPU Network. Statistics tuples blocks distinct values histograms.
Query Optimization = Choose cheapest plan. Heuristics: Push selection down early filter early reduces rows, push projection early keep only needed columns, combine selection with cartesian to make join. Join strategies: Nested Loop O(n*m) for each row of outer for each row of inner, Block Nested Loop buffer, Indexed Nested Loop uses index on inner fast if index exists, Sort-Merge sort both then merge O(n log n + m log m) good for sorted, Hash Join build hash table O(n+m) best for equi-join. Cost estimation choose cheapest. Let's learn with handwritten diagrams.
Why Indexing? Without index full table scan O(n) slow, with index O(log n) fast like book index.
B+ Tree = Balanced Tree for database indexing:
- Keeps data in leaves only, internal nodes only keys and pointers to children no data.
- All leaves at same depth balanced.
- Leaf nodes contain keys + data pointers + next pointer linked list for range queries.
Example from Fig 1 Order m=4 (max children 4):
Root Internal Node [30 | 40] has 3 pointers.
Leaf Nodes:
- Leaf [10 | 20] → data ptr rec(10) rec(20)
- Leaf [30] → data ptr rec(30)
- Leaf [40 | 50] → data ptr rec(40) rec(50) next→NULL
Leaf nodes linked as linked list: [10|20] next→ [30] next→ [40|50] → NULL for range queries.
Insertion Example keys 10,20,30,40,50:
Step1 Insert 10 → [10] leaf only root is leaf.
Step2 Insert 20 → [10|20]
Step3 Insert 30 → [10,20,30] full m=4? Actually max keys m-1=3? For m=4 max keys 3 now full split at 20 promote 20 to parent root becomes [20] internal with children [10|20] and [30].
Step4 Insert 40 → [30,40]
Step5 Insert 50 → [40,50] split promote 40 root becomes [20|40] children [10|20] [30|40] [50] leaves all depth 2 balanced.
Properties:
- All leaves same depth balanced.*
- Internal node: ceil(m/2) ≤ #children ≤ m → for m=4 2 to 4 children.
- Leaf node: stores keys + data pointers + next pointer.
- Internal nodes hold only keys & pointers to children no data.
- Balanced → O(log_m N) time for search/insert/delete.
- Range queries fast via leaf linked list just follow next pointers.
- Supports both equality search and range queries efficiently.
- High fanout reduces tree height → fewer disk I/Os.
- m = max children per node. All data records stored only in leaf nodes.*
- Common in DBMS: MySQL InnoDB uses B+ Tree for indexes.
B Tree vs B+ Tree:
- B Tree data in internal and leaves, B+ Tree data only in leaves.
- B+ Tree leaf linked list range queries faster, B Tree not.
- B+ Tree higher fanout shorter height.
- DBMS uses B+ Tree mostly.
Hash function h(key) maps to bucket:
h(key) → bucket index = h(key) % N fixed #buckets.
Used when table size fixed. Collision when two keys map to same bucket.
Collision Handling:
- Chaining: Store collisions in linked list each bucket. Bucket 2 → [12]→[22]→[32]→NULL.
- Open Addressing Linear Probing: When collision occurs probe next slot (h(key)+1)%N then +2 +3 until empty slot. Simple but clustering possible.
- Example keys 12,22,32 hashed bucket:
h(12)=12%10=2 → bucket2
h(22)=22%10=2 → bucket2 collision → chain or probe to 3
h(32)=32%10=2 → bucket2 collision → chain or probe to 4
Dynamic Hashing: Table grows as data grows.
- Extendible Hashing: Uses directory of pointers to buckets.
* Global depth gd = #bits to index directory.
* Each bucket has local depth ld ≤ gd.
* Directory example gd=2: 00→Bucket A ld=2, 01→Bucket B ld=1, 10→Bucket A ld=2, 11→Bucket C ld=1.
* Bucket split when full → split bucket increment local depth redistribute keys.
* If directory too small → gd = gd+1 directory doubles.
* Split Bucket A → create Bucket D now ld=2.
- Linear Hashing: No directory no separate directory table.
* Buckets split round-robin in order as data grows.
* Split pointer moves sequentially 0→1→2→3→... then wraps.
* On overflow split bucket pointed by split pointer then advance pointer.
Performance: Average constant time O(1) lookup simple efficient for key-value lookups.
Limitations:
- No range queries / insert / delete range not efficient.
- Not ordered keys not sorted.
- Performance degrades with poor hash or many collisions.
Summary: Static = fixed buckets; Dynamic = grows by splitting/doubling hash tables used in caches maps DB indexes.
How does DBMS execute SELECT * FROM Student WHERE Dept='CS'? Query processing steps.
Steps:
1) SQL Query: User writes SQL SELECT.
2) Parser & Translator: Checks syntax, checks if tables columns exist, translates to relational algebra expression π_Name σ_Dept='CS'(Student). Parser builds parse tree.
3) Optimizer: Cost estimation chooses cheapest evaluation plan. Uses statistics: number of tuples, number of blocks, distinct values, histograms. Many equivalent relational algebra expressions, optimizer estimates cost for each and chooses cheapest. Heuristics and cost-based.
4) Evaluation Plan: Exact steps with algorithms e.g., use index scan or full scan, which join algorithm nested loop or hash join.
5) Execution Engine: Executes plan fetches data from disk buffer manager uses indexes.
6) Result: Output rows.
Cost Components:
- Disk I/O cost dominant number of blocks read/write. Disk is slow.
- CPU cost for processing.
- Network cost if distributed.
Most important is minimizing disk I/Os. Optimizer estimates number of blocks needed.
Statistics:
- Number of tuples n, number of blocks b, size of tuple, blocking factor.
- Number of distinct values for attribute.
- Histograms frequency distribution.
DBMS periodically updates statistics ANALYZE TABLE.
Example: Query SELECT Name FROM Student WHERE Dept='CS' AND Roll>100
Two plans: Plan A full scan Student check both conditions per tuple. Plan B use index on Dept if exists filter Dept='CS' then check Roll>100. Optimizer estimates cost: If Dept='CS' selective few rows index scan cheaper chooses Plan B.
Heuristic Optimization - Rules without cost:
- Push selection down early: Filter early reduces number of tuples early. σ_Dept='CS'(Student ⨝ Enroll) → (σ_Dept='CS'(Student)) ⨝ Enroll. Selection before join reduces join input size.
- Push projection early: Keep only needed columns early reduces size. π_Name(Student) before join.
- Combine selection with cartesian product to make join: σ_Student.Roll=Enroll.Roll(Student × Enroll) → Student ⨝ Enroll. Avoid cartesian product huge.
- Perform most restrictive selection and join first.
Join Strategies - How to implement join:
Suppose Student n tuples Enroll m tuples.
- Nested Loop Join: For each tuple in outer relation Student for each tuple in inner Enroll check if join condition matches. Cost O(n*m) blocks worst. Simple but slow if both large.
- Block Nested Loop Join: Use buffer blocks, read outer in blocks reduces I/O. Improved nested loop.
- Indexed Nested Loop Join: If inner relation has index on join attribute use index to find matching tuples fast. For each outer tuple use index lookup on inner O(n log m). Fast if index exists.
- Sort-Merge Join: Sort both relations on join attribute then merge scan sorted lists. Cost O(n log n + m log m) sorting + O(n+m) merging. Good if relations already sorted or sort cost acceptable, works for equi-join and non-equi.
- Hash Join: Build hash table on smaller relation's join attribute, then probe with larger relation's tuples. Cost O(n+m) best for equi-join equality condition, requires memory for hash table. Two phases build and probe. Partitioned hash join for large relations.
Example from Fig 4:
Query SELECT * FROM Student JOIN Enroll ON Student.Roll=Enroll.Roll WHERE Dept='CS'
Unoptimized: Student × Enroll cartesian product huge then selection Dept='CS' and Roll match.
Optimized: σ_Dept='CS'(Student) first filter CS students small then join with Enroll using Indexed Nested Loop if index on Enroll.Roll. Push selection before join.
Cost estimation: Optimizer estimates cost of each join strategy using statistics chooses cheapest plan.
Cost Estimation: For each plan estimate number of disk I/Os. Choose plan with minimum cost. Cost-based optimization more accurate than heuristics alone. DBMS uses both heuristics to prune and cost-based to choose.
Final Recap: Library 10 lakh books find book without index full scan 10 lakh slow with index dictionary fast. B+ Tree balanced tree database indexing order m=4 max children 4 internal nodes keys & pointers no data Root [30|40] Leaf [10|20]→data rec(10) rec(20) Leaf [30]→rec(30) Leaf [40|50]→rec(40) rec(50) leaf linked list [10|20] next→[30] next→[40|50]→NULL range queries fast follow next. Insertion 10→[10] 20→[10|20] 30→[10,20,30] full split at 20 promote 20 parent 40→[30,40] 50→[40,50] root [20|40] leaves depth 2 balanced. Properties all leaves same depth internal ceil(m/2) to m children for m=4 2 to 4 leaf keys+data pointers+next pointer internal only keys & pointers no data O(log_m N) search insert delete range fast via leaf linked list high fanout reduces height fewer disk I/Os data only leaves B Tree vs B+ Tree B Tree data internal and leaves B+ Tree data only leaves B+ Tree leaf linked list range faster DBMS uses B+ Tree MySQL InnoDB B+ Tree. Hashing h(key)→bucket h(key)%N static fixed buckets collision two keys same bucket chaining linked list Bucket2 12→22→32→NULL open addressing linear probing probe next slot h+1 %N +2 +3 clustering possible example 12%10=2 bucket2 22%10=2 bucket2 collision chain or probe to 3 32%10=2 bucket2 collision chain or probe to 4 Dynamic Extendible hashing directory pointers buckets global depth gd bits to index directory local depth ld ≤ gd directory gd=2 00→A ld=2 01→B ld=1 10→A ld=2 11→C ld=1 bucket split when full increment ld redistribute keys if directory too small gd=gd+1 doubles split Bucket A→create D ld=2 Linear hashing no directory round-robin split pointer 0→1→2→3 wraps on overflow split bucket pointed by pointer advance pointer average O(1) lookup limitations no range queries not ordered not sorted performance degrades poor hash many collisions summary Static fixed Dynamic grows splitting doubling hash tables used caches maps DB indexes. Query Processing Steps SQL Query → Parser & Translator syntax relational algebra π_Name σ_Dept='CS'(Student) parse tree → Optimizer cost estimation statistics tuples blocks distinct values histograms many equivalent algebra optimizer estimates cost chooses cheapest heuristics cost-based → Evaluation Plan exact steps index scan or full scan which join → Execution Engine fetches data buffer manager → Result Cost Disk I/O dominant CPU Network minimizing disk I/Os statistics tuples blocks distinct histograms DBMS ANALYZE TABLE. Example SELECT Name WHERE Dept='CS' AND Roll>100 Plan A full scan check both Plan B index on Dept filter Dept='CS' then Roll>100 optimizer selective few rows index cheaper chooses B. Query Optimization Heuristics Push selection down early filter early reduces rows σ_Dept='CS'(Student ⨝ Enroll) → (σ_Dept='CS'(Student)) ⨝ Enroll selection before join reduces size Push projection early keep only needed columns Combine selection with cartesian to make join σ_Roll=Roll(Student×Enroll)→Student ⨝ Enroll avoid huge cartesian Most restrictive first. Join Strategies Student n Enroll m Nested Loop for each outer for each inner O(n*m) worst simple slow Block Nested Loop buffer read outer in blocks reduces I/O Indexed Nested Loop inner has index on join attribute index lookup O(n log m) fast if index exists Sort-Merge sort both on join attribute then merge O(n log n + m log m) good if already sorted Hash Join build hash table on smaller join attribute then probe larger O(n+m) best equi-join build probe partitioned hash large. Example SELECT Student JOIN Enroll WHERE Dept='CS' unoptimized Student×Enroll cartesian huge then selection optimized σ_Dept='CS'(Student) first filter small then join Indexed Nested Loop index on Enroll.Roll push selection before join cost estimation chooses cheapest cost-based more accurate heuristics prune cost-based choose. If you remember B+ Tree data only leaves leaves same depth linked list range fast O(log_m N) and Hashing h%N chaining linked list linear probing h+1 %N Extendible directory gd ld split Linear round-robin O(1) no range and Query Steps SQL→Parser→Optimizer→Plan→Engine→Result Disk I/O dominant and Heuristics push selection down and Joins Nested O(n*m) Indexed O(n log m) Sort-Merge O(n log n) Hash O(n+m) best equi-join DSSSB 5 marks fixed!
B+ Tree Indexing
Hashing
Query Processing
Query Optimization
| Heuristic | Meaning | Benefit |
|---|---|---|
| Push selection down | Filter early σ_Dept='CS'(Student ⨝ Enroll) → (σ_Dept='CS'(Student)) ⨝ Enroll | Reduces rows early reduces join size |
| Push projection down | Keep only needed columns π_Name | Reduces size |
| Combine selection with cartesian | σ_Roll=Roll(Student×Enroll)→Student ⨝ Enroll | Avoid huge cartesian |
| Most restrictive first | Most selective operation first | Prunes early |
| Join | Cost | When Use | Notes |
|---|---|---|---|
| Nested Loop | O(n*m) | Small relations | For each outer for each inner simple slow |
| Block Nested Loop | O(n*m) but less I/O | Small buffer | Read outer in blocks reduces I/O |
| Indexed Nested Loop | O(n log m) | Inner has index on join attr | Index lookup fast if index exists |
| Sort-Merge | O(n log n + m log m + n+m) | Sorted or sort acceptable equi and non-equi | Sort both then merge |
| Hash Join | O(n+m) | Equi-join equality best | Build hash on smaller probe larger partitioned large |
PYQ Traps:
• Indexing avoids full scan O(n) to O(log n)
• B+ Tree data only leaves internal keys pointers no data leaves same depth linked list range fast
• ceil(m/2) to m children O(log_m N) high fanout fewer I/Os
• B Tree data internal+leaves B+ Tree data only leaves DBMS uses B+ Tree
• Hashing h%N chaining linked list linear probing h+1 %N
• Static fixed Dynamic Extendible directory gd ld split Linear round-robin
• O(1) average no range not ordered
• Query Steps SQL→Parser→Optimizer→Plan→Engine→Result Disk I/O dominant Statistics tuples blocks distinct histograms
• Heuristics push selection down projection down
• Joins Nested O(n*m) Indexed O(n log m) Sort-Merge O(n log n) Hash O(n+m) best equi-join