Introduction to PostgreSQL
By Flavio
Published · Updated
Tagged: Database
Learn PostgreSQL from basics to production: psql commands, roles and least privilege, constraints, transactions, EXPLAIN ANALYZE indexing, connection pools, and pg_dump backups.
PostgreSQL, often called Postgres, is an open source object-relational database management system.
It stores related data in tables and uses SQL for defining, querying, and changing that data. It also extends the SQL model with rich data types, functions, indexes, and an extension system.
PostgreSQL can be used, modified, and distributed for private, commercial, or academic purposes under its permissive license.
Postgres EXPLAIN Visualizer
Turn EXPLAIN FORMAT JSON into a readable query-plan tree with cost and timing hotspots.
Why use PostgreSQL?
PostgreSQL is a general-purpose database suited to applications that need reliable transactions and structured data.
Its core features include:
- transactions with atomic commit and rollback
- foreign keys and constraints
- joins, subqueries, common table expressions, and window functions
- multiversion concurrency control
- views, triggers, and stored functions
- indexes for common and specialized query patterns
- JSON and JSONB alongside relational columns
- full-text search
- user-defined types, functions, operators, and extensions
The official What is PostgreSQL? page summarizes the project’s capabilities.
PostgreSQL is a server
PostgreSQL runs as a database server process.
Applications connect to it over a local socket or network connection, authenticate as a database role, select a database, and send SQL statements.
A connection URL commonly looks like:
postgresql://username:password@localhost:5432/app
Do not commit real database passwords. Store them in environment variables or a secret manager, use TLS for untrusted networks, and grant each application only the permissions it needs.
SQL and PostgreSQL
SQL is the language. PostgreSQL is one database system that implements a large part of the SQL standard and adds PostgreSQL-specific features.
Create a table:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
published_at timestamptz
);
Insert a row and return its generated ID:
INSERT INTO posts (title)
VALUES ('Hello PostgreSQL')
RETURNING id;
Query published posts:
SELECT id, title, published_at
FROM posts
WHERE published_at IS NOT NULL
ORDER BY published_at DESC;
PostgreSQL’s current manual is organized by concepts, SQL commands, administration, client tools, and reference material.
Transactions and concurrency
A transaction groups statements into one unit:
BEGIN;
UPDATE accounts
SET balance = balance - 50
WHERE id = 1;
UPDATE accounts
SET balance = balance + 50
WHERE id = 2;
COMMIT;
If a statement fails or the operation should not continue, use ROLLBACK.
PostgreSQL uses multiversion concurrency control so readers and writers can often work concurrently without blocking each other unnecessarily. An UPDATE writes a new tuple version instead of overwriting the row in place, and VACUUM later reclaims dead tuples:
Transaction isolation still matters: choose it according to the consistency rules of the application.
Schemas are namespaces
One PostgreSQL cluster can hold multiple databases, and each database can contain multiple schemas:
The default schema is usually public. A qualified table name includes the schema:
SELECT *
FROM public.posts;
Do not confuse a PostgreSQL schema namespace with an ORM schema file. They are related concepts but not the same thing.
Extensions
Extensions package additional database objects and behavior.
For example, a supported installation can enable an extension with:
CREATE EXTENSION extension_name;
Available extensions depend on the PostgreSQL installation or managed provider. Enabling one changes the database and may affect portability, upgrades, and backups, so review its documentation first.
Version support
PostgreSQL releases a new major version about once a year and supports each major version for five years.
Run a supported major version and keep it on its current minor release for bug and security fixes. Minor upgrades are designed differently from major upgrades; major upgrades require an upgrade procedure such as pg_upgrade or dump and restore.
Check the live PostgreSQL versioning policy instead of copying a version number from an old tutorial.
Essential psql commands
When I connect with psql "$DATABASE_URL", these meta-commands cover 90% of daily inspection:
| Command | What it does |
|---|---|
\l | List all databases |
\c app | Switch to database app |
\dt | List tables in the current schema |
\d posts | Describe columns, types, constraints, and indexes on posts |
\du | List roles and their permissions |
\timing | Toggle query execution time on or off |
\q | Quit psql |
Roles and least privilege
Keep superuser roles for administration and migrations. Give your running web app its own login role with only the access it needs:
CREATE ROLE app_user LOGIN PASSWORD 'strong-random-password';
GRANT CONNECT ON DATABASE app TO app_user;
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
Always connect your application through a bounded connection pool (such as pg.Pool with max: 10 in Node.js) instead of opening a fresh PostgreSQL process per HTTP request:
Measure queries with EXPLAIN ANALYZE
Never add indexes blindly. Run EXPLAIN (ANALYZE, BUFFERS) on your real query so PostgreSQL executes it and reports actual row counts and buffer hits:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, title
FROM posts
WHERE author_id = 42 AND published_at IS NOT NULL
ORDER BY published_at DESC
LIMIT 20;
If you see Seq Scan on a large table, create a targeted composite or partial index:
CREATE INDEX CONCURRENTLY idx_posts_author_published
ON posts (author_id, published_at DESC)
WHERE published_at IS NOT NULL;
CONCURRENTLY builds the index without blocking writes on a live table.
Back up and restore with pg_dump
Use PostgreSQL’s custom format (-Fc) so backups stay compressed and support selective restores with pg_restore:
pg_dump -Fc --no-owner --no-acl "$DATABASE_URL" > app.dump
createdb app_restore_test
pg_restore -d app_restore_test --no-owner --no-acl app.dump
Run a test restore into a throwaway database before trusting any backup script in production.
Continue learning
- How to install PostgreSQL
- PostgreSQL user permissions
- How to list all users in PostgreSQL
- How to list all databases using PostgreSQL
- How to switch databases using PostgreSQL
- How to create a PostgreSQL database
- Introduction to SQL
Build or parse a database connection string
Assemble or inspect PostgreSQL, MySQL, and SQLite connection URLs locally in your browser:
Want me to talk about your product? You can sponsor this site.
Related posts about database: