CMD Guide
HomeDatabases

Database

Step 13 in the Databases path · 5 concepts · 0 problems

0 / 5 complete

📘 Learn Database from zero

Imagine a giant filing cabinet run by a meticulous clerk. You don't dig through the drawers yourself — you hand the clerk a request ("give me all orders by Maya in May"), and the clerk fetches, files, and keeps everything tidy, even if ten people ask at once. The filing cabinet is the database (the stored data). The clerk is the DBMS (Database Management System) — the software that creates, reads, writes, secures, and protects the data, controlling all access to keep it consistent. You rarely talk to the cabinet directly; you talk to the clerk.

A database is an organized collection of data stored so it can be efficiently retrieved, updated, and kept safe across crashes and concurrent users. The DBMS (Postgres, MySQL, MongoDB) is the engine providing those guarantees. DBMSs split into two families: relational (RDBMS), which store data in tables and query with SQL, and non-relational (NoSQL), which store key-value, document, wide-column, or graph data with a flexible schema.

The dominant model is relational, introduced by Edgar F. Codd in 1970. Data lives in tables (like spreadsheets). Each row is one record, each column a field. A primary key uniquely identifies a row; a foreign key in one table points at another's primary key, linking them.

Worked example. A store has two tables. users(id, name) with row (1, "Maya"), and orders(id, user_id, total) with row (99, 1, 40). Here orders.user_id = 1 is a foreign key pointing to users.id = 1. To answer "what did Maya order?", the DBMS performs a JOIN, matching rows where users.id = orders.user_id, returning ("Maya", 40). You never duplicate Maya's name in the orders table — you link.

Key insight: a database isn't just "saved data" — it's data plus a DBMS that guarantees persistence, concurrent correctness, and efficient querying. The relational model wins when data is structured and related (strong consistency, ACID); non-relational models trade some of those guarantees (often for BASE/eventual consistency) in exchange for flexible schemas and horizontal scale.

✨ Added by the guide to build intuition — not from the source course.

🎯 Guided practice

  1. Easy — File vs. database. An app currently stores users in a plain text file and, on each login, reads the whole file line-by-line to find a match. At 10 million users logins are slow and two simultaneous signups sometimes corrupt the file. What changes when you move to a DBMS?

    Reasoning: Identify the failures. (1) Lookup cost: scanning the file is O(n) per login. A database with an index on the username column makes it O(log n) via a B-tree — the core win. (2) Concurrency: the corruption is a race condition; a DBMS serializes conflicting writes via locks/transactions, so two signups can't clobber each other. (3) Durability: a crash mid-write to a file can lose data; a DBMS uses write-ahead logging to recover. Pattern: when you hear "search-by-field," "many concurrent writers," or "must not lose data," that's the signal to reach for a DBMS — and to add an index on the queried column.

  2. Medium — SQL or NoSQL? You're designing two systems in an interview: (A) a bank ledger tracking account balances and transfers; (B) a social feed storing posts where each post may have different optional fields (image, poll, location) and you expect billions of posts with very high write volume. Pick a database type for each and justify.

    Reasoning: For (A), the non-negotiable requirement is correctness under concurrency: a transfer must atomically debit one account and credit another — both happen or neither (the A in ACID), and the balance must always be exact (strong consistency). Relationships (accounts, transactions) need JOINs. → Choose a relational (SQL) database. Sacrificing consistency for scale is unacceptable here.

    For (B), the drivers are flexible/evolving schema (posts have heterogeneous fields) and massive horizontal write scale. A fixed relational schema fights you, and a single vertically-scaled SQL node won't absorb billions of writes cheaply. → Choose a non-relational store — a document DB (e.g. MongoDB) for the per-post flexible shape, or a wide-column store (e.g. Cassandra) for write-heavy scale, accepting eventual (BASE) consistency (a follower seeing a post a second late is fine). Pattern (canonical SQL-vs-NoSQL frame): map requirements onto the decision axes — data model/schema, scalability (vertical vs horizontal), consistency/transactions (ACID vs BASE, CAP), and query complexity. Strong consistency + transactions + relationships + JOINs ⇒ SQL (Alex Xu's default). Schema flexibility + horizontal scale + tolerance for eventual consistency ⇒ NoSQL. Always justify by the workload, never by fashion.

