Introduction to PostgreSQL

By

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.

Postgres EXPLAIN visualizerInteractive · runs in your browser

Input

Nodes · · planning ms · execution ms · ANALYZE timings present

Hotspots

NodeScoreCostRows

Plan tree

Node detail

Why use PostgreSQL?

PostgreSQL is a general-purpose database suited to applications that need reliable transactions and structured data.

Its core features include:

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:

readsreadsTx 100INSERT rowTuple v1xmin=100 xmax=105Tx 105UPDATE rowTuple v2xmin=105 xmax=0Reader (Tx 102)snapshot < 105Reader (Tx 106)snapshot > 105VACUUMreclaims dead tuple

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:

Cluster: one serverprocess, one datadirectory, port 5432Roles: shared byevery databaseDatabase: appDatabase: postgresSchema: publicSchema: statsTables: posts, tags,post_tagsTable:posts_per_year

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:

CommandWhat it does
\lList all databases
\c appSwitch to database app
\dtList tables in the current schema
\d postsDescribe columns, types, constraints, and indexes on posts
\duList roles and their permissions
\timingToggle query execution time on or off
\qQuit 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:

Requestpg.Pool, max 10RequestRequestRequest, waitsConnection 1Connection 2Connection 3PostgreSQL: oneprocess perconnection,max_connections =100

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

Build or parse a database connection string

Assemble or inspect PostgreSQL, MySQL, and SQLite connection URLs locally in your browser:

Connection string builderInteractive · runs in your browser

Presets

Connection fields

Built connection string

Parses standard URI formats (postgres://, mysql://, sqlite:). Some ORM drivers use keyword=value strings — convert those manually or paste the URI form your host provides.

Want me to talk about your product? You can sponsor this site.

Related posts about database: