Skip to main content

Databases for Backend Engineers

Updated 62 min readMarkdown
Part of seriesFirst Principles of Backend Engineering
Databases for Backend Engineers

1. Databases and why we need them

A database persists application data across failures, crashes and intentional restarts, and in backend systems database operations are among the most frequent work you do.

What a database is

  • At its core, a database is any structure (program, system, technology or even a file) that lets you perform CRUD (create, read, update, delete) on data and keeps that data across sessions.
  • Persistence means data survives after the program that created it has stopped. A to-do app that reopens with your tasks exactly as you left them is relying on persistence; without it, you would start from nothing every time.
  • Everyday examples of a database:
    1. Notes in a notebook or text file
    2. The contact list on a phone
    3. A list or array of items inside a program
    4. Key-value entries in a browser's local storage (also session storage and cookies)
  • In backend engineering, "database" means a persistent, disk-based store that supports CRUD.

Primary vs secondary memory

Where data is stored decides speed, size and cost.

Primary memory (RAM) Secondary memory (HDD / SSD)
Speed Very fast Slow by comparison
Capacity Small (typically 8 to 128 GB on a consumer machine) Large (typically 512 GB to 2 TB)
Cost Expensive Relatively cheap
Persistence Lost on restart Survives restarts
Used by Caches such as Redis, in-memory caches Databases such as PostgreSQL, MongoDB
  • Databases accept slower access in exchange for far more space at lower cost, so traditional relational and non-relational databases are disk based.
  • Caching technologies keep hot data in RAM because reads and writes there are very fast.

2. DBMS (Database Management System)

A DBMS is software whose job is to store data and serve CRUD operations on it efficiently, securely and at scale.

Responsibilities

Responsibility Meaning
Data organization Lay data out so reads, updates and inserts stay efficient
Access Provide create, read, update and delete operations
Integrity Keep data accurate, valid and consistent. Example: a payment amount column of a numeric type rejects a string like "something" at the database level
Security Block unauthorized access using users and roles

A DBMS also handles scaling and load balancing, but storing data and providing CRUD are its two core duties.

Why not plain text files?

Early systems stored data in text files. The problems below are why DBMSs were created.

  • Parsing: every lookup needs application code that reads the file, splits lines and compares fields. This is slow (more so in JavaScript, Python or Ruby than in Rust) and easy to get wrong, and a mistake can corrupt data.
  • No structure: a text file accepts anything, so you cannot enforce rules such as "this field is numeric". Data fluidity means no consistency guarantee.
  • Unreliable and unsecured: anyone can edit the file, and an improper edit can corrupt it.
  • No concurrency control: two writers at once give an unpredictable result.

Concurrency example. An amount field holds 40. Two users read it at the same time. One adds 20 and saves 60; the other subtracts 20 and saves 20. Whoever saves last wins, and which one that is depends on CPU scheduling, so the final value could be 60 or 20 (the correct result would be 40). A DBMS has concurrency mechanisms to produce a consistent result.

A DBMS provides ACID properties (atomicity, consistency, isolation, durability) on data, which removes these disadvantages.

3. Types of databases and why PostgreSQL

Relational databases trade flexibility for robustness; non-relational databases do the opposite, and PostgreSQL covers most needs of both.

Relational Non-relational
Structure Tables of rows and columns; relationships through foreign keys Collections of entries (documents) of key-value pairs
Schema Predefined and strict; columns and types are decided up front None enforced; each document can have a different shape
Language SQL Database-specific query APIs
Integrity (ACID) Maintained by the database through the schema Rules must be set by the developer at the application level
Character Not flexible but robust Flexible but error-prone
Examples PostgreSQL, MySQL, SQLite, SQL Server MongoDB

Terminology mapping (MongoDB vs relational): a table is called a collection, and a row is called a document.

When to use which

  • Fixed, predefined structure: use a relational database. Example: a CRM stores contacts and sales opportunities, needs accurate and consistent data, and benefits from complex queries over relationships between customers.
  • Changing structure and many formats: a non-relational database fits. Example: a CMS stores articles that may contain images, code blocks or YouTube embeds, so the shape is not known in advance. It is also useful for fast prototyping without maintaining a schema.
  • Trade-off of non-relational: integrity is not enforced by the database, so validation moves into application code, which adds complexity and is easier to break because application code changes often.

Why PostgreSQL for most projects

  1. Open source and free, so companies can host and deploy it on their own servers.
  2. Sticks to the SQL standard, so queries behave the same as in MySQL or SQL Server and migrating to another database later takes only minor changes.
  3. Extensible: the documentation runs to roughly 1,400 pages and covers nearly every use case a typical SaaS meets, plus an extension system for customization.
  4. Reliable and scalable.
  5. Strong JSON support (a JSON / JSONB data type with good indexing and querying), so dynamic data does not require switching to a non-relational database.
  6. Good indexing and query mechanisms, and support for migrations through external tools.

Performance edges claimed for MySQL only matter once you serve millions of users and are tuning one specific bottleneck, so PostgreSQL is a safe first choice.

4. PostgreSQL data types

Pick the type by what the value means: exact money uses NUMERIC, free text uses TEXT, and timestamps that cross time zones use TIMESTAMPTZ.

Numeric

Type Size / range Use for Example values
SERIAL 4-byte auto-incrementing integer Auto-generated IDs; you omit it on insert 1, 2, 3
BIGSERIAL 8-byte auto-incrementing integer IDs for tables that may hold a very large number of rows (common choice in production) 1, 2, 3
SMALLINT 2 bytes, -32768 to 32767 Age, small counters 25, 1200
INTEGER 4 bytes, about ±2.1 billion Quantities, general counts 50000, -300
BIGINT 8 bytes, about ±9.2 quintillion View counts, millisecond timestamps 9876543210
DECIMAL / NUMERIC Exact; identical in PostgreSQL Money, prices, anything needing exact precision 99.99, 1500.50
REAL 4 bytes, about 6 digits, approximate Measurements such as temperature 36.6, 0.0025
DOUBLE PRECISION 8 bytes, about 15 digits, approximate Scientific values, coordinates 12.9715987
  • NUMERIC(10, 2): precision 10 means at most 10 digits in total; scale 2 means exactly 2 digits after the decimal point. So 12345678.90 fits and 123456789.00 does not.
  • Exact vs floating point: use NUMERIC when small discrepancies cause real damage (prices). Use REAL or DOUBLE PRECISION when tiny errors do not matter (an area like 567.8987). Floating point is faster to store and compute, which is why scientific work prefers it.

Text

Type Behavior Guidance
CHAR(n) Fixed length; shorter values are padded with spaces Only when every value has the same length (country codes 'IN', weekday codes)
VARCHAR(n) Variable length up to n; no padding; longer values raise an error Only when the database must enforce a maximum
TEXT Variable length, no declared limit Default choice for names, descriptions, comments

Prefer TEXT over VARCHAR(255):

  • PostgreSQL has no performance difference between them, and its documentation recommends TEXT.
  • 255 is a MySQL convention. In PostgreSQL it is a random number that misleads new readers into hunting for its meaning.
  • Raising a limit later needs a database migration touching live data, which is risky.
  • Enforce length in application code instead, so migrations stay simple. Backend engineers reach the database through drivers and application code, so this is natural.

Date and time

Type Stores Example
DATE Date only '2026-10-19'
TIME Time of day only (TIME WITH TIME ZONE also exists) '09:30:00'
TIMESTAMP Date and time, no time zone '2026-10-19 14:30:00'
TIMESTAMPTZ Date and time with zone awareness; stored in UTC, shown in the session time zone '2026-10-19 14:30:00+05:30'
INTERVAL A span of time '1 day', '2 hours 30 minutes'

Use TIMESTAMPTZ for created_at and updated_at columns.

Other types

Type Notes Example
BOOLEAN / BOOL TRUE or FALSE TRUE
UUID Native type, popular for primary keys. Generate with the built-in gen_random_uuid() (the uuid-ossp extension is optional and must be enabled with CREATE EXTENSION) '6e6a6c6f-6b6d-4a6e-866f-6c6d6e6f6a6c'
ENUM A custom type with a fixed set of allowed values, created with CREATE TYPE 'OPEN', 'CLOSED', 'IN_PROGRESS'
JSON Stored as plain text; keeps the input exactly '{"name": "John", "age": 30}'
JSONB Converted to PostgreSQL's internal binary format; faster to query and index. Usually the right choice; PostgreSQL-specific, not SQL standard '{"name": "John", "age": 30}'
ARRAY Ordered values of one type (all elements must share a type) '{1,2,3}' or ARRAY['a','b']
XML PostgreSQL has a native xml type '<name>John</name>'
POINT A point in 2D space '(1, 2)'
MACADDR A MAC address '00:11:22:33:44:55'
INET An IPv4 or IPv6 address '192.168.1.1'

Network, geometric and XML types are rarely used in typical backends; see the official documentation if you need them.

5. Schema design fundamentals

A good schema pushes validity checks into the database: strict types, enums, constraints and defaults, with consistent names.

Naming conventions

  • Table names are plural and snake_case: users, posts, comments, user_profiles. (Some teams prefer singular; the industry norm is plural. Follow your team.)
  • Column names are descriptive and snake_case: first_name, password_hash, created_at.
  • PostgreSQL folds unquoted identifiers to lowercase, so FullName and fullname are the same column. Keeping everything lowercase snake_case avoids double quotes everywhere in application code.

Enums as column types

An enum is a custom type with a predefined set of allowed values. Any other value is rejected by the database.

CREATE TYPE project_status AS ENUM ('active', 'completed', 'archived');

Two benefits:

  1. Integrity: the database validates the value, so an invalid string causes a database-level error even if application validation misses it.
  2. Documentation: anyone reading the migration sees every allowed value at a glance. With a plain TEXT column they would have to search all application code.

Give an enum column a sensible default, such as DEFAULT 'active'. Internally each value is stored compactly instead of as the full string.

Primary keys

  • A primary key uniquely identifies each row. It implies NOT NULL and UNIQUE, and PostgreSQL indexes it automatically.
  • Generate it with SERIAL / BIGSERIAL, or use UUID with a default of gen_random_uuid().
  • By convention the column is named id.
id UUID PRIMARY KEY DEFAULT gen_random_uuid()

Foreign keys

A foreign key is a column that references another table's primary key, written with REFERENCES. It rejects values that do not exist in the referenced table. See section 6 for relationships.

Constraints

Constraints protect a field from invalid data. Every violation is a database-level error.

Constraint Effect
NOT NULL The column cannot be NULL
UNIQUE No two rows share a value (example: email)
CHECK A custom condition must hold (example: priority INTEGER CHECK (priority BETWEEN 1 AND 5))
PRIMARY KEY Unique and not null; identifies the row
FOREIGN KEY Value must exist in the referenced column of another table
  • Columns are nullable by default. Add NOT NULL to most of them (over 70% of columns in a typical table). Automated scripts can have bugs, and without the constraint they quietly fill the table with nulls. Leave a column nullable only when absence is meaningful (a project description, a user's bio).

Default values

A default applies when an insert omits the column. It can be a constant or an expression.

created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
status project_status NOT NULL DEFAULT 'active',
priority INTEGER NOT NULL DEFAULT 1

Timestamps

Keep created_at (when the row first appeared) and updated_at (last change) on every table. Use TIMESTAMPTZ. updated_at also enables sorts like "recently changed first". Section 12 shows how to maintain it automatically.

Hashing credentials

Never store passwords, PINs or other secrets in plain text. The lecture stores a password_hash column and hashes in backend code. PostgreSQL can also hash with the pgcrypto extension:

CREATE EXTENSION IF NOT EXISTS pgcrypto;

INSERT INTO users (username, password)
VALUES ('john', crypt('john', gen_salt('bf')));

crypt() takes the plain value and a salt, and gen_salt('bf') generates a bcrypt salt.

6. Relationships and referential integrity

Relationships link rows through a foreign key that references a primary key; the three shapes differ in where the key sits and what constrains it.

Relationship Meaning How to implement
One-to-one A row in A relates to at most one row in B Foreign key in B that is UNIQUE, or the foreign key is B's primary key
One-to-many A row in A relates to many rows in B; each B row has one A Foreign key in the "many" table (B) referencing A's primary key
Many-to-many Many A rows relate to many B rows Junction table with a foreign key to each, and a composite primary key

One-to-one

Split data into a second table when it will grow or change on a different schedule. Example: user profile details (avatar, bio, phone, later social links) live in user_profiles, so the core users table is not touched by every new profile field.

-- Option A: separate id, unique foreign key
CREATE TABLE profiles (
  id SERIAL PRIMARY KEY,
  user_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  bio TEXT
);

-- Option B (used in the lecture): the foreign key is also the primary key
CREATE TABLE user_profiles (
  user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
  bio TEXT
);

Option B drops the extra id, because primary-key uniqueness already guarantees one profile per user.

One-to-many

One project has many tasks; each task belongs to one project. The foreign key is a plain column (not unique) on the "many" side.

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  title TEXT NOT NULL
);

Many-to-many

A test: look at it from both sides. A user can be on many projects, and a project can have many users, so the link needs its own table (a junction, linking, join or bridge table). The pair of foreign keys forms a composite primary key, which prevents the same pair appearing twice and is never null.

CREATE TABLE post_tags (
  post_id INT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
  tag_id INT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
  PRIMARY KEY (post_id, tag_id)
);