✨ Added by the guide — work these before the full problem set.

Lessons in this topic

🧠 Review & recall

Active recall is what moves a topic into long-term memory. Flip each card before revealing, then test yourself — your results are saved on this device.

Flashcard
What is a database, and how does it differ from storing data in a plain file?
tap to reveal →
A database is a systematic, organized collection of data that supports efficient storage, retrieval, and manipulation. Unlike traditional files, it supports structured data management (e.g. tables), scalability, data integrity, concurrent access, and security.
💡 Filing cabinet (data) + meticulous clerk (DBMS) — you never dig through drawers yourself.
Flashcard
What is a DBMS and what are its four key functions?
tap to reveal →
A DBMS (Database Management System) is the software that creates, maintains, and controls all access to a database, guaranteeing integrity, consistency, and security. Its four key functions are: Defining (data types/structures/constraints), Constructing (storing data), Manipulating (querying and updating, e.g. via SQL), and Sharing (concurrent multi-user access).
💡 DBMS = Define, Construct, Manipulate, Share. A 'database system' = database + DBMS together.
Flashcard
In the relational model, define table, row, column, and primary key — and who introduced this model?
tap to reveal →
A table (relation) stores data in rows and columns and represents one entity. A row (tuple) is a single record; a column (attribute) is a field with a data type/constraint. A primary key is a unique identifier for each row, preventing duplicate records. The relational model was introduced by Edgar F. Codd in 1970.
💡 Codd 1970: Table=relation, Row=tuple, Column=attribute, PK=unique fingerprint.
Flashcard
How does a foreign key link two tables, and what operation answers 'what did Maya order'?
tap to reveal →
A foreign key in one table points at another table's primary key. With users(id,name)=(1,'Maya') and orders(id,user_id,total)=(99,1,40), orders.user_id=1 is a foreign key to users.id=1. A JOIN matches rows where users.id=orders.user_id, returning ('Maya',40) — you link instead of duplicating Maya's name.
💡 FK points at PK; JOIN follows the pointer — link, don't duplicate.
Flashcard
Contrast SQL (relational) vs NoSQL (non-relational) on schema, scaling, and consistency.
tap to reveal →
Relational: fixed/predefined schema, vertical scaling (more power to one server), strong ACID compliance, high integrity — best for financial systems, CRM, ERP. Non-relational: flexible schema, horizontal scaling (more servers), typically BASE properties, app-managed integrity — best for real-time analytics, content management, IoT.
💡 SQL = Schema-fixed, Scale-up, ACID. NoSQL = flexible, Scale-out, BASE.
Flashcard
Name the four data models NoSQL databases can use, with an example system for each family.
tap to reveal →
NoSQL stores structured, semi-structured, or unstructured data as: documents (MongoDB), key-value pairs (Redis), graphs (Neo4j), and wide-column/columnar (Cassandra). They are optimized for large-scale data and fast read/write operations.
💡 Doc-Key-Graph-Column → Mongo, Redis, Neo4j, Cassandra.
Q1. You are designing a bank ledger that tracks account balances and transfers, where a transfer must atomically debit one account and credit another. Which database type fits best and why?
Q2. Which characteristic is listed as a benefit of relational databases, allowing applications to be unaffected by changes to the physical data structure?
Q3. According to the lessons, how do relational and non-relational databases typically differ in scaling approach?
Q4. In a DBMS-backed banking system, an accountant queries the number of outstanding accounts. What is the correct path of that request?
Q5. Which set correctly pairs each NoSQL data model with a listed example system?