File Organizations: Heap, Sorted & Hashed Files
💡 Core Intuition
🍳 The Everyday Analogy: The Warehouse Storage Systems
Imagine managing a physical archive of paper project folders inside a massive warehouse:
- The Pile System (Heap File): Every time a new project folder arrives, you walk to the very back of the warehouse and toss it on top of the newest stack. Filing takes 5 seconds (). But when the CEO asks for "Project Falcon", you must physically walk through every single box from front to back, examining folders one by one ( search).
- The Alphabetical Shelving System (Sorted File): Every project is filed in strict alphabetical order by project code. Finding "Project Falcon" is lightning fast: you jump to the middle aisle (
M), realizeFis in the first half, jump toF, and find it in seconds using Binary Search (). However, when a new project "Project Fixer" arrives, you cannot just drop it in: you must physically push thousands of heavy boxes to the right to make space for one folder. - The Hash Box System (Hashed File): You run the project code through a math formula (e.g. sum of letters modulo 100) that directly spits out the exact aisle and shelf number. You walk straight to that shelf in time.
In database physical storage, disk drives read data in fixed-size Blocks (pages). How records are arranged across these blocks dictates whether queries finish in milliseconds or stall for hours.
💻 Bridging to Computer Science
Theoretically, relational databases are founded on set theory, where tuple order inside a relation is mathematically irrelevant. But in physical database implementation, storage order is everything.
Physical Storage Organization:
├── Unordered (Heap File) ===> Fast Appends O(1), Slow Scans O(b)
├── Ordered (Sorted File) ===> Fast Binary Search O(log2 b), Expensive Shifts
└── Hash File Organization ===> O(1) Direct Key Lookup, Inefficient Range Scans
Every query execution plan generated by the database optimizer begins by estimating the number of Block Transfers (Disk I/Os) required by the underlying file organization.
📚 Core Deep-Dive & Concepts
Physical Storage Primitives: Records, Blocks, and Blocking Factor
Database tables are stored physically as collections of fixed-length or variable-length records packed into fixed-size storage units called disk blocks (pages) (typically or ).
1. Blocking Factor ()
The number of physical records that can fit completely inside a single disk block: (Where represents the floor function for unspanned records).
2. Number of Data Blocks ()
The total number of physical disk blocks required to store records:
Unordered (Heap) File Organization
In a Heap File, records are inserted in the order they arrive, appended directly to the end of the last data block in the file.
Operational Characteristics
- Insertion: Extremely fast. If the last block has free space, the record is written in block I/O. If full, allocate a new block and append.
- Search (Equality): Requires a sequential Linear Scan. On average, the DBMS must search half the blocks if the record is present: If searching for a non-unique attribute or a record that does not exist, the DBMS must read all blocks:
- Deletion: Locate the block containing the target record, set a deletion tombstone flag, and write the block back (). Periodic vacuuming reorganizes space.
Ordered (Sequential / Sorted) File Organization
In an Ordered File, records are physically sorted on disk based on the value of a specific field, termed the Ordering Field (or Ordering Key if unique).
Operational Characteristics
- Search (Equality on Ordering Key): Because records are sorted physically across blocks, the DBMS executes Binary Search over the block directory:
- Range Queries: Exceptionally efficient. Locate the first matching record via binary search, then scan contiguous blocks sequentially until the range boundary is reached.
- Insertion: Highly expensive! Inserting a record into its correct alphabetical/numeric position requires finding the target block and shifting subsequent records across multiple blocks to free space. DBMS engines often mitigate this using Overflow Blocks chained with pointers.
- Deletion: Fast with tombstone markers; physical compaction requires block shifting.
Hashed File Organization
In a Hashed File, records are assigned to disk blocks (called buckets) based on a mathematical hash function applied to the search key:
Operational Characteristics
- Search (Equality on Hash Key): Compute , jump directly to the target bucket block:
- Collision Handling: When a bucket overflows, the DBMS chains an overflow block via a linked list, degrading search to .
- Range Queries: Extremely Poor! A hash function deliberately randomizes data distribution. Executing
WHERE age BETWEEN 20 AND 30requires a complete full table scan of all blocks ( I/Os).
File Organization Trade-Off Matrix
| Dimension | Heap File | Ordered (Sorted) File | Hashed File |
|---|---|---|---|
| Record Physical Order | Random (Arrival order) | Sorted on Ordering Field | Grouped into Hash Buckets |
| Equality Search Cost | linear scan | binary search | direct bucket read |
| Range Query Cost | full scan | contiguous | full scan (randomized keys) |
| Insertion Cost | fast append | block shifting | bucket write |
| Best Used For | Bulk logging, staging tables | Analytical tables, range queries | Fast single-row primary key lookups |
Step-by-Step Solved Numerical: Access Cost Derivation
Problem Specification (from Physical System Parameters):
- Total records in file:
- Disk block size:
- Fixed record length: (unspanned)
- Ordering key field:
- Block pointer size:
Step 1: Calculate the Blocking Factor of the Data File
Step 2: Calculate the Total Number of Data Blocks Required
Step 3: Compute Search Cost Across File Organizations
- Case A: Unordered (Heap File)
- Average equality search (record found):
- Worst-case equality search (record not found):
- Case B: Ordered (Sorted File)
- Using binary search across 3,000 blocks:
Step 4: Quantifying the Performance Multiplier
Switching from a Heap file to an Ordered file slashes the search cost from block reads down to block reads—an immediate speedup in disk I/O latency!
📐 Architecture / Visual Blueprint
The following diagram contrasts the physical block layout of Heap, Sorted, and Hashed file organizations on magnetic or solid-state disk platters:
🏭 In The Real World: Production Case Study
Log Ingestion vs. Analytical Queries (ClickHouse vs. PostgreSQL)
Modern data platforms choose file organizations based strictly on write versus read query patterns.
The High-Throughput Ingestion Problem: Uber Trip Telemetry
Uber ingests over GPS coordinate pings per second. If the telemetry database maintained an alphabetically sorted file on GPS timestamp during live insertion, each write would trigger massive disk block shifts and lock stalls.
The Architecture
- Ingestion Stage (Heap File Pattern): Incoming telemetry is written to append-only memory buffers and raw LSM-tree log blocks (Heap organization). Write latency is because blocks are filled sequentially without shifting data.
- Compaction Stage (Sorted File Pattern): In the background, ClickHouse merges and sorts chunks of records into contiguous, compressed columnar blocks sorted by
(City, Timestamp). - Query Stage: When analytics run queries like
WHERE City = 'Chicago' AND Timestamp BETWEEN ..., the query engine performs binary search across block markers, reading only the necessary blocks out of millions.
🎯 Exam & Interview Pitfall Check
Question 1: A database table has fixed-length records of size . Disk block size is . Compute:
- The blocking factor of the file.
- The number of blocks required.
- The average search cost if stored as a Heap file versus an Ordered file.
Answer:
- Blocking Factor:
- Number of Blocks:
- Search Cost Comparison:
- Heap File (Average): .
- Ordered File (Binary Search): .
Question 2: Why are Hashed file organizations unsuitable for range queries?
Answer:
Hash functions are designed to distribute keys uniformly across buckets to minimize collisions, deliberately destroying any natural numerical or lexicographical order. Two consecutive values (e.g. Age = 25 and Age = 26) hash to completely different bucket addresses across disk. Consequently, retrieving records within a range WHERE age BETWEEN 20 AND 30 cannot scan contiguous blocks; the database is forced to evaluate all possible hash values or perform a full sequential scan of every block in the database.
Trap 1: Using the ceiling function instead of floor for Blocking Factor (). When calculating , you must always use floor () for unspanned records, because you cannot store a fraction of a record inside a block without crossing block boundaries. Using ceiling overestimates block capacity and corrupts block count calculations.
Trap 2: Forgetting to take the ceiling of the final block count. When calculating , you must always use ceiling, because any remaining leftover records (even a single record) require an entire dedicated disk block.