Skip to main content

πŸ—„οΈ Database Concepts and Types

Every serious application needs a reliable place to keep its data. This lesson builds your mental model of what a database is, the vocabulary every backend developer uses daily, and the major database families β€” so you can reason about storage instead of memorizing product names.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Explain what a database and a DBMS are, and why they beat flat files
  • Define the core concepts: schema, ACID, transactions, normalization, and indexes
  • Compare the major database families β€” relational and the four NoSQL types
  • Apply a decision framework to choose the right database for a given workload

Estimated Time: 30–40 minutes  β€’  Difficulty: Beginner

Hands-on: Design the data model for a small library system and justify your database choice.

In This Lesson

What Is a Database?

A database is an organized collection of data that a computer can store, search, update, and protect efficiently. From the messages you send, to your shopping history, to a bank's ledger of transactions β€” all of it lives in databases. Anything an app needs to remember after the user closes the tab has to be persisted somewhere, and that somewhere is almost always a database.

πŸ’‘ A useful analogy: Think of a database as a digital filing cabinet. A physical cabinet has drawers holding folders holding documents. A database has tables (or collections) holding records made of fields β€” but with superpowers: it can find any document in milliseconds, stop two clerks from corrupting the same file, and roll back a mistake as if it never happened.

You rarely talk to the raw data files yourself. Instead you talk to a Database Management System (DBMS) β€” the software that sits between your application and the stored bytes, handling storage, security, concurrency, and query optimization. PostgreSQL, MySQL, MongoDB, and Redis are all DBMSs.

πŸ“– Key Terms

Database: the organized collection of data itself.

DBMS: the software that manages that data (the "librarian").

Query: a request for the DBMS to read or change data.

Record / Row / Document: a single item of data (e.g. one user).

Field / Column / Attribute: a single property of a record (e.g. an email).

Where the DBMS sits An application sends queries to the DBMS, which manages the underlying database files on disk and returns results back to the application. Application your backend code DBMS PostgreSQL Β· MongoDB Stored Data files on disk query results
Figure 1 β€” Your application never touches the raw files directly. It asks the DBMS, which does the heavy lifting.

Why Not Just Use Files?

Before databases, applications stored data in plain files. Imagine a business keeping its customers in a text file:

# customers.csv (flat-file approach)
1,John Smith,42,New York,1985-03-12
2,Sarah Johnson,35,Chicago,1990-07-28
3,Michael Lee,29,San Francisco,1996-11-05

This works for three customers. It falls apart at three million. Flat files have no built-in way to:

  • Update one field without rewriting the whole file
  • Prevent bad data (duplicate IDs, malformed emails)
  • Search efficiently ("find everyone in Chicago" means scanning every line)
  • Handle two processes writing at once without corruption
  • Relate one file's data to another's

A DBMS solves every one of these. Here's what you gain by moving from files to a real database:

CapabilityWhat it gives you
Data integrityRules that keep data accurate and consistent (types, uniqueness, required fields)
Concurrent accessMany users read and write safely at the same time
Efficient queryingIndexes and query planners find records fast, without full scans
SecurityFine-grained access control over who can see or change what
Backup & recoveryPoint-in-time restore after mistakes or hardware failure
ScalabilityGrows to handle more data and traffic than a single file ever could

⚠️ Files still have their place

Databases aren't for everything. Large binary blobs β€” images, videos, PDFs β€” usually live in object storage (like Amazon S3), with only a reference (a URL or key) stored in the database. Use the right tool: databases for structured, queryable data; object storage for big files.

Core Database Concepts

These terms come up in every backend job, tutorial, and code review. Learn them once and they pay off everywhere.

Schema β€” the blueprint

A schema defines how data is organized: which tables/collections exist, what fields they hold, the data types of those fields, and the constraints and relationships between them. It's the architect's plan drawn before the building goes up. Relational databases enforce their schema strictly; many NoSQL databases keep it flexible (more on that later).

Normalization β€” no duplication

Normalization is the practice of organizing data so each fact is stored in exactly one place. Instead of repeating a publisher's full address on every book record, you keep publishers in their own table and have each book reference it by ID. This reduces redundancy and prevents update anomalies. We dedicate the next lesson to it.

Indexes β€” the shortcut

An index is an extra data structure the DBMS maintains to find rows fast β€” exactly like the index at the back of a book. Without an index on last_name, finding "Smith" means checking every row (a full table scan). With one, the database jumps straight to the answer.

-- Create an index so lookups by email are fast
CREATE INDEX idx_users_email ON users (email);

-- Now this query can use the index instead of scanning the whole table
SELECT * FROM users WHERE email = 'jane@example.com';

⚠️ Indexes are a trade-off

They speed up reads but slow down writes (every insert/update must also update the index) and consume extra storage. Index the columns you filter and join on frequently β€” not every column.

ACID and Transactions

A transaction is a group of operations treated as one indivisible unit of work: either all of them succeed, or none of them do. The classic example is a bank transfer β€” deduct from one account, add to another. You never want the first step to happen without the second.

BEGIN;                                                    -- start the transaction

UPDATE accounts SET balance = balance - 100 WHERE id = 123;  -- deduct $100
UPDATE accounts SET balance = balance + 100 WHERE id = 456;  -- add $100

COMMIT;   -- make both changes permanent together
-- If anything failed above, we would ROLLBACK instead and undo everything.

Reliable transactions are guaranteed by four properties known by the acronym ACID:

graph TD A[ACID] --> B["Atomicity β€” all or nothing"] A --> C["Consistency β€” only valid states"] A --> D["Isolation β€” transactions don't interfere"] A --> E["Durability β€” committed data survives crashes"]
PropertyMeaningBank-transfer view
AtomicityEvery step happens, or none doesBoth updates commit, or neither does
ConsistencyOnly moves the DB between valid statesTotal money across accounts stays the same
IsolationConcurrent transactions don't corrupt each otherAnother transfer can't read a half-finished balance
DurabilityCommitted data persists through failuresA power cut right after commit doesn't lose the transfer

Traditional relational databases are strongly ACID-compliant, which is why they dominate finance, healthcare, and any domain where a lost or duplicated record is unacceptable. Many NoSQL systems relax some of these guarantees in exchange for scale and speed β€” a trade-off we'll unpack in the NoSQL lesson.

The Major Database Types

Databases fall into two broad camps β€” relational (SQL) and non-relational (NoSQL) β€” and NoSQL itself splits into four sub-families, each optimized for a different shape of data.

graph TD DB[Databases] --> REL[Relational / SQL] DB --> NOSQL[NoSQL] REL --> R1["PostgreSQL Β· MySQL Β· SQLite"] NOSQL --> DOC[Document Stores] NOSQL --> KV[Key-Value Stores] NOSQL --> COL[Column-Family Stores] NOSQL --> GR[Graph Databases] DOC --> D1["MongoDB Β· CouchDB"] KV --> K1["Redis Β· DynamoDB"] COL --> C1["Cassandra Β· HBase"] GR --> G1["Neo4j Β· Neptune"]

Relational databases (SQL)

Data lives in tables of rows and columns with a fixed schema, and tables link to each other through keys. You query them with SQL (Structured Query Language). They shine when data is well-structured, relationships matter, and you need ACID guarantees.

  • PostgreSQL β€” powerful, standards-compliant open-source database; the modern default choice
  • MySQL / MariaDB β€” hugely popular for web apps
  • SQLite β€” a whole database in a single file; perfect for mobile and small apps
  • Oracle / SQL Server β€” enterprise-grade commercial systems

Document stores

Data is stored as flexible, JSON-like documents. Each document can have its own shape, and the structure can evolve without a migration. Great for content, user profiles, and product catalogs.

{
  "_id": "5f8d0c0b1c9d440000a7df7b",
  "username": "johndoe",
  "email": "john@example.com",
  "profile": {
    "firstName": "John",
    "lastName": "Doe",
    "interests": ["hiking", "photography", "cooking"]
  },
  "lastLogin": "2026-03-15T14:30:00Z"
}

Examples: MongoDB, CouchDB, Firebase Firestore.

Key-value stores

The simplest model: a giant dictionary of unique keys mapping to values. Blazing fast for lookups by key, with limited querying. Ideal for caching, sessions, and leaderboards.

# Redis
SET session:a1b2c3 '{"userId":1000,"expires":"2026-03-16T14:30:00Z"}'
GET session:a1b2c3
INCR pageviews:homepage        # atomic counter
EXPIRE session:a1b2c3 3600     # auto-delete after 1 hour

Examples: Redis, Amazon DynamoDB, Riak.

Column-family stores

Store data by column family across many machines, built for write-heavy workloads at enormous scale. Rows can hold different columns. Ideal for time-series and IoT data.

-- Cassandra (CQL looks like SQL but the engine is very different)
CREATE TABLE sensor_readings (
  sensor_id  uuid,
  reading_at timestamp,
  temperature float,
  PRIMARY KEY (sensor_id, reading_at)
);

Examples: Apache Cassandra, HBase, ScyllaDB.

Graph databases

Model data as nodes (entities) and edges (relationships). Traversing connections β€” "friends of friends", "people you may know" β€” is natural and fast, where the same query in SQL would need many expensive joins.

// Neo4j Cypher β€” create a friendship
CREATE (john:Person {name: 'John'})
CREATE (mary:Person {name: 'Mary'})
CREATE (john)-[:FRIENDS_WITH {since: '2026-01-15'}]->(mary);

Examples: Neo4j, Amazon Neptune, ArangoDB.

βœ… "NewSQL" β€” the best of both?

A newer generation (Google Spanner, CockroachDB, Amazon Aurora) combines the SQL interface and ACID guarantees of relational databases with the horizontal scalability of NoSQL. Handy for global apps that need both consistency and massive scale.

Choosing the Right Database

There's no single "best" database β€” only the best fit for your data shape, query patterns, and scale. Walk through these questions:

flowchart TD A[What does your data look like?] --> B{Structured with clear relationships?} B -->|Yes| C[Relational: PostgreSQL / MySQL] B -->|Flexible / evolving| D[Document: MongoDB] B -->|Simple key lookups| E[Key-Value: Redis] B -->|Highly connected| F[Graph: Neo4j] B -->|Huge write volume, time-series| G[Column-Family: Cassandra] C --> H{Need global scale + ACID?} H -->|Yes| I[NewSQL: CockroachDB / Spanner] H -->|No| C
If you need…Reach for…
Complex queries, joins, strict integrityRelational (PostgreSQL, MySQL)
Flexible, nested, evolving recordsDocument (MongoDB)
Fastest possible lookups by key; cachingKey-Value (Redis)
Relationship traversal (social, recommendations)Graph (Neo4j)
Massive write throughput, time-series/IoTColumn-Family (Cassandra)

πŸ’‘ Real systems mix databases

Big applications rarely pick just one. A typical e-commerce platform uses a relational database for orders and inventory (integrity matters), Redis for shopping carts and sessions (speed matters), and a document store for the product catalog (flexibility matters). This is called polyglot persistence.

Hands-on Exercise

πŸ‹οΈ Model a Library Management System

Objective: Practice thinking in entities, relationships, and database choice β€” before touching any SQL.

Instructions:

  1. List the entities (things you store data about) for a library: at minimum books, members, and loans.
  2. For each entity, list 3–5 fields and mark which one is the unique identifier.
  3. Describe the relationships between them (e.g. one member can have many loans).
  4. Name one place an ACID transaction is essential (hint: think about two members trying to borrow the last copy at once).
  5. Decide: relational or NoSQL? Write one sentence justifying your choice.
πŸ’‘ Hint

A loan connects one book copy to one member for a period of time β€” that's a classic relationship best captured by a foreign key. When two members race for the last copy, you need isolation so both can't succeed.

βœ… Example answer

Entities & keys: books(book_id*, title, isbn, total_copies), members(member_id*, name, email, joined_on), loans(loan_id*, book_id→, member_id→, borrowed_on, due_on, returned_on).

Relationships: one member β†’ many loans; one book β†’ many loans over time. loans links books and members.

ACID transaction: checking out the last copy must, in one atomic + isolated step, verify a copy is available and create the loan β€” otherwise two members could both "get" it.

Choice: Relational β€” the data is highly structured with clear relationships and integrity (no loan without a real member/book) is essential.

Best Practices

βœ… Do

  • Start relational (PostgreSQL) unless you have a concrete reason not to β€” it's flexible and battle-tested.
  • Choose the database from the data's shape and access patterns, not from hype.
  • Wrap multi-step changes that must succeed together in a transaction.
  • Index the columns you filter and join on β€” then measure.
  • Keep large binary files in object storage; store only references in the database.

❌ Don't

  • Don't pick NoSQL just because it's trendy β€” "schemaless" still needs careful design.
  • Don't over-index; every extra index taxes writes and storage.
  • Don't rely on flat files for concurrent, growing, or relational data.
  • Don't assume one database must serve every need β€” polyglot persistence is normal.

Summary & Quiz

πŸŽ‰ Key Takeaways

  • A database stores structured data; a DBMS manages it, giving you integrity, concurrency, speed, security, and recovery that files can't.
  • Schema, normalization, and indexes are the everyday vocabulary of data modeling.
  • Transactions guarantee reliability through the four ACID properties.
  • Databases split into relational and four NoSQL families β€” document, key-value, column-family, graph.
  • Choose by data shape, query patterns, and scale β€” and remember real systems often mix several.

🎯 Quick Quiz

Question 1: What does the "A" in ACID guarantee?

Question 2: You need the fastest possible lookups for user session data and don't need complex queries. Which database type fits best?

Question 3: Why do most applications prefer a DBMS over storing data in flat files?

πŸ“š Further Reading

πŸš€ What's Next?

Now that you can tell the database families apart, we'll zoom into the most common one. Next lesson: Relational Database Design β€” modeling entities, keys, relationships, and normalization the right way.

πŸŽ‰ Nice work!

You now have the map of the data layer. Let's start drawing the tables.