KAHIBARO
Discord Login Register

9.1 Introduction to Databases

Why Backends Need Databases

When you build a backend, you almost always need a place to store data so you can use it later. A database is that place.

Some typical things a backend stores:

You could store data in files like data.json, but this quickly becomes a problem:

Databases solve these problems. They are specialized systems designed to:

Key idea: A database is a system that stores data in a structured way, lets many users and applications access it at the same time, and provides tools to query, update, and protect that data.

In backend development, you usually do not build your own database from scratch. You use an existing database engine such as PostgreSQL, MySQL, or MongoDB.

Database vs File Storage

Many beginners wonder: “Why not just use files?”

Simple file storage example

Imagine a simple blog application that stores posts in a JSON file:

json
[
  {
    "id": 1,
    "title": "Hello world",
    "content": "My first post",
    "author": "alice",
    "created_at": "2026-08-27T12:00:00Z"
  },
  {
    "id": 2,
    "title": "Second post",
    "content": "More content",
    "author": "bob",
    "created_at": "2026-08-27T13:00:00Z"
  }
]

If you want to find all posts by alice, your backend would:

  1. Read the whole file into memory.
  2. Loop over all items.
  3. Filter items where author == "alice".

This is fine for 10 posts, maybe 1000 posts, but not for millions.

File storage problems

With pure file storage, you must handle everything yourself:

How databases improve this

Databases provide:

So you, as a backend developer, can focus on business logic, not on reinventing safe storage.

Types of Data and Databases

Different applications work with different types of data, and different databases are optimized for different styles.

Structured vs semi-structured vs unstructured data

TypeExampleTypical storage
StructuredUsers with name, email, created_atRelational databases (PostgreSQL, MySQL)
Semi-structuredJSON API responses, settings documentsDocument databases (MongoDB), JSON columns
UnstructuredImages, videos, PDFsObject storage (S3), file storage

As a backend developer you will often:

This chapter focuses on the core database concepts, not on choosing a database yet.

Core Concepts: Database, Table, Row, Column

At a very high level, a typical relational database system has:

You will study tables, rows, and columns more deeply in later chapters. For now, you only need an intuitive picture.

Simple example

Imagine a database for a task management app. It might have tables like:

The users table could look like this conceptually:

idemailnamecreated_at
1alice@example.comAlice2026-08-27 10:00:00 UTC
2bob@example.comBob2026-08-27 10:05:00 UTC

In code, this concept maps to a Python dictionary or JSON, but in a database it is a row in a table.

Visual analogy

Think of:

But databases are much more powerful than spreadsheets:

How Backends Talk to Databases

Your backend application is usually a separate program that connects to a database server over the network.

Connection basics

To connect, the backend needs:

In Python, a very simplified PostgreSQL connection might look like:

python
import psycopg2
conn = psycopg2.connect(
    host="localhost",
    port=5432,
    dbname="task_manager",
    user="app_user",
    password="secret-password"
)

You will normally hide these values in environment variables, not hard-code them, but this shows the idea.

Once connected, the backend can:

Query example

Imagine we want all tasks for user with ID 1:

python
cursor = conn.cursor()
cursor.execute("SELECT id, title, completed FROM tasks WHERE user_id = %s", (1,))
rows = cursor.fetchall()

The idea is:

You will learn the SQL language and ORMs later. At this stage just remember: the backend talks to the database using a protocol and a query language, most often SQL.

What Databases Do for Your Backend

Databases offer several important properties that directly affect how you design your backend.

Reliability and durability

If your server restarts, you do not want to lose all data.

Databases typically guarantee that once data is committed, it will survive crashes and restarts, as long as disk storage is intact.

For example:

Consistency and constraints

Databases can enforce rules about your data:

These rules are called constraints and help keep your data valid. You will study them in detail in a separate chapter.

Your backend can rely on the database to prevent certain invalid states, which simplifies your code.

Concurrency

Many clients access your backend at the same time. They might:

The database manages concurrency so that operations do not corrupt data. For example, it ensures that:

As a backend developer, you need to understand that:

Transactions

A transaction groups a set of operations into a single logical unit. Either all operations succeed, or none of them do.

Example:

You want either all three steps to succeed, or if any fails, you want none of them to be saved, so your data does not get into a broken state.

In Python pseudocode:

python
try:
    cursor.execute("BEGIN")
    cursor.execute("INSERT INTO orders (...) VALUES (...);")
    cursor.execute("UPDATE products SET stock = stock - 1 WHERE id = ...;")
    cursor.execute("INSERT INTO order_items (...) VALUES (...);")
    cursor.execute("COMMIT")
except Exception:
    cursor.execute("ROLLBACK")
    raise

You will learn more about transactions and ACID properties in later chapters, but the key point is that databases can group operations safely.

Important: Use transactions when you need multiple related changes to be applied together, so your data never ends up in a half-updated state.

Logical vs Physical View of Data

As a backend developer, you mostly work with the logical view of the data, not how bytes are stored on disk.

Logical view

Examples of questions you ask:

You think of data in terms of:

Physical view

The database internally deals with:

You rarely control these details directly, although you might tune them for performance later.

The separation is helpful:

Examples of Common Backend Data Models

To make the idea of a database concrete, here are some simple models you might build as a beginner backend developer.

User and task model

For a task management API, you might have:

users table

ColumnTypeNotes
idintegerUnique identifier
emailtextMust be unique
passwordtextHashed password
created_attimestampWhen the user registered

tasks table

ColumnTypeNotes
idintegerUnique identifier
user_idintegerWhich user owns the task
titletextTask title
completedbooleanTrue or false
created_attimestampWhen the task was created

Your backend would:

You will learn more about relationships like user_id in dedicated chapters.

Blog model

For a simple blog, you might design:

Your backend:

These models show how database tables map naturally to backend API endpoints.

How Databases Fit into a Backend System

It is useful to see where the database sits in the whole architecture.

A typical web backend has:

  1. Client
    Web browser, mobile app, or another service.
  2. Backend application
    Your code, for example a FastAPI app running on a server.
  3. Database server
    PostgreSQL, MySQL, or another database that stores persistent data.

Communication flow:

  1. Client sends a request to your backend, for example POST /tasks.
  2. Backend receives the request, validates input.
  3. Backend sends a query to the database to insert a new task row.
  4. Database stores the data and returns a result.
  5. Backend sends a response back to the client.

In diagram form:

StepActorAction
1ClientSends HTTP request
2BackendProcesses request
3Backend → DBExecutes query (insert / select)
4DB → BackendReturns rows / success status
5Backend → ClientSends HTTP response

The database is a separate component. It might run:

Choosing a Database as a Beginner

You will later study the differences between relational and NoSQL databases. For now, it is useful to know what beginners usually start with.

Most backend tutorials and real-world APIs use:

Common beginner choices:

PurposePopular choice
Main application dataPostgreSQL
Simple dev / experimentsSQLite
Caching / ephemeral dataRedis

For this course, you will usually see PostgreSQL as the main example database.

Practical advice: As a beginner backend developer, focus on learning one relational database (like PostgreSQL) and SQL well before exploring many other database types.

Summary

In this chapter you learned:

In the next chapters you will dive deeper into database types, structures, relationships, and how to design efficient and reliable schemas for your backend applications.

Views: 7

Comments

Please login to add a comment.

Don't have an account? Register now!