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

Speaker 1Speaker 2

Build a Database from Scratch

5:09
0:00-5:09
  1. Simon

    Michael, have you ever wondered what happens inside a database when you run a simple query? I mean, we use them every day, but the internals are like a black box.

  2. Michael

    Absolutely. And that's exactly what this video is about. The creator, named mk or something, decided to build a toy database from scratch and document the whole journey. It's a wild ride.

  3. Simon

    Right. He starts with his limited understanding – he knows that MySQL stores databases as folders and tables as files, and that those files contain both the data and an index built with a B-Tree or B+Tree. But he doesn't know how that actually works.

  4. Michael

    So he decides to experiment. First, he tries storing rows in a CSV-like format with delimiters, but that's terrible for performance because you can't jump between rows. Then he switches to fixed-size rows: 4 bytes for an integer primary key, 1 byte for string length, and 255 bytes for the string itself. That gives 260 bytes per row.

  5. Simon

    With fixed-size rows, you can at least skip linearly by 260 bytes, but that's still O(n). So he considers using a binary tree in memory for the index. But binary trees aren't balanced by default, and storing them on disk is a nightmare. Plus, if the index is huge, it won't fit in RAM.

  6. Michael

    That's where B-Trees come to the rescue. A B-Tree is self-balancing and each node can hold multiple keys and children. In his example, with a minimum children count of 2, the maximum keys per node becomes 3. When you insert keys in ascending order, you hit the maximum, take the median, move it up, split the node, and continue. This keeps the tree balanced, so search is always O(log n).

  7. Simon

    And for storage, he exploits the fact that disks read in blocks. He defines a 'page' of 4 KiB, which equals one block. Each B-Tree node is stored in a single page. Child pointers become page numbers – just multiply to jump to any page. So the file is just a sequence of 4 KiB pages containing B-Tree nodes.

  8. Michael

    But rows can be variable-length. To store them efficiently, he uses 'slotted pages'. The page has a slot array at the beginning that grows rightward, and the actual variable-length data ('cells') grows leftward. The slot array stores offsets, so you can binary search on fixed-size slots and shift just a couple of bytes when inserting, instead of moving the entire data.

  9. Simon

    Now, how do external indexes point to rows? He chooses index-organized storage, like SQLite. The table itself is a B-Tree sorted by primary key, so each cell is a row. An index on another column, say email, stores the email and the primary key. To find a row by email, you first find the email in the index B-Tree, then look up the primary key in the table B-Tree. That's two O(log n) lookups, but it avoids needing a separate row location that might change.

  10. Michael

    And what about rows that are larger than a page? He uses overflow pages. If a row exceeds a quarter of the page size, the first chunk goes in the B-Tree cell, and the last 4 bytes point to an overflow page. That overflow page has a header pointing to the next overflow page, forming a linked list. When reading the row, you reassemble the chunks.

  11. Simon

    So the database file is a collection of table B-Trees, index B-Trees, and overflow pages – all just 4 KiB pages. That's the storage engine. Next comes the SQL layer. The user sends a string, which goes through a tokenizer, then a parser using Top-Down Operator Precedence to produce an Abstract Syntax Tree.

  12. Michael

    Then an analyzer checks for semantic errors, and an optimizer simplifies the AST. Finally, the AST is translated into a query plan – another tree, but this one uses the iterator model. Each node in the plan is an iterator over tuples. You call .next() on the top-level plan, which chains down to a scan node at the bottom. That scan has a cursor that reads rows one by one from the storage engine, using no memory beyond the cursor.

  13. Simon

    That iterator model handles large datasets because you process a single tuple at a time. But some operations, like sorting, need the entire dataset. For that, he implements a 'collect plan' that writes tuples to a temporary file if they don't fit in RAM. Then he uses the K-Way External Merge Sort algorithm.

  14. Michael

    External merge sort is clever. Say you have K=2 buffers. Pass 0 creates sorted runs of 2 pages each. Pass 1 merges two 2-page runs into 4-page runs, and so on. The number of passes is logarithmic, and you only load K pages at a time. So even terabytes of data can be sorted with limited memory.

  15. Simon

    For caching, he uses a clock algorithm. Pages in cache have a reference bit and a dirty bit. When the cache is full and a new page is needed, a clock pointer sweeps through, clearing reference bits. The first page it finds with ref bit 0 is evicted; if dirty, it's written back first. This is simple but effective.

  16. Michael

    Transactions are implemented with a journal file. Before modifying a page, the original content is copied to the journal. On a crash or rollback, those original pages are copied back. On commit, the journal is deleted. That's enough for single-threaded transactions, but production systems use Write-Ahead Logging for concurrency.

  17. Simon

    Finally, the whole thing is served as a TCP server with a simple protocol inspired by Redis. The creator notes that the code is 25,000 lines but heavily documented and meant for learning. He acknowledges it's not production-quality but hopes it demystifies databases.

  18. Michael

    Honestly, after hearing all that, I have a whole new respect for database engineers. Building one from scratch involves so many interlocking pieces: B-Trees, slotted pages, overflow pages, parsers, query plans, external sorting, caching, transaction journals… it's a huge undertaking.

  19. Simon

    Absolutely. And this project is a fantastic way to learn because you see how each component fits together. If anyone wants to dive deeper, the source code is on GitHub. But for now, let's just appreciate the complexity behind the simple 'SELECT * FROM users'.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent