PostgreSQL Guide: Setup, Roles, JSONB, and Backups

Mark Gates
Mark Gates Author & Technology Writer
Published Updated

PostgreSQL is an open-source object-relational database that combines SQL with a broad set of types, constraints, indexes, and extensions.

For query syntax, start with the SQL guide. The database engine guides explain how PostgreSQL compares with the other options.

Choose PostgreSQL when the database itself should enforce your business rules through constraints, types, and indexes, and when your team can run its backups and major upgrades.

When Should You Use PostgreSQL?

PostgreSQL fits applications whose database must express more than basic row storage. It is a strong candidate when the data model relies on detailed constraints, several index types, JSONB alongside relational columns, geospatial work through extensions, or database-side functions and types.

Choose it when these conditions match the application:

  • Relationships and business rules need database constraints.
  • Queries benefit from partial, expression, GIN, GiST, or BRIN indexes.
  • Extensions such as PostGIS solve a documented database requirement.
  • The team can operate backups, restores, monitoring, and major upgrades.
  • The hosting platform supports the required major version and extensions.

Use MySQL when its hosting, compatibility, and team experience are a better fit. Use SQLite when the application needs a local database file instead of a shared server.

How Do You Install and Connect to PostgreSQL?

Install PostgreSQL using your operating system's package or your provider's setup process, start the server, and connect with psql. Package names and authentication settings vary:

psql -h 127.0.0.1 -U postgres -d postgres

Use a supported stable PostgreSQL release for these examples. A beta or release candidate is for testing, not a production upgrade.

Ask the server for its identity and current connection context:

SELECT version();
SELECT current_database(), current_user, current_schema();
SHOW search_path;
SHOW server_encoding;

The result identifies the server, database, role, active schema, name-resolution path, and encoding. Keep these details in your deployment notes because a local psql version does not prove the remote server version.

How Do You Create PostgreSQL Roles and a Schema?

Create PostgreSQL roles with CREATE ROLE and give them access to a schema with GRANT. Some roles can log in, while others collect permissions or own objects. Separate ownership from the account used by ordinary application requests.

In the administrative psql session, create a fresh application database and connect to it first:

CREATE DATABASE codewalkers_app;
\connect codewalkers_app
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE app_runtime LOGIN
PASSWORD 'replace-with-a-generated-secret';

CREATE SCHEMA app AUTHORIZATION app_owner;

GRANT USAGE ON SCHEMA app TO app_runtime;

The runtime role can use the application schema without owning it. Migrations can run through an owner role or a controlled deployment identity, while web requests receive only the permissions needed for their queries.

Create objects with schema-qualified names so the target schema is explicit:

CREATE TABLE app.users (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE app.users OWNER TO app_owner;
GRANT SELECT, INSERT, UPDATE, DELETE
ON app.users TO app_runtime;
GRANT USAGE, SELECT
ON SEQUENCE app.users_id_seq TO app_runtime;

The explicit sequence grant permits direct sequence access when needed. Identity-column inserts themselves are covered by the table permissions. Default privileges need separate planning for tables and sequences created by future migrations. Test the complete migration with the migration identity, then test runtime queries again as app_runtime.

How Do PostgreSQL JSONB and Indexes Work Together?

PostgreSQL can index jsonb documents or individual values extracted from them. Unlike json, which preserves the input text, jsonb stores a processed binary representation. JSONB works well for fields whose shape varies, while stable application facts remain ordinary columns.

Run this example as the administrator or migration user. The event table keeps its user relationship and event type in ordinary columns:

CREATE TABLE app.events (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES app.users (id),
  event_type TEXT NOT NULL,
  payload JSONB NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

INSERT INTO app.users (email)
VALUES ('reader@example.com');

INSERT INTO app.events (user_id, event_type, payload)
SELECT id, 'article_viewed',
       '{"article_id": 17, "referrer": "newsletter"}'::jsonb
FROM app.users
WHERE email = 'reader@example.com';

The payload holds event-specific details, while the user, event type, and timestamp remain visible to constraints and common reports. Add an index only after the query shape is known:

CREATE INDEX events_article_id_idx
ON app.events ((payload ->> 'article_id'))
WHERE event_type = 'article_viewed';

EXPLAIN
SELECT id, created_at
FROM app.events
WHERE event_type = 'article_viewed'
  AND payload ->> 'article_id' = '17';

This partial expression index supports one repeated lookup without indexing every key in every payload.

Use EXPLAIN and query measurements to check whether an index speeds up the queries you actually run.

How Do You Back Up and Upgrade PostgreSQL?

Back up a PostgreSQL database with pg_dump and restore its custom archive with pg_restore. Rehearse major upgrades using pg_upgrade or dump and restore. Here is a small-database backup example:

pg_dump \
  --format=custom \
  --file=codewalkers_app.dump \
  codewalkers_app

createdb codewalkers_app_restore
pg_restore \
  --dbname=codewalkers_app_restore \
  codewalkers_app.dump

A complete recovery plan may also need roles, tablespaces, configuration, and other cluster-wide settings that a single-database dump does not cover. A full pg_dump includes large objects by default.

Verify restored row counts, constraints, extensions, permissions, and application queries. Keep the backup away from the server it protects and measure whether the restore finishes inside the required recovery window.

PostgreSQL supports each major version for five years. Minor upgrades within a major do not require dump and restore, although release notes can still require extra steps. Major upgrades normally use pg_upgrade or dump and restore because data-directory compatibility can change. Test extensions and query plans before the production cutover.

How Did PostgreSQL Begin?

The Berkeley POSTGRES implementation began in 1986 under Professor Michael Stonebraker. The first demonstration system operated in 1987, and Version 1 reached a small group of external users in June 1989.

Andrew Yu and Jolly Chen added an SQL interpreter in 1994, and the open-source descendant was released as Postgres95. The project adopted the PostgreSQL name in 1996 to connect the original POSTGRES work with its SQL capability. The shorter name "Postgres" remains an official alternative.

The long history matters because current PostgreSQL combines a mature relational core with features added over many release cycles. It does not remove the need to choose a supported version, test extensions, or plan major upgrades.

Common Pitfalls

Using the Superuser for the Application

An application bug can alter schemas or bypass ordinary permission boundaries. The web process connects as a superuser or object owner. Create a restricted runtime role, grant only required schema and table access, and run migrations through a separate identity.

Trusting the Search Path

A migration or job reads the wrong object after a schema is added or reordered. Unqualified names depend on a session's search_path. Use schema-qualified names in migrations and background jobs, and set a deliberate path for application sessions.

Hiding Core Fields in JSONB

Joins, reports, uniqueness checks, and permissions repeatedly extract the same JSON keys. Stable relational facts were stored inside one flexible payload. Move identifiers, money, states, and common filters into typed columns with constraints.

Adding Indexes Without a Query

Writes slow down while the intended read still uses a scan. An index was chosen by column name rather than a real predicate and sort order. Run EXPLAIN on the target query and add the smallest index that matches its access pattern.

For related decisions, read SQL schema design basics, SQL transactions and ACID, MySQL vs PostgreSQL vs SQLite.

Frequently Asked Questions

Should you use a PostgreSQL beta in production?

PostgreSQL beta and release-candidate builds are intended for testing, not production workloads. Use a supported stable major version, keep it on the current minor release, and test application plus extension compatibility before upgrading.

What is a PostgreSQL schema?

A PostgreSQL schema is a namespace inside a database. It can contain tables, views, functions, types, and other objects. Schemas help separate ownership and names, but permissions and a controlled search_path still matter. Schema-qualified names make migrations and background jobs easier to review.

When should a PostgreSQL application use JSONB?

A PostgreSQL application should use JSONB for variable payloads whose fields differ by event or integration type. Keep identifiers, relationships, money, permissions, common filters, and reporting fields in typed columns with constraints. JSONB can be indexed, but indexing does not restore a relational model hidden inside one document.

Does a PostgreSQL major upgrade require planning?

A PostgreSQL major upgrade requires deliberate planning. Major versions can change the data-directory format, so an upgrade normally uses pg_upgrade or dump and restore. Verify extensions, read release notes, test migrations and query plans on production-shaped data, preserve a rollback path, and rehearse the complete cutover before production.

Sources

  1. [1]
    PostgreSQL pg_dump
    (postgresql.org)
  2. [2]
  3. [3]
  4. [4]
  5. [5]
  6. [6]
    Database Roles
    (postgresql.org)
  7. [7]
    PostgreSQL Schemas
    (postgresql.org)
  8. [8]
    PostgreSQL JSON Types
    (postgresql.org)
  9. [9]
    PostgreSQL Indexes
    (postgresql.org)
  10. [10]
    SQL Dump
    (postgresql.org)