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

  • 34Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Database Storage Fundamentals

Why is storing data in CSV format problematic for a database, and how does using fixed-size rows address this issue?

34 questions

  1. 1

    Why is storing data in CSV format problematic for a database, and how does using fixed-size rows address this issue?

    Model answer

    CSV requires linear search for row delimiters, making it inefficient. Fixed-size rows allow direct access by multiplying row size by row number, enabling O(1) jumps to any row.

    Explanation

    CSV uses delimiters like commas and newlines, forcing byte-by-byte scanning to find rows. Fixed-size rows eliminate delimiters, so the row location can be computed directly from the row number and row length.

  2. 2

    In a fixed-size row format, if a table has an integer primary key (4 bytes) and a variable-length name (max 255 chars, 1 byte for length), what is the total row size in bytes?

    Model answer

    260 bytes: 4 (ID) + 1 (length) + 255 (max name) = 260.

    Explanation

    The row size is the sum of column sizes: the integer is 4 bytes, the length byte is 1, and the string capacity is 255 ASCII characters = 255 bytes, totaling 260 bytes.

  3. 3

    Why is searching a flat file of fixed-size rows still O(n) even though you can jump by row size?

    Model answer

    Without an index, you must examine each row’s primary key sequentially until a match is found, which is O(n).

    Explanation

    You can skip to the next row, but you still need to check each row one by one because there is no ordering that allows binary search. An index is required for O(log n).

  4. 4

    What are two major problems with using a normal binary tree as an index stored in memory?

    Model answer

    First, the tree can become unbalanced (e.g., a linked list) if inserted in ascending order, degrading search to O(n). Second, if the tree is too large to fit in memory, it cannot be stored entirely in RAM.

    Explanation

    Binary trees are not self-balancing by default, so sequential insertion leads to a skewed tree. Additionally, the index may be gigabytes, exceeding available memory, making disk storage necessary.

  5. 5

    How does a B-Tree differ from a binary tree in terms of node structure and children?

    Model answer

    B-Tree nodes can hold multiple keys and have more than two children, unlike binary trees which have one key and two children.

    Explanation

    In a B-Tree, each internal node contains between C-1 and 2C-1 keys (where C is the minimum degree) and between C and 2C children. This allows the tree to stay short and wide, reducing disk I/O.

  6. 6

    For a B-Tree with a minimum children count C = 2, what is the maximum number of keys per node?

    Model answer

    3 keys (2C - 1 = 3).

    Explanation

    With minimum children = 2, maximum keys = 2*2 - 1 = 3. This is a common property used to keep the tree balanced.

  7. 7

    Describe the insertion process in a B-Tree when the target node is full (has reached maximum keys).

    Model answer

    The median key is promoted to the parent node. If there is no parent (root), a new root is created. The original node is split into two nodes containing keys less than and greater than the median, respectively. Then the new key is inserted into the appropriate child node.

    Explanation

    This self-balancing mechanism ensures the tree remains balanced. The median becomes a separator in the parent, and the split creates two nodes that each have minimum occupancy. For root, a new level is created.

  8. 8

    Why does the B-Tree insertion algorithm guarantee that the tree remains balanced regardless of insertion order?

    Model answer

    Whenever a node becomes full, it is split, and the median moves upward. This ensures all leaf nodes remain at the same depth, so the tree height grows only when the root splits.

    Explanation

    The algorithm prevents any node from having too many children by consistently redistributing keys. This keeps all paths from root to leaf equally long, guaranteeing O(log n) search.

  9. 9

    Why are B-Tree nodes typically stored as whole blocks (e.g., 4 KiB) on disk?

    Model answer

    Disk reads are done in blocks; storing each node in one block minimizes I/O operations because accessing a node costs exactly one block read.

    Explanation

    Since disk I/O is block-oriented (typically 512 B to 4 KiB), aligning node size to block size allows reading a complete node with a single operation, reducing seek time and overhead.

  10. 10

    How do B-Tree nodes point to their children on disk?

    Model answer

    Children pointers are block numbers (or page numbers). By multiplying the block number by the block size, you can directly seek to that child’s location in the file.

    Explanation

    The file is a sequence of blocks; each child pointer is an integer offset that can be used with base + offset * block_size to locate the block.

  11. 11

    What is a slotted page and why is it used in database storage?

    Model answer

    A slotted page organizes variable-length data by storing a fixed-size slot array (with offsets) at the beginning of the page and variable-length cells at the end, growing toward each other. This allows efficient binary search and insertion without moving large amounts of data.

    Explanation

    The slot array provides fixed-size pointers to the cells. Inserting a new cell only requires appending it at the end and updating the slot array, which is cheap because slots are small (e.g., 2 bytes). Binary search is done on the sorted slots.

  12. 12

    How does the slot array enable efficient binary search in a slotted page?

    Model answer

    The slot array contains keys (or pointers to keys) in sorted order, and each slot has a fixed size, so binary search can be performed on the array without moving variable-length data.

    Explanation

    Since slots are small and uniformly sized, the search can quickly narrow down the target key. Once the slot is located, the corresponding variable-length cell is accessed via the offset stored in the slot.

  13. 13

    What are overflow pages and when are they used?

    Model answer

    Overflow pages are extra pages used when a row exceeds a certain threshold (e.g., 1/4 of the page size). The row’s payload is split across multiple pages linked together in a chain.

    Explanation

    When a row is too large to fit in a single page, its data is stored in a linked list of overflow pages. The B-Tree cell holds the first chunk and a pointer to the next overflow page, allowing the row to be reassembled when read.

  14. 14

    Compare the database file organization of Postgres and SQLite as described in the content.

    Model answer

    Postgres stores each table and index in separate files (one file per object) and uses a page directory. SQLite stores all tables and indexes in a single file using index-organized storage (tables are B-Trees).

    Explanation

    Postgres has additional metadata management (page directory) for heap storage. SQLite’s approach simplifies file management but requires secondary indexes to point to primary keys rather than direct row locations.

  15. 15

    What is index-organized storage and what is its main advantage?

    Model answer

    Index-organized storage stores table data as a B-Tree sorted by primary key, so each cell is a row. The main advantage is that the primary key index is automatically available, and the same B-Tree code can be reused for both tables and indexes.

    Explanation

    In this approach, the table itself is the primary key index. This reduces the number of different data structures needed. However, secondary indexes must store the primary key (not a row pointer), requiring two B-Tree lookups.

  16. 16

    In index-organized storage, how does a secondary index (e.g., on email) point to a row?

    Model answer

    The secondary index stores the email and the corresponding primary key. To retrieve the row, you first find the email in the secondary B-Tree, get the primary key, then search the table B-Tree for that primary key.

    Explanation

    This requires two B-Tree traversals (one for the index, one for the table), unlike heap storage where the index stores the exact page and slot, allowing direct row access.

  17. 17

    What is the purpose of a page directory in Postgres’ storage model?

    Model answer

    The page directory keeps track of free pages and free space within each table file, allowing efficient allocation of new pages and reuse of freed space without scanning the entire file.

    Explanation

    Without a page directory, finding space for a new row would require scanning pages linearly, which is inefficient. The directory provides a map of page metadata, like a free space map.

  18. 18

    Name the four stages of the parsing pipeline described for SQL statements.

    Model answer

    Tokenizer, parser, analyzer, and optimizer.

    Explanation

    The tokenizer converts input characters into tokens; the parser produces an Abstract Syntax Tree (AST); the analyzer performs context checks (e.g., table existence, datatype correctness); the optimizer simplifies the AST for more efficient execution.

  19. 19

    What parsing algorithm was used in the project to build the AST?

    Model answer

    Top-Down Operator Precedence (TDOP) parsing.

    Explanation

    TDOP is a 1970s algorithm that uses mutual recursion between functions associated with operators. It handles operator precedence naturally by assigning binding power to operators.

  20. 20

    What is a query plan and how does the iterator model work?

    Model answer

    A query plan is a tree of iterators, each representing a step like scanning, filtering, or projection. The iterator model processes tuples one by one via a .next() method, so only one tuple is in memory at a time.

    Explanation

    The root of the plan calls .next() on its child, which calls its child, and so on down to a scan node that reads rows from disk. This allows processing large datasets without loading everything into memory.

  21. 21

    What is the collect plan used for in the query execution engine?

    Model answer

    The collect plan gathers all tuples from its source into a buffer (and spills to disk if the buffer overflows) so that algorithms like sorting can work on the full dataset.

    Explanation

    Operations like sorting require seeing all tuples; the collect plan materializes the intermediate results, possibly into a temporary file, enabling subsequent operators to process the entire set.

  22. 22

    For external merge sort with K=2, explain how the run sizes grow from pass 0 to pass 2.

    Model answer

    Pass 0 produces runs of 2 sorted pages (2-page runs). Pass 1 merges two such passes into 4-page runs. Pass 2 merges two 4-page runs into 8-page runs. Each pass multiplies run length by K (2).

    Explanation

    The algorithm uses K input buffers to merge K runs at a time. The run length doubles each pass because it merges K runs of previous length L into a run of length K*L.

  23. 23

    How does increasing K (number of input buffers) in K-way external merge sort affect performance and memory usage?

    Model answer

    Higher K reduces the number of passes (log_K of dataset size), decreasing I/O, but requires more RAM for K buffers. The trade-off is I/O vs. memory.

    Explanation

    With more buffers, each pass merges more runs, so fewer passes are needed. However, each buffer holds a page, so K directly increases memory consumption.

  24. 24

    Describe the clock algorithm for page replacement in a cache.

    Model answer

    The cache is a circular array of pages, each with a reference bit. A clock pointer moves around; if the pointed page is referenced, it resets the bit and moves on; if unreferenced, that page is evicted. If the page is dirty, it is written back to disk first.

    Explanation

    The algorithm approximates LRU without full tracking. Pages that are referenced frequently keep their reference bit set, so the clock skips them, aging them out only after they go unreferenced long enough.

  25. 25

    What does the dirty bit in a cache page indicate, and what happens when such a page is evicted?

    Model answer

    The dirty bit indicates the page has been modified in memory. When evicted, the page must be written back to disk before eviction to preserve the changes.

    Explanation

    A clean page (not dirty) can be evicted without disk write. Dirty pages must be flushed to avoid data loss. Some caches also write dirty pages asynchronously to avoid blocking eviction.

  26. 26

    How does the journal file (rollback journal) method implement commit and rollback?

    Model answer

    Before modifying a page, its original contents are written to the journal file. On commit, the journal file is deleted. On rollback, the original pages are copied from the journal back to the database file.

    Explanation

    This technique ensures atomicity: either all changes are applied (commit deletes journal) or none are (rollback restores from journal). It works for single-transaction systems but not for concurrent transactions.

  27. 27

    What is a Write-Ahead Log (WAL) and how does it improve upon the journal file approach?

    Model answer

    WAL records changes to a log before applying them to the database. It supports multiple concurrent writers and allows readers to see committed consistent states without blocking.

    Explanation

    WAL enables better concurrency control: writes append to the log, and the database pages can be updated later. This design allows multiple transactions in progress simultaneously, unlike the journal which locks one transaction.

  28. 28

    In the given project, how is concurrency handled for multiple connections?

    Model answer

    A mutex is used to allow only one transaction at a time. Other connections block until the current transaction completes.

    Explanation

    This simple approach avoids complex concurrency issues. Each statement is a transaction if not explicitly started; the mutex ensures serialization.

  29. 29

    Why is storing variable-length strings without wasting space significantly more complex than using fixed-size fields?

    Model answer

    Variable-length strings make row sizes unpredictable, preventing direct jumping by index and complicating binary search on disk. Slotted pages and careful offset management are needed to maintain performance.

    Explanation

    Fixed-size rows allow simple arithmetic for row locations. With variable data, the database must manage offsets, use slotted pages, and handle overflow pages for large rows, adding substantial implementation complexity.

  30. 30

    What is the primary key index in index-organized storage and how does it affect queries searching by primary key?

    Model answer

    The primary key index is the table itself (the B-Tree). Queries by primary key directly search the table B-Tree in O(log n), without needing a separate index lookup.

    Explanation

    Because the table is organized as a B-Tree on the primary key, a primary key search is simply a B-Tree traversal. This is an automatic performance benefit compared to heap storage.

  31. 31

    Why did the project use a custom network protocol inspired by Redis rather than a standard protocol?

    Model answer

    The Redis protocol is simple and easy to implement, allowing the project to focus on database internals rather than complex protocol parsing.

    Explanation

    A custom protocol with simple commands and responses makes the server communicate efficiently without the overhead of, say, PostgreSQL’s protocol. It was designed for learning, not production.

  32. 32

    What are some features explicitly excluded from the toy database project?

    Model answer

    Foreign keys, joins, GROUP BY, and subqueries are not supported.

    Explanation

    These relational database features add significant complexity. The project focused on core storage, indexing, and basic CRUD operations to keep the scope manageable for a learning exercise.

  33. 33

    How does the analyzer component of the parser improve the AST?

    Model answer

    The analyzer performs context-dependent checks, such as verifying table existence, column data types, and resolving name references, producing a semantically valid AST.

    Explanation

    After parsing, the analyzer validates that the SQL statement makes sense in the current database schema. It may also resolve star expansions and type casts.

  34. 34

    What is the role of the optimizer in the query compilation pipeline?

    Model answer

    The optimizer simplifies the AST to avoid redundant computations, such as constant folding or removing unnecessary subexpressions, because the interpreter is slower than native CPU execution.

    Explanation

    Since queries run on an interpreter, each operation has overhead. The optimizer reduces the number of operations by applying algebraic simplifications, making execution faster.

1 of 34
Question 1 of 34

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent