ποΈ 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).
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:
| Capability | What it gives you |
|---|---|
| Data integrity | Rules that keep data accurate and consistent (types, uniqueness, required fields) |
| Concurrent access | Many users read and write safely at the same time |
| Efficient querying | Indexes and query planners find records fast, without full scans |
| Security | Fine-grained access control over who can see or change what |
| Backup & recovery | Point-in-time restore after mistakes or hardware failure |
| Scalability | Grows 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:
| Property | Meaning | Bank-transfer view |
|---|---|---|
| Atomicity | Every step happens, or none does | Both updates commit, or neither does |
| Consistency | Only moves the DB between valid states | Total money across accounts stays the same |
| Isolation | Concurrent transactions don't corrupt each other | Another transfer can't read a half-finished balance |
| Durability | Committed data persists through failures | A 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.
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:
| If you need⦠| Reach for⦠|
|---|---|
| Complex queries, joins, strict integrity | Relational (PostgreSQL, MySQL) |
| Flexible, nested, evolving records | Document (MongoDB) |
| Fastest possible lookups by key; caching | Key-Value (Redis) |
| Relationship traversal (social, recommendations) | Graph (Neo4j) |
| Massive write throughput, time-series/IoT | Column-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:
- List the entities (things you store data about) for a library: at minimum books, members, and loans.
- For each entity, list 3β5 fields and mark which one is the unique identifier.
- Describe the relationships between them (e.g. one member can have many loans).
- Name one place an ACID transaction is essential (hint: think about two members trying to borrow the last copy at once).
- 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
- PostgreSQL β Official Tutorial
- MongoDB β NoSQL Explained
- Neo4j β Graph Database Fundamentals
- "Designing Data-Intensive Applications" by Martin Kleppmann (book)
π 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.