Introduction to PostgreSQL
Table of Contents
Why PostgreSQL Matters for Backend Development
PostgreSQL, often called “Postgres,” is a powerful open source relational database management system (RDBMS). As a backend developer, you will frequently need a reliable database to store and query application data. PostgreSQL is one of the most popular choices for modern web backends.
It is:
- Free and open source, with a large community
- Cross platform, runs on Linux, macOS, and Windows
- Very standards compliant, follows SQL standards closely
- Trusted in production by many companies for critical systems
PostgreSQL is not the only database you can use, but it is an excellent one to learn first because it gives you strong foundations for relational databases in general.
Key idea: PostgreSQL is a relational database that uses SQL to define, store, and query data in tables.
Learning PostgreSQL teaches you practical SQL plus concepts that apply to many other relational databases.
In this chapter, you will get an overview of what makes PostgreSQL special, what you can do with it, and how you will use it in backend projects. Installation, SQL, performance tuning, and so on will be handled in later chapters, so here we focus on the big picture.
PostgreSQL in the Database Landscape
There are many relational databases: MySQL, MariaDB, SQL Server, Oracle, SQLite, and others. PostgreSQL belongs to this family but has its own philosophy.
PostgreSQL vs other relational databases
Here is a rough comparison to build intuition.
| Database | License | Typical use cases | Strengths |
|---|---|---|---|
| PostgreSQL | Open source | Web apps, analytics, geospatial, microservices | Features, correctness, extensibility |
| MySQL | Open source | Web apps, LAMP stack, legacy apps | Simplicity, huge ecosystem |
| SQLite | Public domain | Mobile, embedded, small tools | Zero config, single file, very lightweight |
| Oracle | Commercial | Large enterprises, legacy systems | Enterprise tools, long history |
| SQL Server | Commercial/Free | Windows shops, .NET apps | Integration with Microsoft stack |
PostgreSQL focuses strongly on:
- Correctness and reliability
- Rich SQL features
- Extensibility (you can add data types, functions, and more)
This makes it a solid default for many backend applications, from small projects to large systems.
PostgreSQL vs NoSQL databases
You will also encounter NoSQL systems like MongoDB, Cassandra, and Redis. These are often:
- Document databases (for example MongoDB)
- Key value stores (for example Redis)
- Wide column stores (for example Cassandra)
- Graph databases
PostgreSQL is different because:
- It enforces schemas and constraints
- It uses SQL for queries
- It provides transactions with strong ACID guarantees
However, PostgreSQL has evolved and now includes features that feel “NoSQL like”, such as JSONB columns, key value style operations, and full text search. In many cases, you can keep using PostgreSQL instead of adding a second specialized database.
Core Concepts in PostgreSQL
Before using PostgreSQL in code, you need a conceptual map of its main building blocks.
Cluster, databases, schemas, and tables
PostgreSQL has a hierarchy of objects. This often confuses beginners, so keep this structure in mind:
| Level | Example name | Description |
|---|---|---|
| Cluster | One Postgres “server” process | Contains one or more databases |
| Database | my_app_db | Contains schemas, tables, functions, etc. |
| Schema | public | A namespace inside a database |
| Table | users | Stores rows of data with defined columns |
In practice for simple apps:
- You have one PostgreSQL server (cluster).
- Inside it, you create one database for your app.
- Inside that database, you use the default
publicschema. - Inside that schema, you create your tables (
users,orders,products, etc.).
Example mental model for a simple app:
- Cluster:
postgres@localhost - Database:
task_manager - Schema:
public - Table:
users - Table:
tasks
You will learn how to actually create these in later PostgreSQL chapters.
Data types and constraints
PostgreSQL has many data types, more than many other relational databases. Some common ones you will use often:
| Category | Examples |
|---|---|
| Numeric | INTEGER, BIGINT, NUMERIC, REAL |
| Text | TEXT, VARCHAR(n), CHAR(n) |
| Boolean | BOOLEAN |
| Date/Time | DATE, TIME, TIMESTAMP, TIMESTAMPTZ |
| Binary | BYTEA |
| JSON | JSON, JSONB |
| UUID | UUID |
You also use constraints to enforce rules:
NOT NULLvalue must be presentUNIQUEvalue must be unique in the tablePRIMARY KEYunique identifier for a rowFOREIGN KEYreference to another tableCHECKcustom conditions, for exampleage >= 0
These make your data safer and help prevent bugs in your backend code by catching invalid data early.
Example of a table definition (simplified, you will learn syntax later):
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
full_name TEXT NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);Even if you do not know all the syntax yet, you can see:
idis the primary keyemailcannot be null and must be uniqueis_activehas a default valueTRUE
Typical PostgreSQL Use Cases in Backends
PostgreSQL supports many patterns you will see repeatedly when writing backend services.
Storing core application data
Most web apps need to store:
- Users
- Authentication data
- Domain objects, for example products, tasks, posts, orders
- Relations between these objects
PostgreSQL models this with tables and relationships.
Example: a task management app:
users
id (PK)
email
password_hash
tasks
id (PK)
user_id (FK to users.id)
title
description
is_completed
created_atYou can then answer questions such as:
- “Find all tasks for user with email
alice@example.com” - “Count completed tasks for each user”
All with SQL queries, which we cover in the SQL section of the course.
Transactions and consistency
In real applications, you frequently need several related changes to happen atomically. For example in an ecommerce app:
- Create an order
- Reduce product inventory
- Save a payment record
You want either all of these steps to succeed or none of them. PostgreSQL gives you:
- Transactions: groups of operations that are either fully committed or fully rolled back
- ACID guarantees: important properties that ensure reliability
You will have a separate chapter focused on transactions and ACID, but for now you should understand:
In PostgreSQL you can wrap multiple database operations in a transaction so they behave as a single, all-or-nothing unit of work.
This is essential for correct backend logic.
Advanced querying and analytics
PostgreSQL supports powerful SQL features such as:
- Joins to combine data from multiple tables
- Aggregations with
GROUP BYand functions likeCOUNT,SUM,AVG - Window functions for advanced calculations
- Common Table Expressions (CTEs) for readable complex queries
- Views to encapsulate frequently used queries
Even simple apps benefit from this. For example:
- “How many tasks did each user complete in the last 7 days?”
- “Show the 10 most recent orders with the total amount and user name.”
As you build more complex backends, these features become very valuable.
How Backend Code Talks to PostgreSQL
Your backend application does not talk SQL manually in a terminal in production. Instead, it connects to PostgreSQL over the network and runs queries through a driver or an ORM.
Client server model
PostgreSQL runs as a server process that listens on a port, typically 5432. Your backend application is a client:
- Your code opens a connection to PostgreSQL
- It sends SQL commands as text
- PostgreSQL executes them
- Results come back to your code
Example conceptual flow for a FastAPI endpoint:
- HTTP request:
GET /users/1 - FastAPI handler runs
- Handler uses SQLAlchemy (ORM)
- SQLAlchemy generates SQL like
SELECT * FROM users WHERE id = 1 - PostgreSQL executes the query and returns the row
- Handler serializes the result to JSON and returns an HTTP response
You will learn the details of ORMs and integration in later chapters, but this is the basic idea.
Connection parameters
To connect to PostgreSQL, you usually need:
| Parameter | Example |
|---|---|
| Host | localhost |
| Port | 5432 |
| Database | my_app_db |
| User | my_app_user |
| Password | secret_password |
These are often combined into a connection URL, for example:
postgresql://my_app_user:secret_password@localhost:5432/my_app_dbYour backend will use environment variables to store these values, for example:
DATABASE_URL=postgresql://my_app_user:secret_password@localhost:5432/my_app_db
Then your Python code reads DATABASE_URL and uses it to connect.
Strengths and Features that Matter to Backend Developers
PostgreSQL has many advanced features. You will not use all of them on day one, but it is useful to know what is available so you can pick the right tools later.
Rich data types for real world data
Some PostgreSQL data types are especially useful in backends:
- JSON and JSONB
- Store flexible JSON documents
- Query inside JSON fields, for example
preferences->>'theme' - Great for semi structured data like settings, logs, or integrations
- UUID
- Random unique identifiers like
550e8400-e29b-41d4-a716-446655440000 - Useful for public IDs in APIs, as they are hard to guess and do not expose table size
- Arrays
- Columns that hold arrays, for example
tags TEXT[] - Useful when you need a small list of values without a separate table
- Geospatial (PostGIS extension)
- Store locations, shapes, routes
- Important for maps, delivery apps, etc.
You will learn details of data types in the “PostgreSQL Data Types” chapter.
Indexes for performance
When tables grow large, queries can become slow. PostgreSQL uses indexes to speed up lookups, just like an index in a book.
Common example:
- Table
usershas 1 million rows - You often look up users by
email - You create an index on
email - PostgreSQL can now find a user by email much faster
We will cover indexes in both the SQL section and the PostgreSQL section, including how they work and when to use them.
Extensions and customization
PostgreSQL is very extensible. You can add:
- New data types
- New functions
- Procedural languages (PL/pgSQL, PL/Python, etc.)
- Full text search with advanced ranking
- Geospatial support via PostGIS
For most basic backends you will use the built in features only, but knowing that PostgreSQL can grow with your needs is important.
Example: Simple Application Data Model in PostgreSQL
To see PostgreSQL concepts in context, imagine a simple blog backend with:
- Users
- Posts
- Comments
A possible schema in PostgreSQL might look like this (simplified):
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
title TEXT NOT NULL,
content TEXT NOT NULL,
published_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE comments (
id SERIAL PRIMARY KEY,
post_id INTEGER NOT NULL REFERENCES posts(id),
user_id INTEGER NOT NULL REFERENCES users(id),
content TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);Concepts in this example:
- Each table has a primary key
id posts.user_idandcomments.user_idreferenceusers.idcomments.post_idreferencesposts.id- Timestamps use
TIMESTAMPTZ, a timezone aware type
From your backend code, you could:
- Insert a new user when someone registers
- Insert a post linked to that user
- Insert comments linked to both the post and the commenting user
- Query posts with their authors and comment counts
You will later represent these tables as Python classes when using an ORM like SQLAlchemy.
How You Will Use PostgreSQL in This Course
Throughout this course, PostgreSQL appears in several roles:
- Learning SQL
- You will run
CREATE,INSERT,SELECT,UPDATE, andDELETEstatements against PostgreSQL. - You will practice joins, aggregates, indexes, and transactions.
- Integrating with FastAPI
- You will connect FastAPI applications to PostgreSQL using SQLAlchemy.
- You will build REST APIs that read and write data in PostgreSQL.
- Using PostgreSQL in Docker
- You will run PostgreSQL in containers for local development.
- You will use
docker-composeto run FastAPI and PostgreSQL together. - Deploying to production
- You will configure PostgreSQL on a Linux server or use a managed PostgreSQL service.
- You will manage migrations, backups, and performance basics.
By the end of the PostgreSQL and ORM sections, you will be comfortable:
- Designing schemas for typical web applications
- Writing and optimizing common queries
- Integrating PostgreSQL into real backend services
Summary
In this chapter you learned the big picture of PostgreSQL:
- It is a powerful, open source relational database system, widely used in modern backends.
- It organizes data in databases, schemas, and tables, with rich data types and constraints.
- It supports transactions and ACID properties for reliable multi step operations.
- Backend applications talk to PostgreSQL over the network using drivers or ORMs.
- PostgreSQL offers advanced features like JSONB, indexes, full text search, and extensions.
Next, you will learn how to install PostgreSQL, connect to it, and start creating databases and tables that you can use from your backend code.
Views: 7
KAHIBARO