Data that describes the link itself (for example a member's role in a project) belongs in the junction table.

Referential integrity

  • A foreign key value must always refer to an existing row. Inserting a nonexistent value is rejected, even if it is a validly formatted UUID.
  • Deleting a referenced row that still has dependents is rejected unless a cascading action is set.

ON DELETE actions

Action Effect when the referenced row is deleted
RESTRICT Block the delete if dependent rows exist
NO ACTION Default. Rejects the delete if dependents exist, but the check can be deferred to the end of the transaction
CASCADE Delete dependent rows too
SET NULL Set the foreign key to NULL (errors if the column is NOT NULL)
SET DEFAULT Set the foreign key to its default value

The same options exist for ON UPDATE. Example choice: projects.owner_id ... ON DELETE RESTRICT means a user who owns projects cannot be deleted until those projects are handled.

7. Case study: project management platform schema

The lecture models five tables, three enums and four relationship patterns for a project management platform. The SQL below is reconstructed from the lecture's description.

Tables and relationships

Table Relationship Key design choice
users Parent of everything else email is UNIQUE; stores password_hash, never the password
user_profiles One-to-one with users user_id is both primary key and foreign key; avatar, bio, phone are nullable
projects Many projects per owner (users) owner_id ... ON DELETE RESTRICT; status enum defaults to active
tasks One-to-many from projects project_id ... ON DELETE CASCADE; assigned_to ... ON DELETE SET NULL; priority check 1 to 5
project_members Many-to-many between users and projects Composite primary key (project_id, user_id); role enum defaults to member

Every table has created_at and updated_at (TIMESTAMPTZ, default now()).

Up migration

-- enums
CREATE TYPE project_status AS ENUM ('active', 'completed', 'archived');
CREATE TYPE task_status    AS ENUM ('pending', 'in_progress', 'completed', 'cancelled');
CREATE TYPE member_role    AS ENUM ('owner', 'admin', 'member');

CREATE TABLE users (
  id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email         TEXT NOT NULL UNIQUE,
  full_name     TEXT NOT NULL,
  password_hash TEXT NOT NULL,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- one-to-one with users
CREATE TABLE user_profiles (
  user_id    UUID PRIMARY KEY REFERENCES users(id),
  avatar_url TEXT,
  bio        TEXT,
  phone      TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE projects (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name        TEXT NOT NULL,
  description TEXT,
  status      project_status NOT NULL DEFAULT 'active',
  owner_id    UUID NOT NULL REFERENCES users ON DELETE RESTRICT,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- one-to-many from projects
CREATE TABLE tasks (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  project_id  UUID NOT NULL REFERENCES projects ON DELETE CASCADE,
  title       TEXT NOT NULL,
  description TEXT,
  priority    INTEGER NOT NULL DEFAULT 1 CHECK (priority BETWEEN 1 AND 5),
  status      task_status NOT NULL DEFAULT 'pending',
  due_date    DATE,
  assigned_to UUID REFERENCES users ON DELETE SET NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- many-to-many linking table
CREATE TABLE project_members (
  project_id UUID NOT NULL REFERENCES projects ON DELETE CASCADE,
  user_id    UUID NOT NULL REFERENCES users ON DELETE CASCADE,
  role       member_role NOT NULL DEFAULT 'member',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (project_id, user_id)
);

Down migration

Undo everything in reverse order: tables that reference others first, types last.

DROP TABLE project_members;
DROP TABLE tasks;
DROP TABLE projects;
DROP TABLE user_profiles;
DROP TABLE users;
DROP TYPE member_role;
DROP TYPE task_status;
DROP TYPE project_status;

Why these choices

  • ON DELETE RESTRICT on owner_id: a user cannot be deleted while they own projects. CASCADE would delete the projects too; SET NULL would fail because the column is NOT NULL.
  • ON DELETE CASCADE on tasks.project_id: deleting a project removes its tasks. NOT NULL also means no orphan task can exist.
  • ON DELETE SET NULL on tasks.assigned_to: deleting a user keeps their tasks and just unassigns them.
  • Composite key on project_members: user 1 in project 2 is one fact that cannot repeat. Role is stored here because it only exists when a user is part of a project.
  • Foreign key constraint: you cannot assign a task to a UUID that is not in users.

8. Migrations

A migration is a versioned, committed change to the database (mostly schema, sometimes data), so every change is tracked and reversible instead of typed into a GUI.

Why not run SQL from a GUI?

In production you cannot just open a tool and execute queries: there is no record of what changed, who changed it or when, and no way to version or roll back the database state. Migrations give you both.

How they work

  • Each change is a numbered or timestamped SQL file in a folder such as db/migrations/, committed to Git alongside the code.
  • A file has an up section that applies the change (create table, create type, create index) and a down section that reverts exactly that change. Some modern approaches skip down migrations, but they are the standard way and enable rollback.
  • A migration tool (DBMate, Flyway, Liquibase, Alembic, Prisma Migrate, golang-migrate) runs pending files in order and records the current version in a table, so each runs only once. DBMate keeps this in schema_migrations.
  • Files are ordered by their names. Timestamps keep one consistent sequence.
  • To revert, run the down migration to return to the previous state.

DBMate workflow

  1. Put the connection string in .env: DATABASE_URL=postgres://...
  2. Create a migration: dbmate new create_users_table. It creates db/migrations/<timestamp>_create_users_table.sql.
  3. Fill in the file:
-- migrate:up
CREATE TABLE users ( ... );

-- migrate:down
DROP TABLE users;
  1. Apply: dbmate up. Roll back the latest migration: dbmate rollback.
  2. Inspect the result in a GUI client (the lecture uses TablePlus). The schema_migrations table shows the current version.

If the tool re-ran old files, PostgreSQL would error with "table already exists". Tracking the version is what lets it start from where it left off.

When to write a migration

New features with schema changes, performance fixes such as indexes, new constraints, keeping all environments in sync, and moving to a new server or engine.

Standard procedure

  1. Write the migration with a rollback.
  2. Back up production before applying.
  3. Test locally, then staging, then production.
  4. Verify; roll back if it fails.

Good practices

  • Keep files small and simple, with one naming convention and a consistent order.
  • Commit migration files to the repository.
  • Use separate migrations for different concerns (schema, seed data, indexes and triggers).

9. Seeding data

Seeding fills a development or test database with sample data so you can test APIs before real users exist; keep it in its own migration file.

  • Production data arrives through normal user flows (sign-up forms, project forms). In development you need test data instead.
  • Seed with a SQL script or program that inserts rows. Best practice is a separate migration, for example dbmate new seed_data, which sorts after the schema migration because its timestamp is later. Run it with dbmate up.
  • Never seed test data into production.

Technique: chained CTEs

A common table expression (CTE) names an intermediate result so a multi-step insert reads cleanly. Each step inserts rows and returns what the next step needs:

WITH inserted_users AS (
  INSERT INTO users (email, full_name, password_hash)
  VALUES
    ('alice@example.com', 'Alice Brown', 'hash1'),
    ('john@example.com',  'John Doe',    'hash2')
  RETURNING id, email
),
inserted_profiles AS (
  INSERT INTO user_profiles (user_id, avatar_url, bio, phone)
  SELECT
    id,
    'https://example.com/avatar.png',
    CASE email
      WHEN 'alice@example.com' THEN 'Designer who loves charts'
      WHEN 'john@example.com'  THEN 'Backend engineer'
      ELSE 'Team member'
    END,
    '+1-555-0100'
  FROM inserted_users
  RETURNING user_id
)
INSERT INTO projects (name, description, owner_id)
SELECT 'Website redesign', 'Seeded project', id
FROM inserted_users
WHERE email = 'alice@example.com';
  • RETURNING id, email hands the generated IDs to the next step, so you never hard-code UUIDs.
  • INSERT ... SELECT ... FROM inserted_users builds profile rows from the users just created.
  • CASE varies the sample data per row.

Projects, tasks and project members are seeded the same way. Afterwards, open the tables in your GUI client to confirm rows exist.

10. Querying data

SELECT retrieves rows; clauses are optional except SELECT itself, but must appear in a fixed order.

SELECT syntax

SELECT column1, column2        -- columns or expressions; * means all
FROM table_name alias          -- the table to read (an alias is a short name)
LEFT JOIN other_table o        -- INNER JOIN, LEFT JOIN, RIGHT JOIN
  ON alias.id = o.alias_id     -- join condition
WHERE condition                -- filters rows before grouping
GROUP BY column1               -- groups rows; used with COUNT, SUM, AVG
HAVING condition               -- filters groups after grouping
ORDER BY column1 ASC | DESC    -- ascending by default
LIMIT count                    -- max rows returned
OFFSET start;                  -- rows to skip (pagination)

Write the FROM and JOIN part first when composing, so you know where the data comes from before choosing what to select.

Joins

  • INNER JOIN returns a row only when both tables match. If a user has no profile row, that user disappears from the result.
  • LEFT JOIN keeps every row of the left table even without a match. Use it when the related row is optional (a user who never edited their profile).
  • Embedding a related row as JSON in one query saves the client a second API call:
SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
ORDER BY u.created_at DESC;

to_jsonb(up.*) is a PostgreSQL function that turns the joined profile row into a JSON object named profile.

Result order is not guaranteed

Without ORDER BY, rows come back in no defined order. Always sort list endpoints, usually by created_at DESC so the newest items come first.

Parameterized queries

A parameterized query sends the SQL text and the values separately. The text holds numbered placeholders ($1, $2), and values are supplied at execution time.

  • Values are always treated as data, never as SQL, so input like '; DELETE FROM users; -- is just a harmless string. This prevents SQL injection.
  • The unsafe alternative is building the query by concatenating strings. Never do that with user input.
  • In SQL itself:
PREPARE get_user (UUID) AS
SELECT * FROM users WHERE id = $1;

EXECUTE get_user('6e6a6c6f-6b6d-4a6e-866f-6c6d6e6f6a6c');
  • In application code, database drivers and ORMs accept the query text and an array of values as separate arguments, so you rarely write PREPARE yourself. GUI clients such as TablePlus also prompt for parameter values.
  • Parameters only replace values. Column names and sort directions cannot be parameters, so allow them from a whitelist (section 11).

11. Mapping APIs to SQL

Each REST endpoint becomes one parameterized query, and the backend's job is to read the request, build the query, pass values as parameters and return rows.

Endpoint Query
GET /v1/users SELECT with LEFT JOIN profile, optional filter, sort, pagination
GET /v1/users/:userId Same select plus WHERE u.id = $1
POST /v1/users INSERT ... RETURNING *
PATCH profile UPDATE user_profiles SET ... WHERE user_id = $n RETURNING *
DELETE DELETE ... WHERE ... RETURNING *

Get all users

SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
ORDER BY u.created_at DESC;

Get one user

The user ID arrives as a dynamic URL parameter and goes into the query as a parameter, never concatenated.

SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
WHERE u.id = $1;

Dynamic filter, sort and pagination

List endpoints (users, projects, tasks) usually support filtering, sorting and pagination together. The backend reads the query parameters, applies defaults for missing ones, and builds the SQL at runtime.

Query parameter If missing Notes
page 1 The user sees pages from 1
limit 10 (or 20) Page size
letter No filter Add the WHERE clause only if sent
sort_by created_at Allow only a whitelist: full_name, email, created_at
sort_order DESC ASC or DESC only

The finished query for filter by first letter, sort and page 1:

SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
WHERE u.full_name ILIKE $1 || '%'    -- $1 = 'j'; ILIKE ignores case
ORDER BY u.email ASC                 -- whitelisted column and direction
LIMIT $2 OFFSET $3;                  -- $2 = limit, $3 = (page - 1) * limit
  • ILIKE 'j%' matches names starting with J, in any case.
  • Page to offset: the user sees page 1, but the database offset starts at 0, so OFFSET = (page - 1) * limit. Page 2 with limit 1 is offset 1.
  • Sort fields are not values. In the lecture, TablePlus substitutes parameter text, so the column and direction were passed as parameters (with the table alias, u.email) and it worked. With a real driver, placeholders replace values only. Choose the column and direction from a whitelist in code, put them into the SQL text, and keep every user-supplied value as a parameter.
  • Always paginate list endpoints unless the UI has a specific reason not to.

Create a user

INSERT INTO users (email, full_name, password_hash)
VALUES ($1, $2, $3)
RETURNING *;

RETURNING * sends back the created row, including database-generated values like id and created_at, so the response needs no second query.

Partial update (PATCH)

The client may send any subset of bio, phone and avatar_url. The backend checks which fields arrived from an allowed set and builds the SET clause from only those. Fields not sent are untouched.

UPDATE user_profiles
SET bio = $1, phone = $2           -- only the fields that were sent
WHERE user_id = $3
RETURNING *;

Without a WHERE clause, an UPDATE changes every row.

Delete

DELETE FROM projects
WHERE id = $1
RETURNING *;

Without WHERE, every row is deleted. What else happens is decided by the foreign keys' ON DELETE rules: deleting this project also deletes its tasks and memberships (CASCADE). Deleting a user who owns projects fails (RESTRICT).

12. Triggers

A trigger runs a function automatically when an event happens on a table, and its most common job is keeping updated_at correct without any application code.

The problem

An UPDATE changes a row but leaves updated_at equal to created_at, because the default only applies on insert. Two ways to fix it:

  1. In application code: every update query also sets updated_at = now(). Easy to forget.
  2. With a trigger: the database does it on every update, for every caller (the lecture's choice).

How triggers work

  • A trigger has two parts: a trigger function holding the logic, and the trigger that binds the function to a table and an event.
  • Events: INSERT, UPDATE, DELETE, TRUNCATE. Timing: BEFORE or AFTER. Scope: FOR EACH ROW or FOR EACH STATEMENT.
  • Inside a row-level function, NEW is the row about to be written and OLD is the previous row.
CREATE FUNCTION set_updated_at() RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER users_set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();

Create one trigger per table (users, user_profiles, projects, tasks, and any other table with updated_at), each with its own name so it is easy to drop later.

In a migration

  • Up: create the function, then a trigger on each table.
  • Down: drop the triggers, then the function (the lecture's down section also drops the indexes created in the same migration).

Verifying

Run an update such as changing a profile's bio, then check the row: updated_at now shows the current time, while created_at stays unchanged.

13. Indexing

An index is a separate lookup structure that lets PostgreSQL find rows without scanning the whole table, at the cost of slower writes and extra storage.

How it works

  • Book analogy: to find chapter 4 you check the index for its page instead of flipping through 50 pages.
  • Without an index: the database does a sequential scan, checking each row in turn wherever it sits on disk. Fine for 6 rows, slow for millions.
  • With an index: a lookup table keeps each indexed value alongside the row's disk location, stored together and in order. The database finds the value quickly and jumps straight to the row. (The default structure is a B-tree; Hash, GIN, GiST and BRIN also exist.)
  • Order matters: an index can be ascending or descending. An index on created_at DESC matches a query with ORDER BY created_at DESC, so no re-sorting is needed.
  • Primary key and UNIQUE columns are indexed automatically. Foreign key columns are not.

When to create one

The rule of thumb is whether the column appears in a WHERE clause, a JOIN condition or an ORDER BY, and whether that query runs often.

  • Every index must be updated on each INSERT, UPDATE and DELETE, which adds overhead that grows with table size.
  • Don't index every column. Start with the frequent queries, monitor, and drop indexes that turn out unused.
  • In a multi-column index, column order matters.
  • Use EXPLAIN ANALYZE to check whether a query actually uses an index.
CREATE INDEX index_name ON table_name (column1 DESC);
CREATE UNIQUE INDEX index_name ON table_name (column1);
DROP INDEX index_name;

Indexes for the project schema

Index Reason
users(email) Finding a user by email in WHERE or JOIN
users(created_at DESC) Default sort of get-all-users
tasks(project_id) Foreign key used in the join that fetches a project's tasks
tasks(assigned_to) Foreign key used in the join that fetches a user's tasks
tasks(created_at DESC) Default sort of get-all-tasks
tasks(status) Filtering tasks by status (WHERE status = 'pending')
project_members(project_id) Foreign key used in joins
project_members(user_id) Foreign key used in joins

Primary keys such as projects.id and users.id need no extra index.

CREATE INDEX idx_users_email           ON users (email);
CREATE INDEX idx_users_created_at      ON users (created_at DESC);
CREATE INDEX idx_tasks_project_id      ON tasks (project_id);
CREATE INDEX idx_tasks_assigned_to     ON tasks (assigned_to);
CREATE INDEX idx_tasks_created_at      ON tasks (created_at DESC);
CREATE INDEX idx_tasks_status          ON tasks (status);
CREATE INDEX idx_project_members_project_id ON project_members (project_id);
CREATE INDEX idx_project_members_user_id    ON project_members (user_id);

The lecture puts these and the triggers in one migration, with matching DROP INDEX lines in the down section. One note: users.email is already UNIQUE, which PostgreSQL indexes automatically, so idx_users_email is redundant in this schema and can be skipped.

14. Request flow and key takeaways

Most backend database work is one repeatable loop: read what the client sent, build a query, bind the values as parameters, run it and return the rows.

[embedded content: request path · 6 stages, 4 data-layer steps]

A request is routed to a handler, passed to a service and then a repository, which talks to PostgreSQL; the rows come back the same way and are serialized to JSON for the front end. Parameter binding is the safety step.

Takeaways

  • Let the database enforce integrity with types, enums, constraints and foreign keys, instead of relying only on application code.
  • Change the schema only through versioned migrations, each with a rollback, and seed test data in its own migration.
  • Never build SQL by concatenating user input; use parameterized queries and whitelist sort columns.
  • Index columns used in frequent WHERE, JOIN and ORDER BY, index foreign keys yourself, and weigh the write overhead.
  • Use LEFT JOIN when the related row is optional, and always sort and paginate list endpoints.
  • Maintain updated_at with a trigger so no caller can forget it.

This covers about 80% of what a backend engineer does with a database. The rest, such as how B-trees and storage work internally, is optional depth.

Databases for Backend Engineers: Notes

Nov 24, 2026 · @MK

1. Databases and why we need them

A database persists application data across failures, crashes and intentional restarts, and in backend systems database operations are among the most frequent work you do.

What a database is

  • At its core, a database is any structure (program, system, technology or even a file) that lets you perform CRUD (create, read, update, delete) on data and keeps that data across sessions.
  • Persistence means data survives after the program that created it has stopped. A to-do app that reopens with your tasks exactly as you left them is relying on persistence; without it, you would start from nothing every time.
  • Everyday examples of a database:
    1. Notes in a notebook or text file
    2. The contact list on a phone
    3. A list or array of items inside a program
    4. Key-value entries in a browser's local storage (also session storage and cookies)
  • In backend engineering, "database" means a persistent, disk-based store that supports CRUD.

Primary vs secondary memory

Where data is stored decides speed, size and cost.

Primary memory (RAM) Secondary memory (HDD / SSD)
Speed Very fast Slow by comparison
Capacity Small (typically 8 to 128 GB on a consumer machine) Large (typically 512 GB to 2 TB)
Cost Expensive Relatively cheap
Persistence Lost on restart Survives restarts
Used by Caches such as Redis, in-memory caches Databases such as PostgreSQL, MongoDB
  • Databases accept slower access in exchange for far more space at lower cost, so traditional relational and non-relational databases are disk based.
  • Caching technologies keep hot data in RAM because reads and writes there are very fast.

2. DBMS (Database Management System)

A DBMS is software whose job is to store data and serve CRUD operations on it efficiently, securely and at scale.

Responsibilities

Responsibility Meaning
Data organization Lay data out so reads, updates and inserts stay efficient
Access Provide create, read, update and delete operations
Integrity Keep data accurate, valid and consistent. Example: a payment amount column of a numeric type rejects a string like "something" at the database level
Security Block unauthorized access using users and roles

A DBMS also handles scaling and load balancing, but storing data and providing CRUD are its two core duties.

Why not plain text files?

Early systems stored data in text files. The problems below are why DBMSs were created.

  • Parsing: every lookup needs application code that reads the file, splits lines and compares fields. This is slow (more so in JavaScript, Python or Ruby than in Rust) and easy to get wrong, and a mistake can corrupt data.
  • No structure: a text file accepts anything, so you cannot enforce rules such as "this field is numeric". Data fluidity means no consistency guarantee.
  • Unreliable and unsecured: anyone can edit the file, and an improper edit can corrupt it.
  • No concurrency control: two writers at once give an unpredictable result.

Concurrency example. An amount field holds 40. Two users read it at the same time. One adds 20 and saves 60; the other subtracts 20 and saves 20. Whoever saves last wins, and which one that is depends on CPU scheduling, so the final value could be 60 or 20 (the correct result would be 40). A DBMS has concurrency mechanisms to produce a consistent result.

A DBMS provides ACID properties (atomicity, consistency, isolation, durability) on data, which removes these disadvantages.

3. Types of databases and why PostgreSQL

Relational databases trade flexibility for robustness; non-relational databases do the opposite, and PostgreSQL covers most needs of both.

Relational Non-relational
Structure Tables of rows and columns; relationships through foreign keys Collections of entries (documents) of key-value pairs
Schema Predefined and strict; columns and types are decided up front None enforced; each document can have a different shape
Language SQL Database-specific query APIs
Integrity (ACID) Maintained by the database through the schema Rules must be set by the developer at the application level
Character Not flexible but robust Flexible but error-prone
Examples PostgreSQL, MySQL, SQLite, SQL Server MongoDB

Terminology mapping (MongoDB vs relational): a table is called a collection, and a row is called a document.

When to use which

  • Fixed, predefined structure: use a relational database. Example: a CRM stores contacts and sales opportunities, needs accurate and consistent data, and benefits from complex queries over relationships between customers.
  • Changing structure and many formats: a non-relational database fits. Example: a CMS stores articles that may contain images, code blocks or YouTube embeds, so the shape is not known in advance. It is also useful for fast prototyping without maintaining a schema.
  • Trade-off of non-relational: integrity is not enforced by the database, so validation moves into application code, which adds complexity and is easier to break because application code changes often.

Why PostgreSQL for most projects

  1. Open source and free, so companies can host and deploy it on their own servers.
  2. Sticks to the SQL standard, so queries behave the same as in MySQL or SQL Server and migrating to another database later takes only minor changes.
  3. Extensible: the documentation runs to roughly 1,400 pages and covers nearly every use case a typical SaaS meets, plus an extension system for customization.
  4. Reliable and scalable.
  5. Strong JSON support (a JSON / JSONB data type with good indexing and querying), so dynamic data does not require switching to a non-relational database.
  6. Good indexing and query mechanisms, and support for migrations through external tools.

Performance edges claimed for MySQL only matter once you serve millions of users and are tuning one specific bottleneck, so PostgreSQL is a safe first choice.

4. PostgreSQL data types

Pick the type by what the value means: exact money uses NUMERIC, free text uses TEXT, and timestamps that cross time zones use TIMESTAMPTZ.

Numeric

Type Size / range Use for Example values
SERIAL 4-byte auto-incrementing integer Auto-generated IDs; you omit it on insert 1, 2, 3
BIGSERIAL 8-byte auto-incrementing integer IDs for tables that may hold a very large number of rows (common choice in production) 1, 2, 3
SMALLINT 2 bytes, -32768 to 32767 Age, small counters 25, 1200
INTEGER 4 bytes, about ±2.1 billion Quantities, general counts 50000, -300
BIGINT 8 bytes, about ±9.2 quintillion View counts, millisecond timestamps 9876543210
DECIMAL / NUMERIC Exact; identical in PostgreSQL Money, prices, anything needing exact precision 99.99, 1500.50
REAL 4 bytes, about 6 digits, approximate Measurements such as temperature 36.6, 0.0025
DOUBLE PRECISION 8 bytes, about 15 digits, approximate Scientific values, coordinates 12.9715987
  • NUMERIC(10, 2): precision 10 means at most 10 digits in total; scale 2 means exactly 2 digits after the decimal point. So 12345678.90 fits and 123456789.00 does not.
  • Exact vs floating point: use NUMERIC when small discrepancies cause real damage (prices). Use REAL or DOUBLE PRECISION when tiny errors do not matter (an area like 567.8987). Floating point is faster to store and compute, which is why scientific work prefers it.

Text

Type Behavior Guidance
CHAR(n) Fixed length; shorter values are padded with spaces Only when every value has the same length (country codes 'IN', weekday codes)
VARCHAR(n) Variable length up to n; no padding; longer values raise an error Only when the database must enforce a maximum
TEXT Variable length, no declared limit Default choice for names, descriptions, comments

Prefer TEXT over VARCHAR(255):

  • PostgreSQL has no performance difference between them, and its documentation recommends TEXT.
  • 255 is a MySQL convention. In PostgreSQL it is a random number that misleads new readers into hunting for its meaning.
  • Raising a limit later needs a database migration touching live data, which is risky.
  • Enforce length in application code instead, so migrations stay simple. Backend engineers reach the database through drivers and application code, so this is natural.

Date and time

Type Stores Example
DATE Date only '2026-10-19'
TIME Time of day only (TIME WITH TIME ZONE also exists) '09:30:00'
TIMESTAMP Date and time, no time zone '2026-10-19 14:30:00'
TIMESTAMPTZ Date and time with zone awareness; stored in UTC, shown in the session time zone '2026-10-19 14:30:00+05:30'
INTERVAL A span of time '1 day', '2 hours 30 minutes'

Use TIMESTAMPTZ for created_at and updated_at columns.

Other types

Type Notes Example
BOOLEAN / BOOL TRUE or FALSE TRUE
UUID Native type, popular for primary keys. Generate with the built-in gen_random_uuid() (the uuid-ossp extension is optional and must be enabled with CREATE EXTENSION) '6e6a6c6f-6b6d-4a6e-866f-6c6d6e6f6a6c'
ENUM A custom type with a fixed set of allowed values, created with CREATE TYPE 'OPEN', 'CLOSED', 'IN_PROGRESS'
JSON Stored as plain text; keeps the input exactly '{"name": "John", "age": 30}'
JSONB Converted to PostgreSQL's internal binary format; faster to query and index. Usually the right choice; PostgreSQL-specific, not SQL standard '{"name": "John", "age": 30}'
ARRAY Ordered values of one type (all elements must share a type) '{1,2,3}' or ARRAY['a','b']
XML PostgreSQL has a native xml type '<name>John</name>'
POINT A point in 2D space '(1, 2)'
MACADDR A MAC address '00:11:22:33:44:55'
INET An IPv4 or IPv6 address '192.168.1.1'

Network, geometric and XML types are rarely used in typical backends; see the official documentation if you need them.

5. Schema design fundamentals

A good schema pushes validity checks into the database: strict types, enums, constraints and defaults, with consistent names.

Naming conventions

  • Table names are plural and snake_case: users, posts, comments, user_profiles. (Some teams prefer singular; the industry norm is plural. Follow your team.)
  • Column names are descriptive and snake_case: first_name, password_hash, created_at.
  • PostgreSQL folds unquoted identifiers to lowercase, so FullName and fullname are the same column. Keeping everything lowercase snake_case avoids double quotes everywhere in application code.

Enums as column types

An enum is a custom type with a predefined set of allowed values. Any other value is rejected by the database.

CREATE TYPE project_status AS ENUM ('active', 'completed', 'archived');

Two benefits:

  1. Integrity: the database validates the value, so an invalid string causes a database-level error even if application validation misses it.
  2. Documentation: anyone reading the migration sees every allowed value at a glance. With a plain TEXT column they would have to search all application code.

Give an enum column a sensible default, such as DEFAULT 'active'. Internally each value is stored compactly instead of as the full string.

Primary keys

  • A primary key uniquely identifies each row. It implies NOT NULL and UNIQUE, and PostgreSQL indexes it automatically.
  • Generate it with SERIAL / BIGSERIAL, or use UUID with a default of gen_random_uuid().
  • By convention the column is named id.
id UUID PRIMARY KEY DEFAULT gen_random_uuid()

Foreign keys

A foreign key is a column that references another table's primary key, written with REFERENCES. It rejects values that do not exist in the referenced table. See section 6 for relationships.

Constraints

Constraints protect a field from invalid data. Every violation is a database-level error.

Constraint Effect
NOT NULL The column cannot be NULL
UNIQUE No two rows share a value (example: email)
CHECK A custom condition must hold (example: priority INTEGER CHECK (priority BETWEEN 1 AND 5))
PRIMARY KEY Unique and not null; identifies the row
FOREIGN KEY Value must exist in the referenced column of another table
  • Columns are nullable by default. Add NOT NULL to most of them (over 70% of columns in a typical table). Automated scripts can have bugs, and without the constraint they quietly fill the table with nulls. Leave a column nullable only when absence is meaningful (a project description, a user's bio).

Default values

A default applies when an insert omits the column. It can be a constant or an expression.

created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
status project_status NOT NULL DEFAULT 'active',
priority INTEGER NOT NULL DEFAULT 1

Timestamps

Keep created_at (when the row first appeared) and updated_at (last change) on every table. Use TIMESTAMPTZ. updated_at also enables sorts like "recently changed first". Section 12 shows how to maintain it automatically.

Hashing credentials

Never store passwords, PINs or other secrets in plain text. The lecture stores a password_hash column and hashes in backend code. PostgreSQL can also hash with the pgcrypto extension:

CREATE EXTENSION IF NOT EXISTS pgcrypto;

INSERT INTO users (username, password)
VALUES ('john', crypt('john', gen_salt('bf')));

crypt() takes the plain value and a salt, and gen_salt('bf') generates a bcrypt salt.

6. Relationships and referential integrity

Relationships link rows through a foreign key that references a primary key; the three shapes differ in where the key sits and what constrains it.

Relationship Meaning How to implement
One-to-one A row in A relates to at most one row in B Foreign key in B that is UNIQUE, or the foreign key is B's primary key
One-to-many A row in A relates to many rows in B; each B row has one A Foreign key in the "many" table (B) referencing A's primary key
Many-to-many Many A rows relate to many B rows Junction table with a foreign key to each, and a composite primary key

One-to-one

Split data into a second table when it will grow or change on a different schedule. Example: user profile details (avatar, bio, phone, later social links) live in user_profiles, so the core users table is not touched by every new profile field.

-- Option A: separate id, unique foreign key
CREATE TABLE profiles (
  id SERIAL PRIMARY KEY,
  user_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  bio TEXT
);

-- Option B (used in the lecture): the foreign key is also the primary key
CREATE TABLE user_profiles (
  user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
  bio TEXT
);

Option B drops the extra id, because primary-key uniqueness already guarantees one profile per user.

One-to-many

One project has many tasks; each task belongs to one project. The foreign key is a plain column (not unique) on the "many" side.

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  title TEXT NOT NULL
);

Many-to-many

A test: look at it from both sides. A user can be on many projects, and a project can have many users, so the link needs its own table (a junction, linking, join or bridge table). The pair of foreign keys forms a composite primary key, which prevents the same pair appearing twice and is never null.

CREATE TABLE post_tags (
  post_id INT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
  tag_id INT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
  PRIMARY KEY (post_id, tag_id)
);

Data that describes the link itself (for example a member's role in a project) belongs in the junction table.

Referential integrity

  • A foreign key value must always refer to an existing row. Inserting a nonexistent value is rejected, even if it is a validly formatted UUID.
  • Deleting a referenced row that still has dependents is rejected unless a cascading action is set.

ON DELETE actions

Action Effect when the referenced row is deleted
RESTRICT Block the delete if dependent rows exist
NO ACTION Default. Rejects the delete if dependents exist, but the check can be deferred to the end of the transaction
CASCADE Delete dependent rows too
SET NULL Set the foreign key to NULL (errors if the column is NOT NULL)
SET DEFAULT Set the foreign key to its default value

The same options exist for ON UPDATE. Example choice: projects.owner_id ... ON DELETE RESTRICT means a user who owns projects cannot be deleted until those projects are handled.

7. Case study: project management platform schema

The lecture models five tables, three enums and four relationship patterns for a project management platform. The SQL below is reconstructed from the lecture's description.

Tables and relationships

Table Relationship Key design choice
users Parent of everything else email is UNIQUE; stores password_hash, never the password
user_profiles One-to-one with users user_id is both primary key and foreign key; avatar, bio, phone are nullable
projects Many projects per owner (users) owner_id ... ON DELETE RESTRICT; status enum defaults to active
tasks One-to-many from projects project_id ... ON DELETE CASCADE; assigned_to ... ON DELETE SET NULL; priority check 1 to 5
project_members Many-to-many between users and projects Composite primary key (project_id, user_id); role enum defaults to member

Every table has created_at and updated_at (TIMESTAMPTZ, default now()).

Up migration

-- enums
CREATE TYPE project_status AS ENUM ('active', 'completed', 'archived');
CREATE TYPE task_status    AS ENUM ('pending', 'in_progress', 'completed', 'cancelled');
CREATE TYPE member_role    AS ENUM ('owner', 'admin', 'member');

CREATE TABLE users (
  id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email         TEXT NOT NULL UNIQUE,
  full_name     TEXT NOT NULL,
  password_hash TEXT NOT NULL,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- one-to-one with users
CREATE TABLE user_profiles (
  user_id    UUID PRIMARY KEY REFERENCES users(id),
  avatar_url TEXT,
  bio        TEXT,
  phone      TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE projects (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name        TEXT NOT NULL,
  description TEXT,
  status      project_status NOT NULL DEFAULT 'active',
  owner_id    UUID NOT NULL REFERENCES users ON DELETE RESTRICT,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- one-to-many from projects
CREATE TABLE tasks (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  project_id  UUID NOT NULL REFERENCES projects ON DELETE CASCADE,
  title       TEXT NOT NULL,
  description TEXT,
  priority    INTEGER NOT NULL DEFAULT 1 CHECK (priority BETWEEN 1 AND 5),
  status      task_status NOT NULL DEFAULT 'pending',
  due_date    DATE,
  assigned_to UUID REFERENCES users ON DELETE SET NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- many-to-many linking table
CREATE TABLE project_members (
  project_id UUID NOT NULL REFERENCES projects ON DELETE CASCADE,
  user_id    UUID NOT NULL REFERENCES users ON DELETE CASCADE,
  role       member_role NOT NULL DEFAULT 'member',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (project_id, user_id)
);

Down migration

Undo everything in reverse order: tables that reference others first, types last.

DROP TABLE project_members;
DROP TABLE tasks;
DROP TABLE projects;
DROP TABLE user_profiles;
DROP TABLE users;
DROP TYPE member_role;
DROP TYPE task_status;
DROP TYPE project_status;

Why these choices

  • ON DELETE RESTRICT on owner_id: a user cannot be deleted while they own projects. CASCADE would delete the projects too; SET NULL would fail because the column is NOT NULL.
  • ON DELETE CASCADE on tasks.project_id: deleting a project removes its tasks. NOT NULL also means no orphan task can exist.
  • ON DELETE SET NULL on tasks.assigned_to: deleting a user keeps their tasks and just unassigns them.
  • Composite key on project_members: user 1 in project 2 is one fact that cannot repeat. Role is stored here because it only exists when a user is part of a project.
  • Foreign key constraint: you cannot assign a task to a UUID that is not in users.

8. Migrations

A migration is a versioned, committed change to the database (mostly schema, sometimes data), so every change is tracked and reversible instead of typed into a GUI.

Why not run SQL from a GUI?

In production you cannot just open a tool and execute queries: there is no record of what changed, who changed it or when, and no way to version or roll back the database state. Migrations give you both.

How they work

  • Each change is a numbered or timestamped SQL file in a folder such as db/migrations/, committed to Git alongside the code.
  • A file has an up section that applies the change (create table, create type, create index) and a down section that reverts exactly that change. Some modern approaches skip down migrations, but they are the standard way and enable rollback.
  • A migration tool (DBMate, Flyway, Liquibase, Alembic, Prisma Migrate, golang-migrate) runs pending files in order and records the current version in a table, so each runs only once. DBMate keeps this in schema_migrations.
  • Files are ordered by their names. Timestamps keep one consistent sequence.
  • To revert, run the down migration to return to the previous state.

DBMate workflow

  1. Put the connection string in .env: DATABASE_URL=postgres://...
  2. Create a migration: dbmate new create_users_table. It creates db/migrations/<timestamp>_create_users_table.sql.
  3. Fill in the file:
-- migrate:up
CREATE TABLE users ( ... );

-- migrate:down
DROP TABLE users;
  1. Apply: dbmate up. Roll back the latest migration: dbmate rollback.
  2. Inspect the result in a GUI client (the lecture uses TablePlus). The schema_migrations table shows the current version.

If the tool re-ran old files, PostgreSQL would error with "table already exists". Tracking the version is what lets it start from where it left off.

When to write a migration

New features with schema changes, performance fixes such as indexes, new constraints, keeping all environments in sync, and moving to a new server or engine.

Standard procedure

  1. Write the migration with a rollback.
  2. Back up production before applying.
  3. Test locally, then staging, then production.
  4. Verify; roll back if it fails.

Good practices

  • Keep files small and simple, with one naming convention and a consistent order.
  • Commit migration files to the repository.
  • Use separate migrations for different concerns (schema, seed data, indexes and triggers).

9. Seeding data

Seeding fills a development or test database with sample data so you can test APIs before real users exist; keep it in its own migration file.

  • Production data arrives through normal user flows (sign-up forms, project forms). In development you need test data instead.
  • Seed with a SQL script or program that inserts rows. Best practice is a separate migration, for example dbmate new seed_data, which sorts after the schema migration because its timestamp is later. Run it with dbmate up.
  • Never seed test data into production.

Technique: chained CTEs

A common table expression (CTE) names an intermediate result so a multi-step insert reads cleanly. Each step inserts rows and returns what the next step needs:

WITH inserted_users AS (
  INSERT INTO users (email, full_name, password_hash)
  VALUES
    ('alice@example.com', 'Alice Brown', 'hash1'),
    ('john@example.com',  'John Doe',    'hash2')
  RETURNING id, email
),
inserted_profiles AS (
  INSERT INTO user_profiles (user_id, avatar_url, bio, phone)
  SELECT
    id,
    'https://example.com/avatar.png',
    CASE email
      WHEN 'alice@example.com' THEN 'Designer who loves charts'
      WHEN 'john@example.com'  THEN 'Backend engineer'
      ELSE 'Team member'
    END,
    '+1-555-0100'
  FROM inserted_users
  RETURNING user_id
)
INSERT INTO projects (name, description, owner_id)
SELECT 'Website redesign', 'Seeded project', id
FROM inserted_users
WHERE email = 'alice@example.com';
  • RETURNING id, email hands the generated IDs to the next step, so you never hard-code UUIDs.
  • INSERT ... SELECT ... FROM inserted_users builds profile rows from the users just created.
  • CASE varies the sample data per row.

Projects, tasks and project members are seeded the same way. Afterwards, open the tables in your GUI client to confirm rows exist.

10. Querying data

SELECT retrieves rows; clauses are optional except SELECT itself, but must appear in a fixed order.

SELECT syntax

SELECT column1, column2        -- columns or expressions; * means all
FROM table_name alias          -- the table to read (an alias is a short name)
LEFT JOIN other_table o        -- INNER JOIN, LEFT JOIN, RIGHT JOIN
  ON alias.id = o.alias_id     -- join condition
WHERE condition                -- filters rows before grouping
GROUP BY column1               -- groups rows; used with COUNT, SUM, AVG
HAVING condition               -- filters groups after grouping
ORDER BY column1 ASC | DESC    -- ascending by default
LIMIT count                    -- max rows returned
OFFSET start;                  -- rows to skip (pagination)

Write the FROM and JOIN part first when composing, so you know where the data comes from before choosing what to select.

Joins

  • INNER JOIN returns a row only when both tables match. If a user has no profile row, that user disappears from the result.
  • LEFT JOIN keeps every row of the left table even without a match. Use it when the related row is optional (a user who never edited their profile).
  • Embedding a related row as JSON in one query saves the client a second API call:
SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
ORDER BY u.created_at DESC;

to_jsonb(up.*) is a PostgreSQL function that turns the joined profile row into a JSON object named profile.

Result order is not guaranteed

Without ORDER BY, rows come back in no defined order. Always sort list endpoints, usually by created_at DESC so the newest items come first.

Parameterized queries

A parameterized query sends the SQL text and the values separately. The text holds numbered placeholders ($1, $2), and values are supplied at execution time.

  • Values are always treated as data, never as SQL, so input like '; DELETE FROM users; -- is just a harmless string. This prevents SQL injection.
  • The unsafe alternative is building the query by concatenating strings. Never do that with user input.
  • In SQL itself:
PREPARE get_user (UUID) AS
SELECT * FROM users WHERE id = $1;

EXECUTE get_user('6e6a6c6f-6b6d-4a6e-866f-6c6d6e6f6a6c');
  • In application code, database drivers and ORMs accept the query text and an array of values as separate arguments, so you rarely write PREPARE yourself. GUI clients such as TablePlus also prompt for parameter values.
  • Parameters only replace values. Column names and sort directions cannot be parameters, so allow them from a whitelist (section 11).

11. Mapping APIs to SQL

Each REST endpoint becomes one parameterized query, and the backend's job is to read the request, build the query, pass values as parameters and return rows.

Endpoint Query
GET /v1/users SELECT with LEFT JOIN profile, optional filter, sort, pagination
GET /v1/users/:userId Same select plus WHERE u.id = $1
POST /v1/users INSERT ... RETURNING *
PATCH profile UPDATE user_profiles SET ... WHERE user_id = $n RETURNING *
DELETE DELETE ... WHERE ... RETURNING *

Get all users

SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
ORDER BY u.created_at DESC;

Get one user

The user ID arrives as a dynamic URL parameter and goes into the query as a parameter, never concatenated.

SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
WHERE u.id = $1;

Dynamic filter, sort and pagination

List endpoints (users, projects, tasks) usually support filtering, sorting and pagination together. The backend reads the query parameters, applies defaults for missing ones, and builds the SQL at runtime.

Query parameter If missing Notes
page 1 The user sees pages from 1
limit 10 (or 20) Page size
letter No filter Add the WHERE clause only if sent
sort_by created_at Allow only a whitelist: full_name, email, created_at
sort_order DESC ASC or DESC only

The finished query for filter by first letter, sort and page 1:

SELECT u.*, to_jsonb(up.*) AS profile
FROM users u
LEFT JOIN user_profiles up ON u.id = up.user_id
WHERE u.full_name ILIKE $1 || '%'    -- $1 = 'j'; ILIKE ignores case
ORDER BY u.email ASC                 -- whitelisted column and direction
LIMIT $2 OFFSET $3;                  -- $2 = limit, $3 = (page - 1) * limit
  • ILIKE 'j%' matches names starting with J, in any case.
  • Page to offset: the user sees page 1, but the database offset starts at 0, so OFFSET = (page - 1) * limit. Page 2 with limit 1 is offset 1.
  • Sort fields are not values. In the lecture, TablePlus substitutes parameter text, so the column and direction were passed as parameters (with the table alias, u.email) and it worked. With a real driver, placeholders replace values only. Choose the column and direction from a whitelist in code, put them into the SQL text, and keep every user-supplied value as a parameter.
  • Always paginate list endpoints unless the UI has a specific reason not to.

Create a user

INSERT INTO users (email, full_name, password_hash)
VALUES ($1, $2, $3)
RETURNING *;

RETURNING * sends back the created row, including database-generated values like id and created_at, so the response needs no second query.

Partial update (PATCH)

The client may send any subset of bio, phone and avatar_url. The backend checks which fields arrived from an allowed set and builds the SET clause from only those. Fields not sent are untouched.

UPDATE user_profiles
SET bio = $1, phone = $2           -- only the fields that were sent
WHERE user_id = $3
RETURNING *;

Without a WHERE clause, an UPDATE changes every row.

Delete

DELETE FROM projects
WHERE id = $1
RETURNING *;

Without WHERE, every row is deleted. What else happens is decided by the foreign keys' ON DELETE rules: deleting this project also deletes its tasks and memberships (CASCADE). Deleting a user who owns projects fails (RESTRICT).

12. Triggers

A trigger runs a function automatically when an event happens on a table, and its most common job is keeping updated_at correct without any application code.

The problem

An UPDATE changes a row but leaves updated_at equal to created_at, because the default only applies on insert. Two ways to fix it:

  1. In application code: every update query also sets updated_at = now(). Easy to forget.
  2. With a trigger: the database does it on every update, for every caller (the lecture's choice).

How triggers work

  • A trigger has two parts: a trigger function holding the logic, and the trigger that binds the function to a table and an event.
  • Events: INSERT, UPDATE, DELETE, TRUNCATE. Timing: BEFORE or AFTER. Scope: FOR EACH ROW or FOR EACH STATEMENT.
  • Inside a row-level function, NEW is the row about to be written and OLD is the previous row.
CREATE FUNCTION set_updated_at() RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER users_set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();

Create one trigger per table (users, user_profiles, projects, tasks, and any other table with updated_at), each with its own name so it is easy to drop later.

In a migration

  • Up: create the function, then a trigger on each table.
  • Down: drop the triggers, then the function (the lecture's down section also drops the indexes created in the same migration).

Verifying

Run an update such as changing a profile's bio, then check the row: updated_at now shows the current time, while created_at stays unchanged.

13. Indexing

An index is a separate lookup structure that lets PostgreSQL find rows without scanning the whole table, at the cost of slower writes and extra storage.

How it works

  • Book analogy: to find chapter 4 you check the index for its page instead of flipping through 50 pages.
  • Without an index: the database does a sequential scan, checking each row in turn wherever it sits on disk. Fine for 6 rows, slow for millions.
  • With an index: a lookup table keeps each indexed value alongside the row's disk location, stored together and in order. The database finds the value quickly and jumps straight to the row. (The default structure is a B-tree; Hash, GIN, GiST and BRIN also exist.)
  • Order matters: an index can be ascending or descending. An index on created_at DESC matches a query with ORDER BY created_at DESC, so no re-sorting is needed.
  • Primary key and UNIQUE columns are indexed automatically. Foreign key columns are not.

When to create one

The rule of thumb is whether the column appears in a WHERE clause, a JOIN condition or an ORDER BY, and whether that query runs often.

  • Every index must be updated on each INSERT, UPDATE and DELETE, which adds overhead that grows with table size.
  • Don't index every column. Start with the frequent queries, monitor, and drop indexes that turn out unused.
  • In a multi-column index, column order matters.
  • Use EXPLAIN ANALYZE to check whether a query actually uses an index.
CREATE INDEX index_name ON table_name (column1 DESC);
CREATE UNIQUE INDEX index_name ON table_name (column1);
DROP INDEX index_name;

Indexes for the project schema

Index Reason
users(email) Finding a user by email in WHERE or JOIN
users(created_at DESC) Default sort of get-all-users
tasks(project_id) Foreign key used in the join that fetches a project's tasks
tasks(assigned_to) Foreign key used in the join that fetches a user's tasks
tasks(created_at DESC) Default sort of get-all-tasks
tasks(status) Filtering tasks by status (WHERE status = 'pending')
project_members(project_id) Foreign key used in joins
project_members(user_id) Foreign key used in joins

Primary keys such as projects.id and users.id need no extra index.

CREATE INDEX idx_users_email           ON users (email);
CREATE INDEX idx_users_created_at      ON users (created_at DESC);
CREATE INDEX idx_tasks_project_id      ON tasks (project_id);
CREATE INDEX idx_tasks_assigned_to     ON tasks (assigned_to);
CREATE INDEX idx_tasks_created_at      ON tasks (created_at DESC);
CREATE INDEX idx_tasks_status          ON tasks (status);
CREATE INDEX idx_project_members_project_id ON project_members (project_id);
CREATE INDEX idx_project_members_user_id    ON project_members (user_id);

The lecture puts these and the triggers in one migration, with matching DROP INDEX lines in the down section. One note: users.email is already UNIQUE, which PostgreSQL indexes automatically, so idx_users_email is redundant in this schema and can be skipped.

14. Request flow and key takeaways

Most backend database work is one repeatable loop: read what the client sent, build a query, bind the values as parameters, run it and return the rows.

A request is routed to a handler, passed to a service and then a repository, which talks to PostgreSQL; the rows come back the same way and are serialized to JSON for the front end. Parameter binding is the safety step.

This covers about 80% of what a backend engineer does with a database. The rest, such as how B-trees and storage work internally, is optional depth.

About the author

  • My journey started as a Computer Engineering student with a deep curiosity about how software systems are built from the ground up. During college, I dove into web development, databases, and machine learning — shaping a strong foundation in problem-solving and software engineering. I graduated with a Grade A+ and went on to publish research on a KNN-based recommendation system I built as part of my final-year project. After college, I started out building UI dashboards integrated with Microsoft Dynamics 365, improving data visualization by 40% and cutting decision-making time by 25%. I then grew into a Full Stack role — developing a payment gateway serving 66 million users with 125,000 daily transactions, and a real-time analytics dashboard powered by Apache Kafka and Pinot that reduced query latency by 76%. Outside of work, I enjoy building personal projects — from a neighbourhood e-commerce platform to a URL shortener and a video streaming service. I'm driven by clean architecture, real-world performance, and the satisfaction of shipping systems that actually work under pressure.

No comments yet. Be the first to comment.

First Principles of Backend Engineering

Part 18 of 18

An in-depth article series deconstructing the core mechanics of backend systems. Moving beyond frameworks and trendy tools, this series explores the fundamental building blocks of the web—from network protocols and reverse proxies to database architecture and server security—helping you understand exactly how and why scalable systems work from the ground up.

Start from the beginningIntroduction to Back-endLearn what is back-end, request to back-end, components of back-end, why front-end can do back-end task

More from this blog