1. Home
  2. Explore
  3. Computer Science
  4. Build a Database from Scratch

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Build a Database from Scratch

  • 55Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Basic Storage and Indexing
  • spaceFlip card
  • KI knew it
  • DI didn't know it
  • ←Previous card
  • →Next card

How does MySQL store a database on disk?

Tap to flipClick to flipspace

Creates a folder for the database; each table's storage engine creates a file containing table data and indexes.

Or swipe the card

55 cards

  1. How does MySQL store a database on disk?

    Creates a folder for the database; each table's storage engine creates a file containing table data and indexes.

  2. What is the problem with using CSV format to store a database table?

    Searching for rows requires scanning byte by byte for delimiters, which is extremely inefficient.

  3. How does fixing row sizes improve search efficiency over CSV?

    With fixed-size rows, you can skip directly to the start of any row by multiplying row number by row size, avoiding delimiter scanning.

  4. Why is 255 a common maximum length for database string fields?

    Because 1 byte (8 bits) can store values up to 255, so the string length can be stored in a single byte.

  5. Given a table with an integer primary key (4 bytes) and a string of max 255 characters (1 byte length + 255 bytes content), what is the total row size in ASCII?

    4+1+255=2604 + 1 + 255 = 2604+1+255=260 bytes.

  6. What is the time complexity of searching for a row by primary key in a table with fixed-size rows but no index?

    O(n)O(n)O(n), linear scan.

  7. Why do databases need indexes?

    To achieve O(log⁔n)O(\log n)O(logn) search time instead of O(n)O(n)O(n), essential for large datasets.

  8. How would you use a binary tree to index a table with fixed-size rows?

    Store a balanced binary tree in memory where each node contains a primary key value and a pointer (row number) to the row in the file; traverse the tree to find the key and then compute the file offset.

  9. What problems arise when using a standard binary tree as a database index?

    1. Unbalanced tree leads to O(n) worst-case search. 2) Storing the tree on disk is difficult; if the index is too large for RAM, it cannot be efficiently paged.
  10. Why can't you always load the entire binary tree index into memory?

    The index can be gigabytes in size for large databases (hundreds of millions of rows, terabytes of data), exceeding available RAM.

  11. What is a B-Tree?

    A self-balancing tree data structure that maintains sorted data and allows O(log n) search, insertion, and deletion, designed to work well on disk.

  12. What are the two key problems of binary trees that B-Trees solve?

    1. Self-balancing (no linked-list degeneration). 2) Efficient disk storage (each node corresponds to a disk block, minimizing I/O).
  13. In a B-Tree with minimum children per node C=2, what is the maximum number of keys per node?

    2Cāˆ’1=32C - 1 = 32Cāˆ’1=3.

  14. In a B-Tree with C=2, what are the minimum and maximum number of children for internal nodes (excluding root and leaves)?

    Minimum: C=2C = 2C=2 children. Maximum: 2C=42C = 42C=4 children.

  15. Describe the B-Tree insertion algorithm when a node is full.

    1. Take the median key. 2) Move median up to parent. 3) Split node into two nodes containing keys less than and greater than median. 4) Insert the new key into appropriate node. If parent full, recurse; if root full, create new root with median key.
  16. Why does B-Tree insertion always result in a balanced tree?

    The splitting mechanism ensures that all leaves remain at the same depth, and no node becomes a long chain.

  17. Why must database storage be aware of disk block sizes?

    Disk I/O reads and writes data in fixed-size blocks (e.g., 512 bytes, 4096 bytes); you cannot read individual bytes efficiently.

  18. How is a B-Tree stored in a file for disk-based databases?

    Each B-Tree node is stored in one disk block (or page). The file is a sequence of blocks; the first block contains the root node, and children pointers are block numbers.

  19. How does a B-Tree node point to its child nodes in a file?

    Each pointer is a block number (or page number). To read a child, the database calculates the offset by multiplying the block number by the block size.

  20. What determines the maximum number of keys in a B-Tree node when stored on disk?

    The disk block size and the sizes of keys and pointers: you fit as many keys and pointers as possible into one block.

  21. What is a slotted page and why is it used?

    A page structure where a slot array at the start stores fixed-size offsets to variable-length cells at the end. It allows efficient insertion and binary search on variable-length records without moving large amounts of data.

  22. In a slotted page, how is a new variable-length record inserted while maintaining sorted order?

    The record data is placed at the end of the free space, and its offset is added to the slot array. The slot array is shifted to maintain order; shifting offsets (2 bytes each) is cheaper than moving the large records.

  23. How does binary search work on a slotted page?

    The slot array contains fixed-size entries (2-byte offsets), so binary search can be performed on the keys stored in the cells pointed to by the slots.

  24. In a B-Tree page using slotted layout, where are child pointers stored?

    In the header of each cell (the record/page entry). The pointer indicates the page number of the child node.

  25. What does a cell in a B-Tree page contain?

    Typically includes a child pointer (page number), the key value, and optionally the row data (if storing table rows) or a pointer to the row (if heap storage).

  26. What is heap storage in databases?

    Rows are stored in unsorted pages (heap) without any inherent order. A separate index (e.g., B-Tree) maps keys to row locations (page number + slot offset). A page directory manages free space.

  27. What is index-organized storage?

    The table itself is stored as a B-Tree sorted by primary key. Each B-Tree node contains rows (cells) directly. Secondary indexes store the primary key as the value, so a lookup requires two B-Tree traversals.

  28. What are the advantages of index-organized storage over heap storage?

    1. No need for a separate page directory; free space management is handled by the B-Tree. 2) Primary key lookups are efficient (direct B-Tree search). 3) Reuses B-Tree code for both indexes and table storage.
  29. In index-organized storage, how does a secondary index point to a row?

    The secondary index stores the primary key value as a pointer. To retrieve the row, the system first searches the secondary index B-Tree for the primary key, then searches the table B-Tree for that primary key.

  30. In heap storage, how does a secondary index point to a row?

    The index stores the row's physical location (page number and slot offset). Thus, a lookup returns the direct location without a second B-Tree search.

  31. Does MKDB use heap or index-organized storage?

    Index-organized storage (like SQLite).

  32. What is an overflow page and when is it used?

    A page used to store data that does not fit entirely within a single B-Tree page. When a row's size exceeds a threshold (e.g., 25% of page size), part of the data is stored in overflow pages linked together as a singly linked list.

  33. How is an overflow page linked to the original cell?

    The cell in the B-Tree page includes a pointer (page number) to the first overflow page. Each overflow page contains a header pointing to the next overflow page, forming a chain.

  34. Why does variable-length cell size complicate B-Tree page management?

    The number of keys per page is not fixed; it depends on the actual sizes of the keys/data. This prevents using simple formulas for splitting and makes balancing more complex.

  35. What is a problem with the default B-Tree splitting algorithm when inserting sequential keys?

    Each split leaves the left page only half full, leading to space waste.

  36. How does the modified B-Tree balancing algorithm address the space waste issue?

    Instead of splitting immediately when a page is full, it first tries to redistribute keys among sibling pages. Splitting is delayed until no more space can be reclaimed, resulting in higher page utilization.

  37. What are the steps involved in processing an SQL statement in MKDB?

    1. Tokenizer converts string into tokens. 2) Parser builds an Abstract Syntax Tree (AST). 3) Analyzer validates table and column references. 4) Optimizer simplifies the AST. 5) Query plan generation: converts AST into a tree of plan nodes. 6) Execution: plan nodes use the iterator model to fetch tuples.
  38. What is Top Down Operator Precedence (TDOP) parsing?

    A parsing algorithm from the 1970s that uses mutually recursive functions to handle operator precedence, making expression parsing straightforward.

  39. What is the iterator model in query execution?

    Each plan node implements a .next() method that returns one tuple at a time. Plan nodes call their children's .next() to fetch tuples, allowing processing of large datasets row by row without loading everything into memory.

  40. In the query plan, what does a scan node do?

    It iterates over all rows in a table (or an index), returning one tuple at a time. It uses a cursor to track the current position in the page structure.

  41. What is the purpose of a projection in query plans?

    To select specific columns from a tuple (row) and discard others, implementing the SELECT clause.

  42. What is the K-Way External Merge Sort algorithm used for?

    Sorting data that does not fit into main memory (RAM) by dividing it into pages and performing multiple passes of merging, using only K+1 buffers in memory.

  43. How does pass zero of K-Way External Merge Sort work?

    Read K pages from the file into memory, sort them, and write them back as a single sorted run of K pages. Repeat for all data.

  44. In K-Way External Merge Sort, what does each subsequent pass do?

    Merges K sorted runs into one longer sorted run, using K input buffers (one for each run) and one output buffer. The run sizes multiply by K each pass.

  45. In K-Way External Merge Sort, what is the number of passes required to sort N pages?

    Approximately ⌈log⁔K(N)āŒ‰\lceil \log_K(N) \rceil⌈logK​(N)āŒ‰ passes.

  46. Why is external merge sort efficient for large datasets?

    The number of passes is logarithmic in the number of pages, so the amount of I/O is significantly reduced compared to naive sorting.

  47. What is the clock algorithm for page replacement?

    A circular list of cached pages with a reference bit. A clock hand moves around, resetting reference bits. The first page found with reference bit 0 is evicted (if dirty, written to disk first). Newly accessed pages get reference bit set to 1.

  48. What are the two metadata bits associated with each cached page in the clock algorithm?

    Reference bit (indicates recent access) and dirty bit (indicates that the page has been modified since being read from disk).

  49. How does the clock algorithm decide which page to evict when the cache is full?

    It starts from the current clock hand position and scans forward. For each page: if reference bit is 1, reset it to 0 and move to next page. If reference bit is 0, that page is selected for eviction (after writing to disk if dirty). The hand then points to the next position for future scans.

  50. What is a journal file and how is it used for transactions in MKDB?

    A file created before a transaction modifies pages. The original page contents are written to the journal. If the transaction commits, the journal is deleted. If it rolls back, the journal contents are copied back to the database file, undoing changes.

  51. What is the limitation of using a simple journal file for transactions?

    It only supports one transaction at a time. For concurrent transactions, more sophisticated mechanisms like Write Ahead Log (WAL) are needed.

  52. In the context of databases, what is the Write Ahead Log (WAL)?

    A write-ahead log records all changes made by transactions before they are applied to the database files. It enables crash recovery and supports multiple simultaneous transactions with isolation.

  53. What protocol does MKDB use for client-server communication?

    A custom protocol over TCP, inspired by the Redis protocol. It is designed to be simple and allow clients in any programming language.

  54. How does MKDB store all database data on disk?

    In a single file, similar to SQLite. All tables, indexes, and overflow pages are stored as a sequence of 4 KiB pages in one file.

  55. How does MKDB keep track of the root pages of tables and indexes?

    It uses a special metadata table called "mkdb_meta" that stores the schema and pointers to the root pages of each B-Tree (table or index).

Card 1 of 55
Card 1 of 55

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent