Types of Databases
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Understanding Data Storage Options and Database Types
Introduction: Why Database Selection Matters
In the world of software development and data engineering, the database is the foundation upon which almost every application is built. Whether you are creating a simple personal project or managing a global enterprise system, the way you store, organize, and retrieve data determines the performance, scalability, and maintainability of your entire project. Choosing the wrong type of database at the start of a project can lead to significant technical debt, requiring expensive and time-consuming migrations later on.
Data storage is not a one-size-fits-all problem. Some applications require strict consistency, where every transaction must be perfectly recorded and verified, while others prioritize speed and the ability to handle massive volumes of unstructured data. Understanding the nuances between relational, document, key-value, and graph databases is essential for any professional working with technology. This lesson will guide you through the primary categories of databases, explain their architectural differences, and provide the practical knowledge necessary to make informed decisions for your own technical projects.
Not read yet
1. Relational Databases (RDBMS)
Relational Database Management Systems (RDBMS) have been the industry standard for decades. They are built on the relational model, which organizes data into tables consisting of rows and columns. This structure relies on a schema—a predefined blueprint that dictates exactly what kind of data can be stored, ensuring that the database remains organized and predictable.
Core Characteristics
The defining feature of an RDBMS is the use of Structured Query Language (SQL). SQL allows developers to perform complex operations, such as joining data from multiple tables, filtering records based on specific criteria, and ensuring that transactions follow the ACID properties (Atomicity, Consistency, Isolation, Durability). These properties guarantee that even in the event of a power failure or system crash, your data remains reliable and accurate.
Practical Example: An E-commerce User System
In an e-commerce application, you need to store user profiles and their associated orders. You would typically have two tables: Users and Orders. The Orders table would contain a foreign key that references the id from the Users table, creating a relational link.
-- Creating a table for users
CREATE TABLE Users (
id INT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100)
);
-- Creating a table for orders linked to users
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
user_id INT,
amount DECIMAL(10, 2),
FOREIGN KEY (user_id) REFERENCES Users(id)
);
When to Use RDBMS
- Structured Data: When your data has a clear, consistent structure that does not change frequently.
- Complex Transactions: When you need to ensure that multiple operations either all succeed or all fail (e.g., banking transfers).
- Data Integrity: When you need to enforce strict rules (constraints) on data quality.
Callout: The ACID Principles ACID is the gold standard for relational databases. Atomicity ensures a transaction is all-or-nothing; Consistency ensures the database follows rules; Isolation ensures transactions do not interfere with each other; and Durability ensures that once a transaction is committed, it stays that way permanently.
Not read yet
2. Document Databases (NoSQL)
Document databases represent a significant shift from the rigid, table-based structure of relational databases. Instead of rows and columns, they store data in documents—typically formatted as JSON (JavaScript Object Notation) or BSON (Binary JSON). This approach is highly flexible because each document can have a different structure, making it ideal for rapid development and evolving data requirements.
Why Flexibility Matters
In a document database, you do not need to define a schema before inserting data. If you decide to add a new field to your user profiles—such as "preferred_language"—you can simply start adding that field to new documents without altering existing ones. This "schema-on-read" approach is a major advantage for startups or projects where requirements change frequently.
Practical Example: Storing User Profiles
In a document-oriented database like MongoDB, a user profile might look like this:
{
"_id": "user123",
"username": "jdoe",
"email": "jdoe@example.com",
"preferences": {
"theme": "dark",
"notifications": true
},
"tags": ["active", "premium"]
}
When to Use Document Databases
- Rapid Prototyping: When you are iterating quickly and do not want to manage complex migrations.
- Content Management: When storing varied content types like articles, blogs, or product catalogs where items might have different attributes.
- Hierarchical Data: When your data naturally fits into a nested or tree-like structure.
Note: While document databases offer great flexibility, they often sacrifice some of the strict consistency guarantees found in RDBMS. Always evaluate if your application can tolerate "eventual consistency."
Not read yet
3. Key-Value Stores
Key-value stores are the simplest form of NoSQL databases. They function much like a dictionary or a hash map in programming. You provide a unique key, and the database retrieves the associated value. Because they do not need to parse complex data structures, they are incredibly fast and are often used as caching layers to improve the performance of other databases.
Performance and Scale
Key-value stores are designed for high-performance retrieval. They are frequently used to store session data, user preferences, or real-time gaming state. By keeping this data in memory (as seen in tools like Redis), you can achieve microsecond latency, which is impossible for disk-based relational databases.
Practical Example: Caching Session Data
Imagine you need to store a user's login session. Using a key-value store, you might store the session token as the key and the user's ID as the value.
# Pseudo-code example of setting a key-value pair
db.set("session_token_abc123", "user_user_99")
# Retrieving the value
user_id = db.get("session_token_abc123")
When to Use Key-Value Stores
- Caching: Storing frequently accessed data to reduce the load on primary databases.
- Session Management: Storing login sessions in web applications.
- Real-time Leaderboards: Storing scores that need to be updated and read extremely quickly.
Not read yet
4. Graph Databases
Graph databases are designed to store and navigate relationships. In a relational database, finding connections between many entities requires complex, slow "JOIN" operations. In a graph database, the relationships are stored as first-class citizens alongside the data itself.
The Structure of a Graph
Graph databases consist of "nodes" (entities) and "edges" (the relationships between them). For example, in a social network, a user is a node, and the "follows" action is an edge. This allows you to traverse connections with incredible efficiency, such as finding "friends of friends" or suggesting content based on shared interests.
Practical Example: Social Network Connections
If you were building a recommendation engine, a graph database could quickly identify common connections:
- Nodes: User A, User B, User C.
- Edges: User A "follows" User B; User B "follows" User C.
- Query: "Find all users that User A might know" becomes a simple path-finding operation.
When to Use Graph Databases
- Social Networks: Mapping complex social interactions.
- Recommendation Engines: Identifying patterns in user behavior and product connections.
- Fraud Detection: Spotting suspicious patterns in financial transactions by looking at the network of interactions.
Not read yet
Comparison Table: Database Types at a Glance
| Database Type | Data Structure | Best For | Typical Consistency |
|---|---|---|---|
| Relational | Tables/Rows | Financial, structured data | Strong (ACID) |
| Document | JSON/BSON | Content, flexible schemas | Eventual/Tunable |
| Key-Value | Key-Value pairs | Caching, session state | Eventual |
| Graph | Nodes/Edges | Social networks, fraud detection | Tunable |
Best Practices for Choosing a Database
Selecting the right database is not just about the technical features; it is about aligning the storage technology with the business requirements and the team's expertise.
1. Assess Your Data Access Patterns
Ask yourself: How will the data be read? Do you need to run complex analytical queries, or is the application mostly performing simple lookups? If you need to perform complex analytical reporting, a relational database is usually the superior choice. If you are building a high-traffic web application where speed is the primary concern, a key-value store or a document database might be more appropriate.
2. Consider the Growth Trajectory
Think about how your data will scale. Relational databases can scale vertically (adding more power to a single server), but scaling horizontally (adding more servers) is notoriously difficult. Many NoSQL databases are built from the ground up for horizontal scaling, making them better suited for massive, unpredictable growth.
3. Evaluate Team Expertise
There is a "cost" to adopting a new technology. If your entire team is proficient in SQL and PostgreSQL, switching to a graph database might introduce a steep learning curve that slows down development. Always weigh the benefits of a "perfect" database against the reality of your team's current skill set.
Tip: Start with what you know. If your data requirements are modest, a standard relational database like PostgreSQL can handle an astonishing amount of complexity and scale before you ever need to consider more specialized solutions.
Not read yet
Common Mistakes and How to Avoid Them
Even experienced engineers fall into traps when choosing and implementing database solutions. Avoiding these mistakes early in the design phase can save you hundreds of hours of debugging and refactoring.
Mistake 1: The "One Size Fits All" Approach
Many developers try to force every single piece of data into one database. For instance, they might store logs, user sessions, and core financial data all in the same relational database. This often leads to performance bottlenecks where a high-volume process (like logging) slows down a critical business process (like processing payments).
- Solution: Practice polyglot persistence. Use the right tool for the right job. Use a relational database for core transactional data and a document or key-value store for logs and transient data.
Mistake 2: Ignoring Schema Design
In relational databases, poor schema design—such as improper normalization or missing indexes—is the number one cause of performance degradation. Developers often forget to add indexes to columns that are frequently queried, leading to full table scans that bring systems to a halt as the data grows.
- Solution: Regularly review your query execution plans. If a query is slow, check if an index could speed it up. Normalize your data to reduce redundancy, but be prepared to denormalize if read performance becomes the primary bottleneck.
Mistake 3: Over-complicating the Architecture
It is tempting to adopt the latest "distributed, sharded, multi-model" database because it looks good on a resume. However, these systems are notoriously complex to maintain, monitor, and back up.
- Solution: Follow the principle of simplicity. Only introduce complexity if you have a specific, proven problem that a simpler system cannot solve. A well-tuned relational database is often faster than a poorly tuned, overly complex distributed system.
Not read yet
Step-by-Step Guide: Evaluating Your Needs
To help you decide which database to choose, follow this structured evaluation process:
Step 1: Define Your Data Structure
- Is the data highly structured? (Use RDBMS)
- Is the data semi-structured or changing often? (Use Document Store)
- Is the data entirely about relationships? (Use Graph)
Step 2: Define Your Performance Requirements
- Do you need sub-millisecond responses? (Use Key-Value Cache)
- Do you need complex JOINs and reports? (Use RDBMS)
- Do you need to handle massive, concurrent writes? (Use NoSQL)
Step 3: Define Consistency Needs
- Does every single record update need to be immediately visible to all users? (Use RDBMS)
- Can the application tolerate a few milliseconds of lag in data updates? (Use NoSQL with eventual consistency)
Step 4: Prototype and Benchmark
Do not just read about the database; build a small proof of concept. Load it with a realistic amount of dummy data and simulate the types of queries you expect to run. If your application needs to handle 1,000 requests per second, make sure your prototype can handle at least 2,000 to account for overhead.
Not read yet
Industry Recommendations and Trends
As technology evolves, the lines between these categories are blurring. Many modern relational databases now offer JSONB support, allowing them to function like document databases. Similarly, many NoSQL databases have added SQL-like query languages.
Multi-Model Databases
We are seeing a rise in "multi-model" databases that support multiple data structures within a single engine. This allows developers to store relational data, documents, and even graph data in one system. While this reduces the operational burden of managing multiple systems, it can sometimes lead to a "Jack of all trades, master of none" scenario. Always ensure that the multi-model database excels at your most critical use case.
Serverless Databases
Another trend is the move toward serverless databases. These are managed services where you do not need to worry about provisioning servers, patching software, or managing backups. You simply connect your application to an API endpoint and pay for the storage and throughput you use. For many small-to-medium projects, this is the most efficient way to get started.
Callout: Managed vs. Self-Hosted Managing your own database requires significant expertise in backups, security patching, and high-availability configuration. For most organizations, using a managed database service (where the cloud provider handles the operations) is the recommended path, allowing your team to focus on building features rather than maintaining infrastructure.
Not read yet
Quick Reference: When to Choose What
- PostgreSQL/MySQL: Use these when you need rock-solid reliability, ACID compliance, and standard SQL support. They are the best "default" choice for most applications.
- MongoDB: Use this when you have highly dynamic data structures and need to scale horizontally across multiple servers.
- Redis: Use this for caching, session storage, and any scenario where speed is the absolute priority.
- Neo4j: Use this if your application’s primary value comes from understanding connections between data points (e.g., recommendation engines).
- Cassandra: Use this if you have massive amounts of write-heavy data that needs to be distributed across many global data centers.
FAQ: Common Questions
Q: Can I use more than one database in a single project? A: Yes, this is known as polyglot persistence. It is very common to use a relational database for your primary user and transaction data while using a key-value store like Redis for caching and a document store for application logs.
Q: Are NoSQL databases always faster than SQL databases? A: Not necessarily. SQL databases are highly optimized for many types of queries. A well-indexed SQL database will often outperform a poorly designed NoSQL implementation. Performance depends more on your schema design and indexing strategy than the database category itself.
Q: Is "Schema-less" actually schema-less? A: No. Even in a document database, your application code implicitly expects certain fields to exist. You are simply moving the responsibility of schema enforcement from the database layer to the application layer.
Q: How do I handle data migration?
A: Migrations are easier in NoSQL because you can change the structure on the fly. In SQL, you must run ALTER TABLE commands, which can be dangerous on large datasets. Always perform migrations in a staging environment first and use automated tools to track your schema changes.
Not read yet
Key Takeaways
- Understand Your Data: Before choosing a database, categorize your data. Is it structured, hierarchical, or relationship-heavy? The nature of your data dictates the architecture you need.
- ACID vs. BASE: Decide if your application requires strict consistency (ACID, usually RDBMS) or if it can handle eventual consistency (BASE, usually NoSQL). This is a fundamental trade-off.
- Prioritize Simplicity: Avoid the temptation to build overly complex database architectures. Start with a proven, simple solution and only add specialized databases when a clear, unsolvable performance bottleneck arises.
- Index Your Data: Regardless of the database type, indexes are the most important tool for read performance. Always identify your most frequent query patterns and ensure your database is configured to handle them efficiently.
- Leverage Managed Services: Unless you have a specific requirement to host your own data for compliance or cost reasons, use managed database services to reduce the operational burden of backups, patching, and scaling.
- Measure, Don't Guess: Performance tuning should be based on data. Use query execution plans and monitoring tools to identify exactly where your database is struggling before making significant architectural changes.
- Plan for Change: Your data needs will change as your application evolves. Choose a database that offers enough flexibility to accommodate growth and shifting requirements without forcing a complete system rewrite.
By mastering these core concepts, you move from being a developer who simply "uses" databases to an engineer who "designs" data systems. This transition is essential for building software that is reliable, performant, and capable of supporting the long-term goals of your projects. Remember that the database is the heart of your application; treat it with the care, planning, and architectural rigor it deserves.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Understanding Structured Data
- Understanding Structured Data Quiz5q
- Features of Structured Data
- Features of Structured Data Quiz5q
- Semi-Structured Data Concepts
- Semi-Structured Data Concepts Quiz5q
- Features of Semi-Structured Data
- Features of Semi-Structured Data Quiz5q
- Understanding Unstructured Data
- Understanding Unstructured Data Quiz5q
- Features of Unstructured Data
- Features of Unstructured Data Quiz5q
- Transactional Workloads Overview
- Transactional Workloads Overview Quiz5q
- Features of Transactional Workloads
- Features of Transactional Workloads Quiz5q
- OLTP Systems
- OLTP Systems Quiz5q
- Analytical Workloads Overview
- Analytical Workloads Overview Quiz5q
- Features of Analytical Workloads
- Features of Analytical Workloads Quiz5q
- OLAP Systems
- OLAP Systems Quiz5q
- SQL Statement Types
- SQL Statement Types Quiz5q
- SELECT Statement Basics
- SELECT Statement Basics Quiz5q
- INSERT UPDATE DELETE Statements
- INSERT UPDATE DELETE Statements Quiz5q
- Common Database Objects
- Common Database Objects Quiz5q
- Views Stored Procedures and Functions
- Views Stored Procedures and Functions Quiz5q
- JOIN Operations
- JOIN Operations Quiz5q
- Azure SQL Family Overview
- Azure SQL Family Overview Quiz5q
- Azure SQL Database
- Azure SQL Database Quiz5q
- Azure SQL Managed Instance
- Azure SQL Managed Instance Quiz5q
- SQL Server on Azure VMs
- SQL Server on Azure VMs Quiz5q
- Azure Database for MySQL
- Azure Database for MySQL Quiz5q
- Azure Database for PostgreSQL
- Azure Database for PostgreSQL Quiz5q
- Azure Database for MariaDB
- Azure Database for MariaDB Quiz5q
- Azure Cosmos DB Overview
- Azure Cosmos DB Overview Quiz5q
- Cosmos DB Use Cases
- Cosmos DB Use Cases Quiz5q
- Cosmos DB APIs Overview
- Cosmos DB APIs Overview Quiz5q
- Cosmos DB for NoSQL
- Cosmos DB for NoSQL Quiz5q
- Cosmos DB for MongoDB
- Cosmos DB for MongoDB Quiz5q
- Cosmos DB for Apache Cassandra
- Cosmos DB for Apache Cassandra Quiz5q
- Cosmos DB for Apache Gremlin
- Cosmos DB for Apache Gremlin Quiz5q
- Cosmos DB for Table
- Cosmos DB for Table Quiz5q
- Global Distribution in Cosmos DB
- Global Distribution in Cosmos DB Quiz5q
- Data Ingestion Concepts
- Data Ingestion Concepts Quiz5q
- Data Processing Considerations
- Data Processing Considerations Quiz5q
- Analytical Data Stores
- Analytical Data Stores Quiz5q
- Data Warehouses and Data Lakes
- Data Warehouses and Data Lakes Quiz5q
- Azure Databricks Overview
- Azure Databricks Overview Quiz5q
- Microsoft Fabric Overview
- Microsoft Fabric Overview Quiz5q
- Azure Synapse Analytics
- Azure Synapse Analytics Quiz5q
- Azure Data Factory
- Azure Data Factory Quiz5q
- Power BI Overview
- Power BI Overview Quiz5q
- Power BI Capabilities
- Power BI Capabilities Quiz5q
- Power BI Data Models
- Power BI Data Models Quiz5q
- Data Model Features
- Data Model Features Quiz5q
- Power BI Visualizations
- Power BI Visualizations Quiz5q
- Choosing Appropriate Visualizations
- Choosing Appropriate Visualizations Quiz5q
- Reports and Dashboards
- Reports and Dashboards Quiz5q
- Power BI Desktop vs Service
- Power BI Desktop vs Service Quiz5q
- Data Refresh and Gateways
- Data Refresh and Gateways Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-900 exam-style practice questions.
Practice for DP-900