Backend Databases: From Schema to Scale
Learn database fundamentals, PostgreSQL, schema design, migrations, querying, indexing, and triggers for building scalable backend systems.
Databases for Backend Engineers: Concepts, PostgreSQL, and Migrations
Backend engineering revolves around data. You build APIs to accept data, process it, and store it. Interacting with databases is one of the most frequent operations you will perform. Understanding the concepts surrounding databases is crucial for building efficient, scalable systems.
#Table of Contents
- Why Do We Need Databases?
- What Is a Database?
- Database Management Systems (DBMS)
- Why Not Just Use Text Files?
- Relational vs. Non-Relational Databases
- Why Choose PostgreSQL?
- PostgreSQL Data Types Deep Dive
Creating the Database Schema: Migrations, Relationships
- Database Design: Project Management Platform
- Database Migrations
- Setting Up Database Migrations
- Custom ENUM Types
- Naming Conventions
- The Users Table
- One-to-One Relationship: User Profiles
- The Projects Table and Referential Integrity
- One-to-Many Relationship: Tasks
- Many-to-Many Relationship: Project Members
- Down Migrations and Execution
Seeding, Querying, and Optimizing PostgreSQL for Backend APIs
- Seeding: Inserting Test Data
- Writing Database Queries for APIs
- Database Indexes: Optimizing Query Performance
- What Is Database Indexing?
- Index Ordering
- When to Create Indexes
- Creating Indexes in Migrations
- Index Performance Trade-offs
Database Indexes, Triggers, and the Backend Engineering Workflow
- Automating Timestamps with Database Triggers
- Automating Timestamps with Triggers
- The Backend Engineering Workflow
#Why Do We Need Databases?
At its core, a database is a mechanism to persist information across sessions. Persistence means storing data so it survives even after the program that created it stops.
Think of a to-do list application. You add tasks, check them off, and close the app. When you reopen it, your progress is still there. Without persistence, you would have to recreate your tasks every time you opened the application. Persistence ensures that the state of your data remains exactly as you left it, regardless of time or physical location.
#What Is a Database?
The term is surprisingly broad. Any structured storage can technically be considered a database. Your phone's contact list, browser local storage, session storage, cookies, or even a simple text file where you jot down notes—all of these provide a way to create, read, update, and delete (CRUD) data.
However, in the context of backend systems and servers, "database" specifically refers to disk-based databases.
Disk Storage vs. Primary Memory (RAM)
Why do we store database records on disk (HDDs or SSDs) instead of RAM?
RAM (primary memory) is extremely fast for data retrieval and saving. But it is expensive and limited in capacity. A typical server might have 32GB to 128GB of RAM.
Disk storage (secondary memory) is relatively cheap and offers massive capacity, ranging from 512GB to multiple terabytes. The trade-off is speed. Disk-based storage is slower than RAM due to the physical or electronic mechanisms required to read and write data.
This is why caching mechanisms like Redis store data in RAM for high-speed access, while traditional databases like PostgreSQL or MongoDB store data on disk to handle massive volumes of data cost-effectively. For databases, capacity and persistence matter more than raw microsecond latency.
#Database Management Systems (DBMS)
Simply dumping data onto a disk is not enough. You need a way to retrieve, update, and delete that data efficiently, especially when dealing with hundreds of gigabytes or terabytes of information.
This is where a Database Management System (DBMS) comes in. A DBMS is a software system designed to efficiently manage CRUD operations. Its core responsibilities include:
- Data Organization: Structuring data on disk using algorithms (like B-Trees) so that fetching, updating, and creating records is fast.
- Access: Providing interfaces and query languages (like SQL) to perform operations.
- Integrity: Ensuring data accuracy and validity. If a column expects a numeric payment amount, the DBMS rejects string inputs.
- Security: Protecting data from unauthorized access through user roles, permissions, and encryption.
#Why Not Just Use Text Files?
Before modern DBMS software existed, people stored data in plain text files. This approach fails at scale for three main reasons:
- Parsing Overhead: To find a specific customer in a text file, your application code must read the file, split the lines, and compare fields. This is slow and error-prone, especially in interpreted languages like Python or JavaScript.
- Lack of Structure: Text files have no formal schema. You cannot enforce that a specific field only accepts numbers. Any string can be dumped into the file, making data consistency impossible to guarantee.
- Concurrency Issues: If two users try to update the same record in a text file simultaneously, race conditions occur. Both read the initial value, make their modifications, and write back. The last write wins, and the other update is silently lost. A DBMS handles concurrency using locking mechanisms and transactions to ensure data consistency.
#Relational vs. Non-Relational Databases
DBMS software generally falls into two categories: relational and non-relational.
| Feature | Relational Databases (SQL) | Non-Relational Databases (NoSQL) |
|---|---|---|
| Structure | Tables with rows and columns. | Collections, documents, key-value pairs, or graphs. |
| Schema | Strict. Must be defined before inserting data. | Flexible. Schema can be dynamic or non-existent. |
| Relationships | Defined using foreign keys and joins. | Handled via embedded documents or application-level logic. |
| Integrity | Enforced at the database level. | Enforced at the application level. |
| Examples | PostgreSQL, MySQL, SQL Server. | MongoDB, Cassandra, DynamoDB. |
Use Case: CRM (Relational)
A Customer Relationship Management (CRM) system requires strict data integrity for contacts, sales opportunities, and financial records. Complex queries and relationship analysis are critical. A relational database like PostgreSQL is the correct choice here because it guarantees data consistency and supports complex joins.
Use Case: CMS (Non-Relational)
A Content Management System (CMS) stores articles that might contain text, images, embedded videos, and code blocks. The structure is highly dynamic and unpredictable. A non-relational database like MongoDB is ideal because you can push JSON documents on the fly without predefined schemas.
The trade-off with NoSQL is that the lack of database-level schema enforcement means you must handle data integrity in your application code, which adds complexity and increases the risk of bugs.
#Why Choose PostgreSQL?
When building a new backend system, choosing a database can be overwhelming. For most backend systems, PostgreSQL is the pragmatic default choice for several reasons:
- Open Source and Free: It is completely open source, allowing companies to host it on their own infrastructure without licensing fees.
- Strict SQL Standard Compliance: PostgreSQL adheres closely to the SQL standard. If you write standard SQL queries, migrating to another relational database like MySQL in the future requires minimal changes.
- Highly Extensible: The feature set is vast. It covers almost every use case a SaaS product might encounter and supports custom extensions (like PostGIS for geospatial data).
- Reliability and Scalability: It is battle-tested and known for handling heavy workloads reliably without data corruption.
- Excellent JSON Support: This is a major advantage. PostgreSQL offers native
JSONandJSONBdata types with powerful indexing and querying capabilities. If you need the flexibility of a NoSQL database for dynamic data, you can just use aJSONBcolumn in PostgreSQL instead of spinning up a separate MongoDB instance.
Note: This blog assumes you understand basic SQL syntax (SELECT, INSERT, CREATE TABLE). If you need a primer on basic SQL or PostgreSQL installation, there are countless free resources available. We will focus strictly on backend-relevant concepts.
#PostgreSQL Data Types Deep Dive
Choosing the right data type is critical for performance, storage efficiency, and data integrity.
Numeric Types
- SERIAL / BIGSERIAL: Auto-incrementing integers.
BIGSERIALis preferred for primary keys in production systems due to its massive capacity (up to 9 quintillion). - SMALLINT, INTEGER, BIGINT: Standard integers with increasing storage capacities. Choose based on the maximum expected value to save disk space.
- DECIMAL / NUMERIC: Exact numeric types. Defined as
DECIMAL(precision, scale). For example,DECIMAL(10, 2)stores up to 10 digits in total, with exactly 2 digits after the decimal point (e.g.,12345678.90). - REAL / DOUBLE PRECISION (FLOAT): Approximate numeric types.
- Rule of thumb: Use
DECIMALfor fields where accuracy is critical, likepriceoraccount_balance. Floating-point math can introduce tiny rounding errors. UseFLOATfor scientific computations or measurements (likeareaorweight) where microscopic discrepancies do not matter and processing speed is prioritized.
- Rule of thumb: Use
String Types
- CHAR(n): Fixed-length. If you define
CHAR(10)and insert "AB", the database pads it with 8 spaces. Only use this if you know the length is always exactly the same (e.g., country codes like "US", "IN", or day abbreviations like "Mo", "Tu"). - VARCHAR(n): Variable-length with a maximum limit.
VARCHAR(255)stores up to 255 characters but only uses the space required for the actual string. - TEXT: Variable-length with no practical upper limit.
Which string type should you choose?
Always use TEXT in PostgreSQL. There is a common misconception inherited from MySQL that VARCHAR(255) is faster or required for indexing. In PostgreSQL, TEXT and VARCHAR have identical performance characteristics.
Using TEXT prevents unnecessary database migrations if a string eventually exceeds an arbitrary limit like 255 characters. Enforce length limits in your application code (via your validation pipeline), not your database schema. This keeps your SQL migrations clean and prevents new developers from guessing why a random number like 255 was chosen.
Other Common Types
- BOOLEAN: Stores
TRUEorFALSE. - DATE / TIME / TIMESTAMP: Stores date, time, or both. Always use
TIMESTAMP WITH TIME ZONE(TIMESTAMPTZ) to avoid timezone-related bugs when your application scales globally. - INTERVAL: Stores durations (e.g., "10 days", "2 hours").
- UUID: A 128-bit unique identifier. Excellent for primary keys, especially in distributed systems or microservices, as they are URL-friendly and globally unique without requiring a central sequence generator.
- JSON / JSONB: Stores JSON data.
JSONstores it as plain text.JSONBstores it in a decomposed binary format, which is slightly slower to write but significantly faster to read, query, and index. Always useJSONB. - Arrays: PostgreSQL allows storing arrays of any data type (e.g.,
INTEGER[],TEXT[]). Use this instead of creating a separate join table for simple one-to-many relationships.
Inserting Data
INSERT INTO table_name (field1, field2, field3)
VALUES (value1, value2, value3);Ensure the order of values matches the order of the specified columns. PostgreSQL will strictly enforce the data types defined in the table schema during insertion.
#Database Design: Project Management Platform
To understand advanced database concepts, we will design the database for a project management platform (similar to the API we designed in previous modules). We will use this schema to write queries for various API endpoints, covering organizations, projects, and tasks.
Before we write the schema, we need to discuss how schema changes are managed in a professional backend environment.
#Database Migrations
In production systems, you never open a GUI tool like TablePlus and manually execute SQL queries to change your schema. Doing so makes it impossible to track changes, roll back errors, or synchronize the schema across different environments (development, staging, production).
Instead, we use database migrations.
Migrations are version-controlled files (usually SQL scripts) that define changes to your database schema. They are stored in your code repository, typically in a folder structure like db/migrations/.
How Migrations Work
You use a migration tool (like dbmate, go-migrate, or Prisma Migrate). The tool reads the migration files in sequential order and applies the SQL statements to your database.
The tool also creates a tracking table (e.g., schema_migrations) in your database to record which migrations have been applied. If the tracking table says the current version is 4, the tool will only execute 5.sql and subsequent files.
Up and Down Migrations
A migration file typically contains two sections:
- Up Migration: The changes you want to apply (e.g.,
CREATE TABLE,ADD COLUMN,CREATE INDEX). - Down Migration: The exact reverse of the up migration (e.g.,
DROP TABLE,DROP COLUMN).
If a deployment fails or introduces a critical bug, you can trigger a rollback. The migration tool will execute the down migration for the latest version, reverting the database to its previous stable state.
Why Migrations are Essential
- Version Control: Your database schema evolves alongside your application code. Migrations ensure the schema changes are committed to Git and reviewed in pull requests alongside your backend logic.
- Environment Synchronization: When a new developer joins the team, they can run a single command to apply all migrations and get a fully structured local database. The same applies to spinning up new staging or production environments.
- Safe Rollbacks: If a deployment breaks production, you can safely revert the database schema without manual intervention or data loss.
Any change to a relational database—adding a table, modifying a column, creating an index—must be done through a migration file. This discipline is what separates a tutorial project from a production-grade backend system.
Creating the Database Schema: Migrations, Relationships
Modeling a database for a production system requires more than just writing CREATE TABLE statements. It requires foresight into data integrity, scalability, and team collaboration.
#Setting Up Database Migrations
In production environments, you never open a GUI tool and manually execute schema changes. Doing so makes it impossible to track history, synchronize environments, or roll back errors. Instead, we use database migrations.
We will use dbmate, a lightweight, framework-agnostic command-line migration tool.
Initial Setup
First, configure your database connection by creating a .env file:
DATABASE_URL=postgres://username:password@localhost:5432/project_management?sslmode=disableTo generate a new migration file, run:
dbmate new create_users_tableThis command creates a db/migrations/ directory and generates a timestamped SQL file (e.g., 20231025120000_create_users_table.sql).
Migration File Structure
A standard migration file contains two sections:
-- migrate:up
-- SQL statements to apply the change (e.g., CREATE TABLE)
-- migrate:down
-- SQL statements to revert the change (e.g., DROP TABLE)#Custom ENUM Types
Before creating tables, we define custom ENUM types for fields with a strict, predefined set of allowed values.
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');Why Use ENUMs?
- Data Integrity: The database enforces validity. If application code attempts to insert
'archieved'(typo) into aproject_statuscolumn, PostgreSQL rejects it immediately. You offload validation from the application layer to the database layer. - Self-Documenting Schema: When a new engineer reviews the migration history, they instantly see the allowed states for a field. If the column were just
TEXT, they would have to grep through the entire application codebase to discover the valid values.
#Naming Conventions
Adhering to strict naming conventions prevents friction between your application code and the database.
- Plural Table Names: Use
users,projects, andtasks. While singular names are sometimes used, plural is the prevailing industry standard for tables representing collections of records. - Lowercase and
snake_case: PostgreSQL folds unquoted identifiers to lowercase. If you name a columnfullName, PostgreSQL stores it asfullname. To preserve case, you must wrap it in double quotes ("fullName"), which clutters your application code and SQL queries. Always use lowercase with underscores for multi-word identifiers (e.g.,password_hash,created_at).
#The Users Table
The users table is the foundation of the platform.
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 TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);Key Concepts
- Primary Key: The
idcolumn is the primary key. This implicitly enforcesNOT NULLandUNIQUEconstraints. We useUUIDwithgen_random_uuid()to generate globally unique identifiers without relying on a centralized sequence, which is ideal for distributed systems. - NOT NULL by Default: Over 70% of your columns should be
NOT NULL. Allowing nulls by default invites silent data corruption, especially when automated scripts or buggy application logic insert incomplete records. Only omitNOT NULLwhen a field is genuinely optional. - UNIQUE: Applied to
emailto prevent duplicate account registrations at the database level. - Timestamps:
TIMESTAMP WITH TIME ZONEensures that date and time data remains accurate regardless of the server's or client's geographic location.
#One-to-One Relationship: User Profiles
Storing extensive profile data (bio, phone number, social links, preferences) directly in the users table bloats the core authentication table. We separate this into a user_profiles table.
CREATE TABLE user_profiles (
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
image_url TEXT,
bio TEXT,
phone_number TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);Implementation Details
- Shared Primary Key: Notice there is no separate
idcolumn. Theuser_idacts as both the Primary Key for this table and a Foreign Key referencingusers(id). - Enforcing 1:1: Because
user_idis the primary key, it is inherentlyUNIQUE. A single user can only have one profile row. - Nullable Fields:
image_url,bio, andphone_numberare optional, so they omit theNOT NULLconstraint.
#The Projects Table and Referential Integrity
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(id) ON DELETE RESTRICT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);Referential Integrity Constraints
The owner_id column links a project to its creator. The ON DELETE clause dictates what happens to the project if the owning user is deleted:
| Constraint | Behavior | Use Case |
|---|---|---|
RESTRICT | Prevents the deletion of the parent record if child records exist. | Default for critical relationships. You cannot delete a user who owns projects. |
CASCADE | Automatically deletes all child records when the parent is deleted. | Useful for dependent data that has no meaning without the parent (e.g., deleting a project deletes its tasks). |
SET NULL | Sets the foreign key to NULL when the parent is deleted. | Only works if the column is not NOT NULL. |
SET DEFAULT | Sets the foreign key to its default value when the parent is deleted. | Rarely used, but available for specific fallback scenarios. |
Using ON DELETE RESTRICT here ensures data consistency: a project cannot become orphaned or lose its owner silently.
#One-to-Many Relationship: Tasks
A single project can contain multiple tasks, but a task belongs to only one project.
CREATE TABLE tasks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
title TEXT NOT NULL,
description TEXT,
priority INTEGER NOT NULL DEFAULT 1 CHECK (priority BETWEEN 1 AND ",
status task_status NOT NULL DEFAULT 'pending',
due_date DATE,
assigned_to UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);Key Concepts
- Foreign Key with CASCADE: If a project is deleted,
ON DELETE CASCADEensures all associated tasks are automatically removed, preventing orphaned records. - CHECK Constraint:
CHECK (priority BETWEEN 1 AND 5)enforces business logic at the database level. Even if the application layer fails to validate the input, the database will reject a priority of99. - SET NULL on Assignment: If a user is deleted from the system,
ON DELETE SET NULLremoves them from theassigned_tofield without deleting the task itself. The task remains, but is temporarily unassigned.
#Many-to-Many Relationship: Project Members
A user can belong to multiple projects, and a project can have multiple users. This requires a linking table (also known as a junction or join table).
CREATE TABLE project_members (
project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role member_role NOT NULL DEFAULT 'member',
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (project_id, user_id)
);Implementation Details
- No Surrogate Key: We do not create a separate
idcolumn for this table. - Composite Primary Key:
PRIMARY KEY (project_id, user_id)combines two foreign keys to form a single, unique identifier for the row. This natively enforces that a specific user can only be added to a specific project once. Attempting to insert the same pair twice will result in a unique violation error. - Contextual Data: The
rolecolumn lives here because a user's role is specific to their membership in a particular project, not to the user globally. - Dual CASCADE: If either the project or the user is deleted, the membership record is automatically cleaned up.
#Down Migrations and Execution
Every up migration must have a corresponding down migration to allow for safe rollbacks. The down block must reverse the operations in the exact opposite order they were created to avoid dependency errors.
-- migrate:down
DROP TABLE IF EXISTS project_members;
DROP TABLE IF EXISTS tasks;
DROP TABLE IF EXISTS projects;
DROP TABLE IF EXISTS user_profiles;
DROP TABLE IF EXISTS users;
DROP TYPE IF EXISTS member_role;
DROP TYPE IF EXISTS task_status;
DROP TYPE IF EXISTS project_status;Applying the Schema
To apply the migrations to your database, run:
dbmate updbmate reads the db/migrations/ directory, checks the schema_migrations table in your database, and executes only the pending up blocks.
The schema_migrations table is automatically created and maintained by the tool. It contains a single version column that records the timestamp of the last successfully applied migration. This prevents the tool from attempting to run the same CREATE TABLE statements twice, which would result in a PostgreSQL error.
By structuring your schema with explicit constraints, composite keys, and version-controlled migrations, you build a foundation that is resilient to application bugs, easy for new engineers to understand, and safe to modify as your product evolves.
Seeding, Querying, and Optimizing PostgreSQL for Backend APIs
Building a database schema is only the first step. Once your tables are defined, you need to populate them with test data, write efficient queries for your API endpoints, and optimize performance for scale.
#Seeding: Inserting Test Data
In production, data enters your database through normal user flows like registration forms and API requests. But when you are developing and testing your backend, you need a way to populate your database with realistic test data. This process is called seeding.
Seeding involves writing scripts to insert mock data into your tables. The best practice is to create a separate migration file specifically for seeding, rather than mixing it with your schema definitions.
Generate a new migration file using your migration tool:
dbmate new seed_dataThis creates a new timestamped SQL file in your migrations directory. Because the timestamp is newer than your schema migrations, it will execute after the tables are created.
Using CTEs for Readable Seeds
When seeding relational data, you often need to insert a parent record and then use its generated ID to insert child records. You can achieve this cleanly using Common Table Expressions (CTEs).
WITH inserted_users AS (
INSERT INTO users (email, full_name, password_hash)
VALUES
('alice@example.com', 'Alice Brown', 'hash1'),
('bob@example.com', 'Bob Smith', 'hash2')
RETURNING id, email
)
INSERT INTO user_profiles (user_id, bio)
SELECT id,
CASE
WHEN email = 'alice@example.com' THEN 'Software engineer who loves open source.'
WHEN email = 'bob@example.com' THEN 'Product manager focusing on developer tools.'
ELSE 'Default bio text.'
END
FROM inserted_users;In this script, the WITH inserted_users AS block inserts rows into the users table and uses RETURNING to capture the newly generated IDs. The subsequent INSERT statement then uses those IDs to create corresponding records in the user_profiles table.
Apply the seed data by running your migration command:
dbmate upYour database now has realistic data to test your API endpoints.
#Writing Database Queries for APIs
With your schema and seed data in place, you can start writing the SQL queries that will power your backend APIs.
Get All Users: Joins and JSON Aggregation
Consider an endpoint that returns a list of all users. The frontend expects each user object to include their profile information. Since profiles are stored in a separate table, you need to join them in a single database 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;Let us break down the components of this query.
Table Aliases: We assign aliases u and up to the users and user_profiles tables. This keeps the query concise and makes it easier to reference columns when both tables share similar names.
LEFT JOIN vs INNER JOIN: We use a LEFT JOIN instead of an INNER JOIN. An INNER JOIN would only return users who have a corresponding profile record. If a user registered but never filled out their profile, they would be excluded from the results. A LEFT JOIN ensures all users are returned, with the profile data simply being null if it does not exist.
JSON Aggregation: The to_jsonb(up.*) function takes the entire matched row from the user_profiles table and converts it into a binary JSON object. We alias this as profile. This allows your backend to receive a single, neatly nested data structure without needing to manually map flat SQL rows into nested objects in your application code.
Default Sorting: Relational databases do not guarantee row order unless explicitly specified. We add ORDER BY u.created_at DESC to ensure the most recently created users appear first.
Get Single User: Parameterized Queries and Security
Now consider an endpoint to fetch a single user by their ID, such as GET /v1/users/:user_id.
To pass the dynamic user ID into your SQL query safely, you must use parameterized queries.
The Danger of String Concatenation
If you construct your SQL query by concatenating strings in your application code, you open the door to SQL injection.
// UNSAFE: Never do this
const query = "SELECT * FROM users WHERE email = '" + userEmail + "'";If a malicious user provides an email like '; DELETE FROM users; --, the database will execute the deletion command because it cannot distinguish between your intended SQL code and the user's input.
The Safety of Parameterized Queries
Parameterized queries separate the SQL structure from the data. You define placeholders in your query and pass the values separately.
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;When the database driver processes this, it sends the query structure and the parameters to the PostgreSQL server separately. The database treats the parameter strictly as a literal value, not as executable SQL code. Even if the input contains malicious SQL syntax, it is safely escaped and evaluated only as a string or number.
Always use parameterized queries for any dynamic input in your database operations.
Dynamic Filters, Sorting, and Pagination
List endpoints rarely return static data. They need to support filtering, sorting, and pagination based on query parameters sent by the frontend.
Filtering with ILIKE
Suppose the frontend wants to filter users by the first letter of their name. You can use the ILIKE operator for case-insensitive pattern matching.
WHERE u.full_name ILIKE $1 || '%'If the parameter $1 is 'A', the expression evaluates to 'A%'. The ILIKE operator then matches any name starting with 'A', regardless of case.
Dynamic Sorting
You want to allow the frontend to sort by different columns, such as email or full_name, in either ascending or descending order.
ORDER BY u.email ASCImportant Real-World Caveat: Standard database drivers do not allow you to parameterize column names or sort directions (e.g., ORDER BY $2 $3 will fail or sort by a literal string). In your actual backend code, you must construct the ORDER BY clause dynamically via string interpolation. To prevent SQL injection, you must validate the user's input against a strict whitelist of allowed column names and sort directions before injecting them into the query string.
Pagination with LIMIT and OFFSET
To prevent overwhelming the database and the frontend, list APIs must be paginated.
LIMIT $2 OFFSET $3;The LIMIT clause restricts the number of rows returned. The OFFSET clause skips a specified number of rows before starting to return data.
If the frontend requests page 2 with a limit of 10 items per page, your backend calculates the offset as (page - 1) * limit, which equals 10. The database will skip the first 10 rows and return the next 10.
Create User: INSERT with RETURNING
For a POST /api/users endpoint, you need to insert a new record and return the created data to the client.
INSERT INTO users (email, full_name, password_hash)
VALUES ($1, $2, $3)
RETURNING *;The RETURNING * clause is incredibly useful. It tells PostgreSQL to return the entire newly created row, including database-generated fields like the id, created_at, and updated_at timestamps. This eliminates the need for a secondary SELECT query to fetch the data you just inserted.
Update User: Partial Updates
For a PATCH endpoint, the frontend might only send the fields that need updating. If a user only updates their bio, you should not overwrite their phone number with null.
Your application code should inspect the request body and dynamically construct the SET clause. If the user sent both bio and phone_number, the resulting query looks like this:
UPDATE user_profiles
SET bio = $1, phone_number = $2
WHERE user_id = $3
RETURNING *;The WHERE user_id = $3 ensures you only update the specific user's profile. Again, RETURNING * provides the updated row so you can send it back to the frontend immediately.
#Automating Timestamps with Database Triggers
Every table includes an updated_at column to track when a record was last modified. When you run an UPDATE query, this field does not change automatically. You have two options to handle this.
Method 1: Manual Updates in Application Code
You can manually set the timestamp in every UPDATE query your application executes.
UPDATE users SET full_name = $1, updated_at = NOW() WHERE id = $2;The problem with this approach is human error. If a developer forgets to include updated_at = NOW() in a new query, the timestamp becomes stale.
Method 2: Database Triggers
A trigger is a function that automatically executes in response to certain events on a particular table. You can create a trigger to automatically update the updated_at column whenever a row is modified.
First, create the trigger function:
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;Next, attach the trigger to your tables:
CREATE TRIGGER update_users_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_projects_updated_at
BEFORE UPDATE ON projects
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();Now, whenever an UPDATE operation occurs on the users or projects table, PostgreSQL automatically sets the updated_at column to the current timestamp. This enforces the rule at the database level, ensuring consistency regardless of which application code or developer executes the query.
#Database Indexes: Optimizing Query Performance
As your database grows from hundreds to millions of rows, queries will start to slow down. This is where database indexes become critical.
What is an Index?
Without an index, PostgreSQL must perform a sequential scan. If you search for a user by email, the database reads every single row in the users table until it finds a match.
An index is a separate data structure, typically a B-Tree, that allows the database to find rows without scanning the entire table. It works exactly like an index in a book. Instead of reading every page to find a topic, you look at the index, find the page number, and jump directly to it.
Creating Indexes
You can create an index using a migration.
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_tasks_project_id ON tasks(project_id);The naming convention idx_tablename_columnname helps keep your database schema organized.
When to Use Indexes
Indexes drastically speed up SELECT queries, especially those involving WHERE clauses, JOIN conditions, and ORDER BY operations.
You should create indexes for:
- Primary Keys and Unique Constraints: PostgreSQL automatically creates unique indexes for these.
- Foreign Keys: Columns used in
JOINoperations, likeproject_idin thetaskstable, should almost always be indexed. - Frequently Queried Columns: If you constantly filter users by
emailor sort tasks bycreated_at, those columns need indexes.
The Trade-off
Indexes are not free. They consume additional disk space and slow down INSERT, UPDATE, and DELETE operations because the database must update the index structure every time the underlying data changes.
Do not index every column. Analyze your query patterns and add indexes only where they provide a measurable performance benefit. You can use PostgreSQL's EXPLAIN ANALYZE command to see if your queries are utilizing indexes or performing slow sequential scans.
By combining proper indexing, automated triggers, and secure parameterized queries, you build a database layer that is fast, reliable, and safe from common vulnerabilities.
Database Indexes, Triggers, and the Backend Engineering Workflow
You have your schema defined, your migrations running, and your seed data in place. Now it is time to optimize how the database retrieves that data and automate repetitive tasks.
#What Is Database Indexing?
To understand indexes, think about the index section at the back of a physical book. If you want to find Chapter 4 in a 500-page book, you do not flip through every single page sequentially. You look at the index, find that Chapter 4 starts on page 214, and jump directly to that page.
Database indexes work on the exact same principle.
The Problem: Sequential Scans
Relational databases store data on disk. The physical location of rows on the disk is not strictly sequential based on your insertion order.
When you run a query like SELECT * FROM tasks WHERE id = '123', the database needs to find that specific row. Without an index, the database performs a sequential scan. It starts at the first row on the disk, checks if the ID matches, moves to the next physical location, checks again, and repeats this process until it finds a match.
For a table with ten rows, this is instantaneous. For a table with ten million rows, a sequential scan will severely degrade your API response times.
The Solution: Index Lookups
An index is essentially a lookup table. When you create an index on a column, the database builds a separate, highly optimized data structure (usually a B-Tree) that maps the indexed values to their physical disk locations.
When the database receives a query for a specific ID, it searches the index first. The index provides the exact disk location of the row, allowing the database to fetch the data in a single jump, completely bypassing the sequential scan.
#Index Ordering
Indexes are not just about finding data faster; they are also about retrieving data in a specific order.
An index can be built in ascending or descending order. If your API defaults to returning a list of users sorted by created_at in descending order (newest first), you should create the index in descending order.
CREATE INDEX idx_users_created_at_desc ON users(created_at DESC);If the index is already sorted in descending order, the database can simply read the index from start to finish and return the rows immediately. If the index were in ascending order, the database would have to fetch all the rows and then perform an expensive, memory-intensive sort operation before returning the results. Matching your index order to your most common ORDER BY clauses eliminates this sorting overhead.
#When to Create Indexes
You should not blindly add indexes to every column. The rule of thumb for creating an index is to look at your query patterns. Create an index on a column if it is frequently involved in:
WHEREclauses: Filtering data (e.g.,WHERE status = 'pending').JOINconditions: Linking tables together (e.g.,ON tasks.project_id = projects.id).ORDER BYclauses: Sorting results (e.g.,ORDER BY created_at DESC).
If a column is only used for displaying data and never for filtering, sorting, or joining, it does not need an index.
#Creating Indexes in Migrations
Let us apply this logic to our project management schema. We will create a new migration file specifically for indexes.
Index on users.email
CREATE INDEX idx_users_email ON users(email);Reasoning: We have APIs that authenticate users by email, and we might have join conditions that match users by email. Indexing this column makes lookups and joins instantaneous.
Index on users.created_at DESC
CREATE INDEX idx_users_created_at_desc ON users(created_at DESC);Reasoning: Our "get all users" API defaults to sorting by creation date, newest first. This index allows the database to return paginated results without performing an in-memory sort.
Index on tasks.project_id
CREATE INDEX idx_tasks_project_id ON tasks(project_id);Reasoning: This is a foreign key. When we fetch all tasks for a specific project, we join the projects table with the tasks table on this column.
Note: PostgreSQL automatically creates a unique index for Primary Keys. Because projects.id is a primary key, it is already indexed. However, foreign keys like tasks.project_id are not indexed automatically. You must index them manually to speed up joins.
Index on tasks.assigned_to
CREATE INDEX idx_tasks_assigned_to ON tasks(assigned_to);Reasoning: Another foreign key. When we fetch all tasks assigned to a specific user, we join the users table with the tasks table on this column.
Index on tasks.created_at DESC
CREATE INDEX idx_tasks_created_at_desc ON tasks(created_at DESC);Reasoning: Similar to the users table, our "get all tasks" API sorts by creation date descending. This index optimizes that default sort.
Index on tasks.status
CREATE INDEX idx_tasks_status ON tasks(status);Reasoning: The status column is a custom ENUM type. Our API allows clients to filter tasks by status (e.g., WHERE status = 'pending'). Indexing this column speeds up these WHERE clause filters.
Indexes on project_members
CREATE INDEX idx_project_members_project_id ON project_members(project_id);
CREATE INDEX idx_project_members_user_id ON project_members(user_id);Reasoning: project_members is a linking table for a many-to-many relationship. We frequently join this table with projects (using project_id) and with users (using user_id). Both foreign keys need indexes to keep these joins fast.
#Index Performance Trade-offs
Indexes are not free. They introduce a trade-off between read performance and write performance.
When you create an index, the database allocates disk space to store the lookup structure. More importantly, every time you execute an INSERT, UPDATE, or DELETE operation, the database must also update the index to keep it in sync with the actual data.
If you have a table with twenty indexes, a single INSERT operation requires the database to update the table data and then update all twenty index structures. This adds overhead to write operations.
How to Decide
As a backend engineer, you must evaluate if the read performance gain outweighs the write overhead.
- Analyze query frequency: If a query is executed thousands of times a day, the index is worth it. If it is executed once a month, it is not.
- Monitor write volume: If a table is heavily written to (e.g., a high-frequency logging table), adding too many indexes will bottleneck your inserts.
- Iterate: Start by indexing columns used in
WHERE,JOIN, andORDER BYclauses for your core API endpoints. If you later notice write performance degrading, you can drop the indexes on less frequently queried columns.
#Automating Timestamps with Triggers
Every table in our schema includes an updated_at column. The requirement is simple: every time a row is modified, this column must be updated to the current timestamp.
You could handle this in your application code by explicitly setting updated_at = NOW() in every UPDATE query. The problem is human error. Eventually, a developer will write an update query, forget to include the timestamp logic, and the updated_at field will become stale.
We can enforce this rule at the database level using a trigger.
Creating the Trigger Function
First, we create a custom Postgres function that defines the action we want to take.
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;This function intercepts the row being modified (represented by NEW), updates its updated_at field to the current timestamp, and returns the modified row so the database can proceed with the actual update.
Attaching Triggers to Tables
Next, we attach this function to the tables that need it. We use the BEFORE UPDATE event so the timestamp is modified before the row is written to the disk.
CREATE TRIGGER update_users_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_user_profiles_updated_at
BEFORE UPDATE ON user_profiles
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_projects_updated_at
BEFORE UPDATE ON projects
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_tasks_updated_at
BEFORE UPDATE ON tasks
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();Now, whenever an UPDATE statement is executed on any of these tables, the trigger fires automatically. Your application code no longer needs to worry about setting the timestamp.
Down Migrations
Migrations must be reversible. In our down migration, we must drop the triggers, the function, and the indexes we created, in the correct order to avoid dependency errors.
-- Drop triggers
DROP TRIGGER IF EXISTS update_users_updated_at ON users;
DROP TRIGGER IF EXISTS update_user_profiles_updated_at ON user_profiles;
DROP TRIGGER IF EXISTS update_projects_updated_at ON projects;
DROP TRIGGER IF EXISTS update_tasks_updated_at ON tasks;
-- Drop function
DROP FUNCTION IF EXISTS update_updated_at_column();
-- Drop indexes
DROP INDEX IF EXISTS idx_users_email;
DROP INDEX IF EXISTS idx_users_created_at_desc;
DROP INDEX IF EXISTS idx_tasks_project_id;
DROP INDEX IF EXISTS idx_tasks_assigned_to;
DROP INDEX IF EXISTS idx_tasks_created_at_desc;
DROP INDEX IF EXISTS idx_tasks_status;
DROP INDEX IF EXISTS idx_project_members_project_id;
DROP INDEX IF EXISTS idx_project_members_user_id;Run dbmate up to apply these optimizations. If you run an UPDATE query on the users table now, you will see the updated_at column change to the exact second the query executed, completely automated.
#The Backend Engineering Workflow
We have now covered the entire lifecycle of database interaction in a backend system. While there are advanced topics like partitioning, replication, and complex window functions, the day-to-day work of a backend engineer revolves around a specific workflow.
When you are assigned a new API endpoint, your database workflow will look like this:
- Analyze the API Payload: Look at the request. What data is the client sending? What dynamic filters, sorting options, or pagination parameters are included in the query string?
- Construct the Dynamic Query: Based on the payload, build the SQL query. If the client provided a filter, add the
WHEREclause. If they requested a specific sort order, add theORDER BYclause. If it is a list endpoint, calculate and append theLIMITandOFFSETfor pagination. - Parameterize the Query: Never concatenate user input directly into the SQL string. Use parameterized queries (placeholders like
$1,$2) to pass dynamic values safely. This separates the code from the data and prevents SQL injection. - Execute and Return: Run the query against the database using your language's database driver. Take the resulting rows, serialize them into the expected JSON format, and return them to the client with the appropriate HTTP status code.
This cycle—analyzing requirements, constructing secure dynamic queries, and mapping database rows to API responses—makes up roughly 80% of the database work you will do as a backend engineer. Mastering indexes, triggers, and parameterized queries ensures that the remaining 20% of your work is built on a foundation that is fast, reliable, and secure.