Database Internals Part 1: Learning How Databases Store Data
Here I am going to write about db internals. Why am I writing this? Because I like to explain things, it makes me understand things better.
so there are two types of devices for storage mainly volatile and non volatile .
volatile are ram and non volatile is HDD
The further you get away from the CPU, the larger but slower the storage devices get . This line demonstrates the performance of the db .
Closer to the CPU: faster, smaller, more expensive
Further from the CPU: slower, larger, cheaper
The two main types of device categories
Volatile Devices
- Volatile means that the device does not retain its state after power loss. Therefore, the data that is stored in such devices can be lost.
- Volatile storage supports fast random access with byte-addressable locations. This means that the program can jump to any byte address and get the data that is there (e.g. in DRAM).
- For our purposes, we will always refer to this volatile storage class as “memory.”
Non-Volatile Devices
- Non-volatile devices do retain their state even when the machine/computer is off or power loss occurs. Therefore, the data that these devices store can be retrieved even after the machine/computer shuts down and restarts (e.g. disk).
- Non-Volatile devices are block/page addressable. This means that in order to read a value at a particular offset (byte), the program first has to load the 4 KB page into memory that holds the value that the program wants to read.
- Non-volatile storage is traditionally better at sequential access (reading contiguous blocks of data because of its architecture e.g. magnetic hard drive).
- We will refer to this as “disk.” We will not make a (major) distinction between solid-state storage (SSD) and spinning hard drives (HDD).
RAM (random access memory) → It means that the computer can access any memory location directly, without having to go through the previous locations first
access time vs access patterns
There is a large contrast between latencies accessing volatile vs. non-volatile devices.
volatile and non volatile memories have different access patterns , this differentiation does not contribute to latency when accessing volatile memory , but plays a significant role in non - volatile memory accesses.
- Sequential access: If data is stored in consecutive locations, the head can read it continuously with relatively little movement.
- Random access: If data is scattered across different locations, the head must repeatedly move to different positions, and the disk may need to rotate to the appropriate location.
This introduces additional time called seek time and rotational latency.
Consequently, random access is considerably slower than sequential access on HDDs.
Sequential access: neighbouring blocks, no jumping
Random access: the head has to jump, and every jump costs seek time
Where is the database stored ?
The database is stored on disk, and the data within the database files are organized into pages, with the first page being the directory page.
(pages -> Page in memory is a fixed-size block of data)
To use the data stored on the disk, the DBMS needs to bring the data into memory. It does this by having a buffer pool that manages the data movement back and forth between disk and memory.
for executing queries in db there is execution engine but we are not going to discuss it in this blog .
Buffer pool -> this is the dedicated area of ram that the database storage engine uses to cache pages loaded from disk.
Try it: click a page on disk to request it (the buffer pool has 3 frames)
Buffer pool (RAM)
Hits: 0, misses: 0
so the dbms stores the data in the form of files and some may use file hierarchy and others may store it in single file (eg. sqlite)
File Storage
File Format. The DBMS traditionally stores files in a proprietary format that is specific to the DBMS, therefore only the specific DBMS knows how to decipher their contents. More recently there are also portable file formats that are open specs which allow all DBMSs to read and write from them. For either approach, the OS does not know anything about the contents of these files.
File System. The DBMS typically runs on off-the-shelf file system provided by the OS. There are some high-end enterprise systems that could inject a custom file system into the OS specific for the DBMS (e.g. Oracle ASM)
File Storage Manager. The DBMS’s storage manager is responsible for managing a database’s files. It represents the files as a collection of pages. It also keeps track of what data has been read and written to pages as well how much free space there is in these pages.
A DBMS typically does not maintain multiple copies of a page on disk. Replication is not handled on storage manager level. Typically they are handled either in the file system below the storage manager (e.g.RAID), or above the storage manager where there could be logical copies of tuples.
Database pages
the data is stored on the disk by the dbms and the disk stores the data in the form of pages. Page is a block of memory.
Pages have unique identifier which is called page ID.
(I will discuss about page layout in detail below in this article.)
what is a page ID ?
A Page ID is simply a unique number used to identify a particular page in the database.
How does the DBMS know where Page ID 2 is physically stored on the disk?
That's where the indirection layer comes in.
What is an indirection layer?
An indirection layer is a mapping mechanism that translates a logical Page ID into its actual physical storage location.
Think of it like a contact list on your phone.
- You search for a person's name.
- Your phone looks up their phone number.
- It uses that number to contact them.
Similarly:
- The DBMS requests Page ID 2.
- The storage manager looks up Page ID 2 in its mapping structure.
- It finds the file path and offset where that page is stored.
- It reads the page from that location.
Mapping table kept by the storage manager (illustrative values)
Now there is an offset that is used to know from where to where we need to access the data/pages. Like from which page to which page we need to go to access some kind of data.
What is a file offset?
An offset tells us the exact position of a page inside a file.
Suppose:
- Each page is 4096 bytes (4 KB).
- Page 0 starts at byte 0.
- Page 1 starts at byte 4096.
- Page 2 starts at byte 8192.
Therefore, if the DBMS wants Page 2, it can access the file starting at byte offset 8192.
The formula :
Offset = Page ID * Page Size
Try it: pick a page size and a Page ID (0 to 9)
the indirection layer is very important and is like an optimization for searching.
Imagine a database has multiple files:
- database1.db
- database2.db
- database3.db
Page ID 2 might be in database1.db, while Page ID 500 might be in database3.db.
The upper levels of the DBMS shouldn't need to know these physical storage details.
Instead, they simply request a Page ID.
The storage manager handles the translation.
Most DBMSs use fixed-size pages to avoid the engineering overhead needed to support variable-sized pages. why ?
First, understand that a page is a fixed-size block of storage used to organize and manage data.
For example, suppose a DBMS uses pages of 4 KB each.
It divides its database storage into equal-sized blocks:
Every page has the same size, making storage management easier.
What problem occurs with variable-sized pages?
Imagine that pages have different sizes:
- Page A = 4 KB
- Page B = 8 KB
- Page C = 4 KB
They are stored consecutively in a file.
Variable-sized pages: delete page B, then try to insert a 12 KB page
Now the problem is:
Suppose the DBMS wants to insert a new page of 4 KB.
- The empty space is 8 KB.
- The new page requires only 4 KB.
- The DBMS must decide how to manage the remaining 4 KB.
- It may create fragmentation or need additional bookkeeping.
If it wants to insert a page of 12 KB, the 8 KB hole is insufficient.
This makes memory and storage management more complicated.
Solution: Fixed-size pages.
If every page is 4 KB, deleting one page creates exactly one 4 KB empty slot. Another 4 KB page can occupy that slot easily.
This simplifies allocation, deallocation and page management.
Fixed-size pages: delete one page, then insert a new one
Note: Variable-sized storage can be managed using sophisticated allocation techniques, but it introduces additional complexity.
Three main concepts of pages DBMS.
1. Hardware page
A hardware page is a block of memory used by the processor's memory-management hardware.
For example, when a program accesses memory, the processor translates virtual addresses into physical addresses.
This translation generally happens at page granularity.
A common hardware page size is 4 KB, although modern processors also support larger page sizes.
2. OS page
The operating system manages memory using pages.
For example, suppose your computer has 8 GB of RAM.
The OS divides physical memory into fixed-size units called frames and manages virtual memory in pages.
If the OS uses 4 KB pages:
8 GB = 8 × 1024 × 1024 KB = 8,388,608 KB
8,388,608 KB ÷ 4 KB = 2,097,152 frames
So, 8 GB of RAM contains 2,097,152 physical 4 KB frames (assuming all RAM is available and using binary units).
The OS uses these units to manage memory allocation, virtual memory and page swapping.
3. Database page
This is the page that matters most from the DBMS perspective.
A database page is the basic unit in which a DBMS organizes and transfers database data between disk storage and memory.
For example, suppose a database uses 8 KB pages.
The database page contains:
- Page header and metadata.
- Database records.
- Free space for inserting new records.
The DBMS reads and writes these pages as units.
How are these three pages related?
Let's take an example:
Suppose:
- Hardware page size = 4 KB.
- OS page size = 4 KB.
- Database page size = 8 KB.
the DBMS wants to read one 8 KB database page.
The operating system and hardware may handle this using two 4 KB memory pages/frames.
Why different database operations need different page layout.
First, remember:
A database page is the unit of data that the DBMS reads from or writes to storage.
The size of this page affects how efficiently the database performs read and write operations.
There are two major types of workloads.
A. Read-heavy workload
A read-heavy workload means the database performs more read operations than write operations.
For example:
- A news website where millions of users read articles.
- A search engine retrieving information.
- An analytics database reading large amounts of historical data.
Such databases may benefit from larger pages.
Why?
Imagine you want to read 100 KB of data.
Option 1: Page size = 4 KB.
You need to read:
100 KB ÷ 4 KB = 25 page reads
Option 2: Page size = 1 MB.
You need only one page read to obtain the 100 KB of data (assuming the relevant data is in that page).
Larger pages can reduce the number of page accesses and help sequential reads.
However, larger pages can also waste memory and I/O bandwidth when only a small amount of data is needed.
B. Write-heavy workload
A write-heavy workload means the database performs more write operations than read operations.
For example:
- Banking transaction systems.
- Online shopping order systems.
- Inventory management systems.
Such databases often benefit from smaller pages.
Why?
Imagine a database page contains 1 MB of data.
You want to update just one small record of 100 bytes.
Depending on the DBMS and its storage architecture, a larger page can mean:
- More data potentially needs to be written or managed.
- More unrelated records may be affected by page-level locking or latching.
- More work may be needed to maintain page consistency.
Smaller pages can reduce the amount of unrelated data involved in an update.
Try it: choose a page size
The storage device guarantees an atomic write of the size of the hardware page. (now what does this mean)
First, understand the word atomic.
Atomic means an operation happens completely or does not happen at all.
There is no partially completed operation.
Let's take the example given in your textbook.
Suppose the hardware page size is 4 KB. Here, "hardware page" means the unit the storage device itself can write atomically.
The storage device guarantees atomic writes of 4 KB.
This means:
When the system writes 4 KB to the disk, only two outcomes are possible:
- The whole 4 KB is written to the disk.
- None of it is written, and the old data stays exactly as it was.
Outcome 1: the whole 4 KB is written
Outcome 2: none of it is written, the old data stays
Not possible: half of it written
Why does this matter for a database? Remember the example above: the database page is 8 KB, but the device only guarantees atomicity for 4 KB. So writing one database page means two separate 4 KB writes.
If the power fails after the first 4 KB is written but before the second, the page on disk is half new and half old. This is called a torn page. The device did nothing wrong, because each 4 KB write was atomic on its own, but the 8 KB database page is now corrupted. This is why databases need their own protection against torn pages, for example a doublewrite buffer or full-page writes.
Heap File Organization in Database
There are a couple of ways to manage pages in files on the disk (e.g., Tree, Sequential/Sorted (ISAM), and Hashing File Organization), and Heap File Organization is one of those ways.
Heap File Organization is a method used by a Database Management System (DBMS) to store records (tuples) in a file.
- A heap file is an unordered collection of database pages.
- Records are stored in no particular order.
- Records are inserted wherever free space is available.
- It does not arrange records in ascending or descending order.
- When a new record is inserted, the DBMS searches for a page with enough free space and stores the record there.
- Insertion is simple and fast because there is no need to sort the records.
- Searching for a particular record can be slow because the DBMS may need to scan multiple pages.
Example
Suppose a student database contains records of Rahul, Amit, Priya, Sneha, Karan and Rohan.
In Heap File Organization, records may be stored in the following order:
There is no fixed order for storing records. They are stored wherever space is available.
A common architecture for the DBMS to locate a page on disk given a page id is a page directory, which are special pages that contain one location entry for each logical database objects (e.g. data pages, index pages). The page directory has to be synchronized with the actual pages. The DBMS also tracks metadata about pages’ contents, including the amount of free space on each page, a list of free/empty pages, and the page types.
structure of pages in storage .
The page contains something called a header that records the metadata about the page's contents.
It contains:
- page size
- checksum
- dbms version
- transaction visibility
Three approaches to laying out data in pages
The three main approaches to laying out data in pages are:
- tuple-oriented
- log-structured
- index-oriented
Tuple-oriented storage
Tuple-oriented storage is a method in which the entire tuple (row) is stored together in a database page.
A database page is a fixed-size block of memory or disk used to store records.
1. Strawman Approach
- In this approach, the DBMS keeps track of the number of tuples stored in a page.
- Whenever a new tuple is added, it is simply appended to the end of the page.
- However, it creates problems when tuples are deleted or when attributes have variable lengths.
Problems:
- Deletion Problem: Deleting a tuple creates empty space in the page.
- Variable-Length Problem: Records of different sizes make it difficult to manage storage space.
Strawman: tuple 2 was deleted, and now a longer tuple arrives
The new tuple is longer than the hole, so it cannot reuse it.
2. Slotted Page Structure
Slotted pages are a common storage technique used to solve these problems.
- A page contains a header, a slot directory and the actual tuples.
- The header stores information such as the number of tuples.
- The slot directory stores pointers to the locations of tuples.
- Actual tuples are stored in the remaining page space.
- When a tuple is deleted, its slot can be marked as empty.
- Variable-length tuples can be stored at different locations without disturbing the slot directory.
(I will explain log-structured and index-oriented in upcoming articles.)
Record IDs
The DBMS assigns each logical tuple a unique record identifier that represents its physical location in the database (e.g. file id, page id, slot number). Most DBMSs do not store ids in the tuple. Common record id size varies from 4 bytes to 10 bytes. Since these are physical locations within the DBMS, the application cannot rely on these IDs.
Data representation: the way data is organized, stored, and displayed in a database so that it can be easily understood, accessed, and managed.
Data Representation in Database:
- INTEGER / BIGINT / SMALLINT / TINYINT: Stored using native C/C++ integer formats.
- FLOAT / REAL: Stored using IEEE-754 format; fast but may have small precision errors.
- NUMERIC / DECIMAL: Uses fixed precision to store exact decimal values.
- VARCHAR / VARBINARY / TEXT / BLOB: Stored as a length header followed by data bytes or a pointer to the data.
- Overflow Pages: Store large values separately when they cannot fit into a single database page.
- German Strings: Store short strings inline and long strings using a prefix and pointer to reduce unnecessary data retrieval.
- External Value Storage: Stores large values in external files, but the DBMS cannot guarantee their transaction safety or durability.
- TIME / DATE / TIMESTAMP / INTERVAL: Stored as 32-bit or 64-bit integers representing time units since the Unix epoch.
- Null Column Bitmap Header: Uses a bitmap to identify NULL values in columns.
- Special Values: Uses reserved values (e.g., INT32 MIN) to represent NULL.
- Per-Attribute Null Flag: Uses a separate flag for each attribute to indicate NULL values.
Try it: VARCHAR and German strings
VARCHAR: length header, then the bytes
German string (16 bytes): 4-byte length, then 12 bytes inline or a 4-byte prefix + 8-byte pointer
FLOAT vs DECIMAL
Timestamps
The NULL bitmap
Example row: id = 7, name = NULL, age = 31, city = Pune
Bitmap header (1 = NULL), one bit each for id, name, age, city
Values actually stored