Getting Started
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
PostgreSQL is an open-source object-relational database management system. It stores data in tables of typed
rows, speaks SQL (with a large and well-documented conformance to the standard), and adds its own extensions on
top: arrays, ranges, enums, jsonb, full-text search, user-defined types and operators, and a rich extension
mechanism. It is ACID by default, uses multiversion concurrency control so readers never block writers, and is
developed by a community project rather than by a single vendor. This page explains where it fits, runs a real
server in a container, introduces psql, loads the shop dataset that the rest of this section reuses, and walks
through a first session.
Everything shown here was executed against PostgreSQL 18.6 (the postgres:latest Docker image on an arm64
host). Output is real; long results are trimmed and say so.
What PostgreSQL is and where it fits
PostgreSQL is a general-purpose relational database. Typical roles are the primary store of an operational
application, a system of record for analytics-style queries over moderate volumes, a geospatial store (with the
PostGIS extension), a document store (through jsonb) and, with pgvector, a vector store. The trade-offs that
follow from its design:
-
Strong SQL and strong consistency. Transactional DDL, constraints, deferrable foreign keys and serializable isolation are first-class. See Transactions, Isolation & MVCC.
-
Extensibility. New data types, index methods, procedural languages and whole feature sets ship as extensions. See Extensions.
-
Process-per-connection model. Each client connection is a separate operating-system process, so a pooler is normal in front of busy applications. See Architecture.
-
Single-primary write scaling. Writes go to one primary; read scaling and availability come from replicas. See Replication & High Availability.
For the engine-agnostic SQL language itself (DDL, queries, joins, window functions) see the sibling SQL Reference; for choosing between engines see Choosing the Right Database.
Editions and distribution
There is exactly one PostgreSQL: the open-source server released under the permissive PostgreSQL License by the PostgreSQL Global Development Group. There is no "community versus enterprise" split in the core server. What varies is how it is packaged and operated:
-
Official source and packages. Source tarballs, the PGDG apt and yum repositories, and the interactive installers listed on the download page.
-
Docker images. The official
postgresimage, used on this page. -
Vendor distributions and forks. Commercial distributions and hosted services (managed cloud offerings, vendor builds with extra tooling) package the same core, sometimes with additions. They are outside the scope of this section.
The project releases one major version per year, supports each for five years, and publishes quarterly minor
releases containing only bug and security fixes. Since version 10 a version number is major.minor (for
example 18.6); upgrading between minors is a binary swap and restart, while a major upgrade needs pg_upgrade
or a dump and restore. The authoritative policy is the
versioning policy.
Running PostgreSQL in Docker
The official image initialises a new cluster on first start. Only POSTGRES_PASSWORD is mandatory:
docker run -d --name pg --restart unless-stopped \
-e POSTGRES_PASSWORD=secret \
-p 5432:5432 \
-v pgdata:/var/lib/postgresql \
postgres:latest
|
From PostgreSQL 18 the image keeps the cluster in a version-specific directory, |
Wait until the server accepts connections, then ask it who it is:
docker exec pg pg_isready -U postgres
docker exec pg psql -U postgres -c "SELECT version()"
/var/run/postgresql:5432 - accepting connections
version
--------------------------------------------------------------------------------------------------------------------------
PostgreSQL 18.6 (Debian 18.6-1.pgdg13+2) on aarch64-unknown-linux-gnu, compiled by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
(1 row)
Useful environment variables of the image: POSTGRES_USER (default postgres), POSTGRES_DB (default equal to
the user), POSTGRES_INITDB_ARGS (for example --data-checksums, which is already the default from 18) and any
*.sql or *.sh file mounted under /docker-entrypoint-initdb.d/, which runs once when the cluster is created.
The official postgres image, like any container, is covered in Docker.
psql basics
psql is the interactive terminal client shipped with the server. In the container it is already installed, so
the examples use docker exec -it pg psql -U postgres; on a workstation the same flags apply
(psql -h localhost -p 5432 -U postgres).
docker exec -it pg psql -U postgres # interactive session
docker exec pg psql -U postgres -c "SELECT 1" # one statement, then exit
docker exec -i pg psql -U postgres < file.sql # run a script from the host
Two kinds of input exist: SQL statements, terminated by a semicolon, and backslash meta-commands, which
psql itself interprets and which need no semicolon. The ones used most often:
| Command | Purpose |
|---|---|
|
Help on meta-commands / on the syntax of an SQL command. |
|
Show the current connection (database, user, socket or host, backend PID). |
|
List databases / connect to another database. |
|
List schemas, list tables, describe a table (columns, indexes, constraints, references). |
|
Toggle expanded (one field per line) output; |
|
Print the elapsed time of each statement. |
|
Run a script file; client-side |
|
Quit. |
The meta-commands for data work (\copy, \gset,
\gexec, \watch) are covered in Data Types & PostgreSQL-specific SQL.
Connecting
A client connects to a database as a role over a Unix socket or TCP. The same information can be given as
discrete flags, environment variables (PGHOST, PGPORT, PGUSER, PGDATABASE, PGPASSWORD) or a connection
URI:
postgresql://postgres:secret@localhost:5432/postgres?sslmode=prefer&application_name=reporting
The sslmode, connect_timeout and application_name parameters are the ones you meet first;
application_name is visible in pg_stat_activity, which makes it worth setting from every application.
Inside the container the default pg_hba.conf trusts local socket and loopback connections, which is why the
docker exec commands above need no password; connections over TCP from the host (any other address) use
scram-sha-256 and therefore the password. Who may connect, and how,
is the subject of Administration.
Common connection problems: connection refused (server down, wrong port, or listen_addresses not including
the interface), no pg_hba.conf entry (the host, database, user and method are not allowed), password
authentication failed, and too many clients already (the max_connections limit, 100 by default, is
reached).
Loading the shop seed
The rest of this section reuses a small online shop: customers, products, orders and order_items, in a
schema named shop (4 customers, 5 products, 8 orders and 11 order lines). The same data set backs the
MongoDB Reference. Save the following script as seed.sql.
-- seed.sql -- the relational "shop" running example (PostgreSQL)
DROP SCHEMA IF EXISTS shop CASCADE;
CREATE SCHEMA shop;
SET search_path = shop;
CREATE TABLE customers (
id text PRIMARY KEY,
name text NOT NULL,
email text NOT NULL UNIQUE,
city text NOT NULL,
tier text NOT NULL CHECK (tier IN ('free', 'pro', 'enterprise')),
created_at timestamptz NOT NULL
);
CREATE TABLE products (
sku text PRIMARY KEY,
name text NOT NULL,
category text NOT NULL,
price numeric(10,2) NOT NULL CHECK (price >= 0),
stock integer NOT NULL CHECK (stock >= 0),
tags text[] NOT NULL DEFAULT '{}',
attrs jsonb NOT NULL DEFAULT '{}'
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id text NOT NULL REFERENCES customers(id),
status text NOT NULL CHECK (status IN ('open', 'shipped', 'cancelled')),
order_date timestamptz NOT NULL
);
CREATE TABLE order_items (
order_id integer NOT NULL REFERENCES orders(id),
sku text NOT NULL REFERENCES products(sku),
qty integer NOT NULL CHECK (qty > 0),
price numeric(10,2) NOT NULL,
PRIMARY KEY (order_id, sku)
);
INSERT INTO customers VALUES
('c-1', 'Ada Lovelace', 'ada@example.com', 'London', 'pro', '2025-01-10 09:00:00+00'),
('c-2', 'Alan Turing', 'alan@example.com', 'Wilmslow', 'free', '2025-02-14 10:30:00+00'),
('c-3', 'Grace Hopper', 'grace@example.com', 'New York', 'enterprise', '2025-03-01 08:15:00+00'),
('c-4', 'Linus Torvalds', 'linus@example.com', 'Helsinki', 'free', '2025-04-20 12:00:00+00');
INSERT INTO products VALUES
('A-1', 'Standing Desk', 'furniture', 349.00, 12, '{office,ergonomic}', '{"color": "oak", "width_cm": 160, "adjustable": true}'),
('A-2', 'Office Chair', 'furniture', 189.50, 30, '{office,ergonomic,sale}', '{"color": "black", "mesh": true}'),
('B-7', 'Desk Lamp', 'lighting', 24.99, 150, '{office,led}', '{"color": "white", "watts": 9}'),
('C-3', 'USB-C Hub', 'electronics', 39.00, 80, '{usb,sale}', '{"ports": 7, "pd_watts": 100}'),
('C-9', 'Monitor 27in', 'electronics', 279.00, 25, '{display,office}', '{"diagonal_in": 27, "panel": "IPS", "hdr": false}');
INSERT INTO orders VALUES
(1001, 'c-1', 'shipped', '2026-01-05 10:00:00+00'),
(1002, 'c-1', 'open', '2026-02-11 15:20:00+00'),
(1003, 'c-2', 'shipped', '2026-02-12 09:05:00+00'),
(1004, 'c-3', 'shipped', '2026-02-20 18:45:00+00'),
(1005, 'c-3', 'cancelled', '2026-03-02 11:11:00+00'),
(1006, 'c-4', 'open', '2026-03-15 14:00:00+00'),
(1007, 'c-1', 'shipped', '2026-03-18 08:30:00+00'),
(1008, 'c-2', 'open', '2026-03-25 19:00:00+00');
INSERT INTO order_items VALUES
(1001, 'A-1', 1, 349.00), (1001, 'B-7', 2, 24.99),
(1002, 'C-9', 1, 279.00),
(1003, 'C-3', 3, 39.00),
(1004, 'A-2', 4, 189.50), (1004, 'A-1', 2, 349.00),
(1005, 'C-9', 2, 279.00),
(1006, 'B-7', 1, 24.99), (1006, 'C-3', 1, 39.00),
(1007, 'A-2', 1, 189.50),
(1008, 'B-7', 5, 24.99);
Load it with psql, stopping at the first error:
docker exec -i pg psql -U postgres -v ON_ERROR_STOP=1 < seed.sql
DROP SCHEMA
NOTICE: schema "shop" does not exist, skipping
CREATE SCHEMA
SET
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 4
INSERT 0 5
INSERT 0 8
INSERT 0 11
The NOTICE appears on a fresh cluster because DROP SCHEMA IF EXISTS found nothing to drop. The script
re-creates the schema every time, so it is safe to re-run.
A first session
List what was created, then describe one table. \d shows columns, the primary key, constraints and the
foreign keys in both directions:
postgres=# \dt shop.*
List of tables
Schema | Name | Type | Owner
--------+-------------+-------+----------
shop | customers | table | postgres
shop | order_items | table | postgres
shop | orders | table | postgres
shop | products | table | postgres
(4 rows)
postgres=# \d shop.orders
Table "shop.orders"
Column | Type | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------
id | integer | | not null |
customer_id | text | | not null |
status | text | | not null |
order_date | timestamp with time zone | | not null |
Indexes:
"orders_pkey" PRIMARY KEY, btree (id)
Check constraints:
"orders_status_check" CHECK (status = ANY (ARRAY['open'::text, 'shipped'::text, 'cancelled'::text]))
Foreign-key constraints:
"orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES shop.customers(id)
Referenced by:
TABLE "shop.order_items" CONSTRAINT "order_items_order_id_fkey" FOREIGN KEY (order_id) REFERENCES shop.orders(id)
Expanded output suits wide rows, and \timing reports how long a statement took:
postgres=# \x
Expanded display is on.
postgres=# SELECT name, price FROM shop.products WHERE category='furniture';
-[ RECORD 1 ]--------
name | Standing Desk
price | 349.00
-[ RECORD 2 ]--------
name | Office Chair
price | 189.50
postgres=# \x
Expanded display is off.
postgres=# \timing on
Timing is on.
postgres=# SELECT c.name, count(*) AS orders FROM shop.customers c JOIN shop.orders o ON o.customer_id=c.id GROUP BY c.name ORDER BY orders DESC, c.name;
name | orders
----------------+--------
Ada Lovelace | 3
Alan Turing | 2
Grace Hopper | 2
Linus Torvalds | 1
(4 rows)
Time: 0.207 ms
To avoid typing shop. everywhere, set the schema search path for the session (or permanently with
ALTER ROLE ... SET search_path):
SET search_path = shop, public;
SHOW search_path;
Where PostgreSQL stores the cluster and which port and version it runs on are also queryable:
SHOW server_version;
SHOW data_directory;
SELECT name, setting FROM pg_settings WHERE name IN ('port', 'max_connections', 'data_checksums', 'wal_level');
Versions
The version numbering, support policy and release notes are published at the release notes and the versioning page. Notable features by version that matter for this section:
| Version | Highlights used or mentioned in these pages |
|---|---|
12 |
Stored generated columns; CTEs inlined by default (the |
13 |
Incremental sort; B-tree index deduplication. |
14 |
Multirange types; |
15 |
|
16 |
SQL/JSON constructors such as |
17 |
|
18 |
Asynchronous I/O ( |
Features introduced after the baseline are called out where they appear. See the section index for the reading path.