← Computer Science notes

Unit 6 · Database Management Systems & SQL

Chapter 6 · Indexing & Query Processing

pdcampus.in
pdcampus.in • DSSSB TGT CS
Beginner Topper
Indexing & Query Processing Unit 3 • Ch 3 • B+ Tree, Hashing Static Dynamic, Query Processing Steps, Optimization Joins
Beginner Story Mode Complete Notes

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.

1. Indexing - B+ Tree Structure - Most Important
Indexing B+ Tree Structure handwritten
Fig 1: B+ Tree balanced tree database indexing data in leaves only | Order m=4 Root internal 30|40 Leaf nodes [10|20]→data ptr rec(10) rec(20) leaf nodes linked as linked list for range queries | Properties All leaves same depth Internal ceil(m/2) to m children Leaf keys+data pointers+next pointer Internal only keys & pointers no data Balanced O(log_m N) Range queries fast via leaf linked list High fanout reduces height fewer disk I/Os

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.

B+ Tree balanced all leaves same depth | Internal ceil(m/2) to m children Leaf keys+data ptr+next ptr linked list | Internal only keys & pointers no data | O(log_m N) search insert delete | Range queries fast via leaf linked list | High fanout reduces height fewer disk I/Os | Data only in leaves
2. Hashing - Static & Dynamic - O(1) Lookup
Hashing Static Dynamic handwritten
Fig 2: Hashing Static fixed buckets hash function h(key)→bucket h(key)%N collision handling chaining linked list Bucket 2 12→22→32→NULL open addressing linear probing h+1 %N | Dynamic Extendible hashing directory gd global depth ld local depth bucket split when full gd=gd+1 directory doubles Linear hashing no directory round-robin split pointer 0→1→2→3 wraps | Average O(1) lookup no range queries not ordered

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.

Static hashing fixed buckets h(key)%N | Chaining linked list per bucket Bucket2 12→22→32→NULL | Open addressing linear probing h+1 %N | Dynamic Extendible directory gd global depth ld local depth bucket split when full gd=gd+1 doubles | Linear hashing no directory round-robin split pointer 0→1→2→3 wraps | O(1) average no range queries
3. Query Processing - Steps & Cost
Query Processing Steps Cost handwritten
Fig 3: Query Processing Steps SQL Query → Parser & Translator syntax relational algebra → Optimizer cost estimation statistics → Evaluation Plan → Execution Engine → Result | Cost Disk I/O dominant CPU Network | Statistics tuples blocks distinct values histograms

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.

Steps: SQL → Parser & Translator relational algebra → Optimizer cost estimation statistics → Evaluation Plan → Execution Engine → Result | Cost Disk I/O dominant CPU Network | Statistics tuples blocks distinct values histograms | Optimizer chooses cheapest plan
4. Query Optimization - Heuristics & Join Strategies
Query Optimization Heuristics Join handwritten
Fig 4: Query Optimization Heuristics Push selection down early filter early Push projection early keep only needed columns Combine selection with cartesian to make join | Join Nested Loop O(n*m) Block Nested Loop buffer Indexed Nested Loop uses index fast Sort-Merge Join sort both then merge O(n log n + m log m) Hash Join build hash table O(n+m) best for equi-join | Example SELECT Student JOIN Enroll WHERE Dept='CS' optimized selection before join Cost estimation choose cheapest

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.

Heuristics: Push selection down early filter early Push projection early keep needed columns Combine selection with cartesian to make join Most restrictive first | Joins: Nested Loop O(n*m) Block Nested Loop buffer Indexed Nested Loop uses index O(n log m) Sort-Merge sort both then merge O(n log n + m log m) Hash Join build hash O(n+m) best equi-join | Choose cheapest cost
5. DSSSB Traps & PYQ Practice
  • Q: Why indexing? → Avoid full scan O(n) to O(log n) fast
  • Q: B+ Tree data? → Only in leaves internal only keys & pointers no data
  • Q: B+ Tree leaves? → Same depth balanced leaf nodes linked list next pointer range queries fast
  • Q: B+ Tree internal nodes? → ceil(m/2) to m children for m=4 2 to 4 children
  • Q: B+ Tree time? → O(log_m N) search insert delete
  • Q: B+ Tree range queries? → Fast via leaf linked list follow next pointers
  • Q: B+ Tree vs B Tree? → B Tree data in internal and leaves B+ Tree data only leaves B+ Tree leaf linked list range faster higher fanout DBMS uses B+ Tree MySQL InnoDB uses B+ Tree
  • Q: Hash function? → h(key)→bucket h(key)%N bucket index
  • Q: Collision? → Two keys map to same bucket
  • Q: Chaining? → Store collisions linked list per bucket Bucket2 12→22→32→NULL
  • Q: Open addressing linear probing? → Probe next slot h+1 %N +2 +3 until empty clustering possible
  • Q: Static hashing? → Fixed buckets
  • Q: Extendible hashing? → Directory pointers to buckets global depth gd bits to index directory local depth ld ≤ gd bucket split when full ld increment redistribute if directory too small gd=gd+1 directory doubles
  • Q: Linear hashing? → No directory round-robin split pointer 0→1→2→3 wraps split bucket pointed by pointer
  • Q: Hashing performance? → Average O(1) lookup fast
  • Q: Hashing limitations? → No range queries not ordered not sorted performance degrades poor hash many collisions
  • Q: Query Processing Steps? → SQL → Parser & Translator relational algebra → Optimizer cost estimation statistics → Evaluation Plan → Execution Engine → Result
  • Q: Cost components? → Disk I/O dominant CPU Network
  • Q: Statistics? → Tuples blocks distinct values histograms
  • Q: Heuristics? → Push selection down early Push projection early Combine selection with cartesian to make join Most restrictive first
  • Q: Join strategies? → Nested Loop O(n*m) Block Nested Loop buffer Indexed Nested Loop uses index O(n log m) fast if index exists Sort-Merge sort both then merge O(n log n + m log m) Hash Join build hash O(n+m) best equi-join build probe partitioned
  • Q: Which join best for equi-join? → Hash Join O(n+m) if memory enough
  • Q: Real DBMS uses? → B+ Tree for indexes MySQL InnoDB B+ Tree Hashing for exact lookup Query optimization cost-based + heuristics
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) | Hashing h(key)%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 | Query Steps SQL→Parser→Optimizer cost→Plan→Engine→Result Disk I/O dominant | Heuristics Push selection down projection down | Joins Nested O(n*m) Indexed Nested O(n log m) Sort-Merge O(n log n) Hash O(n+m) best equi-join

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!

Topper Revision 1 Page = Full Chapter

B+ Tree Indexing

  • Data only in leaves internal only keys & pointers no data | All leaves same depth balanced leaf nodes linked list next pointer range queries fast
  • Internal ceil(m/2) to m children for m=4 2 to 4 | Leaf keys+data ptr+next ptr | O(log_m N) search insert delete | High fanout reduces height fewer I/Os | B Tree data internal+leaves B+ Tree data only leaves DBMS uses B+ Tree MySQL InnoDB B+ Tree
  • Insertion keys 10,20,30,40,50 split at 20 promote 20 root [20|40] leaves depth 2 balanced

Hashing

h(key)→bucket h(key)%N | Chaining linked list Bucket2 12→22→32→NULL | Linear probing h+1 %N clustering | Static fixed Dynamic grows | Extendible directory gd global ld local split gd=gd+1 doubles | Linear round-robin split pointer 0→1→2→3 wraps | O(1) average no range
  • Static fixed buckets collision two keys same bucket | Chaining linked list per bucket | Open addressing linear probing probe next slot h+1 %N +2 +3 clustering
  • Dynamic Extendible hashing directory pointers buckets gd bits to index ld ≤ gd bucket split when full ld increment redistribute if directory too small gd=gd+1 doubles | Linear hashing no directory round-robin split pointer 0→1→2→3 wraps split pointed bucket
  • Average O(1) lookup fast | No range queries not ordered not sorted performance degrades poor hash many collisions | Used caches maps DB indexes

Query Processing

  • Steps SQL → Parser & Translator syntax relational algebra π_Name σ_Dept='CS'(Student) parse tree → Optimizer cost estimation statistics → Evaluation Plan exact steps index scan join algorithm → Execution Engine fetches data buffer → Result
  • Cost Disk I/O dominant CPU Network minimizing disk I/Os | Statistics tuples blocks distinct values histograms DBMS ANALYZE TABLE updates
  • Example SELECT Name WHERE Dept='CS' AND Roll>100 Plan A full scan Plan B index on Dept filter Dept='CS' then Roll>100 optimizer selective index cheaper chooses B

Query Optimization

HeuristicMeaningBenefit
Push selection downFilter early σ_Dept='CS'(Student ⨝ Enroll) → (σ_Dept='CS'(Student)) ⨝ EnrollReduces rows early reduces join size
Push projection downKeep only needed columns π_NameReduces size
Combine selection with cartesianσ_Roll=Roll(Student×Enroll)→Student ⨝ EnrollAvoid huge cartesian
Most restrictive firstMost selective operation firstPrunes early
JoinCostWhen UseNotes
Nested LoopO(n*m)Small relationsFor each outer for each inner simple slow
Block Nested LoopO(n*m) but less I/OSmall bufferRead outer in blocks reduces I/O
Indexed Nested LoopO(n log m)Inner has index on join attrIndex lookup fast if index exists
Sort-MergeO(n log n + m log m + n+m)Sorted or sort acceptable equi and non-equiSort both then merge
Hash JoinO(n+m)Equi-join equality bestBuild hash on smaller probe larger partitioned large
  • Cost estimation number of disk I/Os choose minimum cost plan | Cost-based more accurate than heuristics alone DBMS uses both heuristics prune cost-based choose
  • Example SELECT Student JOIN Enroll WHERE Dept='CS' unoptimized cartesian huge optimized filter CS first then Indexed Nested Loop index on Enroll.Roll

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

© 2026 pdcampus.in · All rights reserved. · Made with ❤️ for Indian students.