Sunday , November 29 2026
Get started with PostgreSQL: psql, identity columns, JSONB, arrays, upserts and Python with psycopg.

PostgreSQL Tutorial for Beginners

Updated: 28 November 2026Level: BeginnerReading time: about 9 minutesPostgreSQL 16+

PostgreSQL (“Postgres”) is a powerful open-source relational database known for strict standards, advanced SQL, JSON support and extensions. It is a favourite of data engineers and is also used as a vector database through the pgvector extension.

What You Will Learn

  • Install PostgreSQL and use psql
  • Create tables with SERIAL / identity columns
  • JSONB, arrays and other Postgres features
  • Upserts with ON CONFLICT
  • Connect from Python with psycopg

Prerequisites

SQL Basics.

Install and Connect

Example
# Docker (any OS)
docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=secret postgres:16
# Connect
psql -h localhost -U postgres
psql commands
\l        -- list databases
\c shop   -- connect to database shop
\dt       -- list tables
\d orders -- describe a table
\q        -- quit

Create a Table

Example
CREATE DATABASE shop;
\c shop
CREATE TABLE products (
  id    INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name  TEXT NOT NULL UNIQUE,
  price NUMERIC(10,2) CHECK (price >= 0),
  tags  TEXT[],
  specs JSONB
);
INSERT INTO products (name, price, tags, specs) VALUES
 ('Laptop', 55000, ARRAY['electronics','office'], '{"ram": 16, "ssd": 512}'),
 ('Mouse',    499, ARRAY['electronics'],          '{"wireless": true}');

Postgres Superpowers

Example
-- query inside JSON
SELECT name, specs->>'ram' AS ram FROM products WHERE (specs->>'ram')::int >= 8;

-- search an array
SELECT name FROM products WHERE 'office' = ANY(tags);

-- upsert: insert or update if the name already exists
INSERT INTO products (name, price) VALUES ('Mouse', 449)
ON CONFLICT (name) DO UPDATE SET price = EXCLUDED.price;
Output
 name   | ram
 Laptop | 16

 name
 Laptop

Explanation: ->> extracts a JSON field as text; ::int casts it. ON CONFLICT ... DO UPDATE avoids duplicates when re-loading data, which is very useful in ETL.

Feature Why it matters
JSONB Store and index semi-structured data
Arrays Lists inside a column
Window functions and CTEs Full support, including recursive CTEs
Extensions pgvector (embeddings), PostGIS (maps), TimescaleDB (time series)
Strong consistency Reliable transactions

Connect from Python

Example
# pip install "psycopg[binary]"
import psycopg

with psycopg.connect("dbname=shop user=postgres password=secret host=localhost") as con:
    rows = con.execute("SELECT name, price FROM products WHERE price < %s", (1000,)).fetchall()
print(rows)
Output
[('Mouse', Decimal('449.00'))]

Explanation: psycopg (version 3) uses %s placeholders for safe parameters. For pandas, use pd.read_sql(query, sqlalchemy_engine).

Common Errors

Problem Cause and fix
password authentication failed Check the user and password, or pg_hba.conf settings.
relation does not exist You are connected to a different database, or the table name needs quotes because of capitals.

Series

SQL series: SQL Basics · MySQL · PostgreSQL · MongoDB · Database Design · SQL for Data Analytics · Advanced SQL Queries · Python MySQL series

Interview Questions

Q: What is JSONB?
A binary JSON type in PostgreSQL that can be queried and indexed efficiently.

Q: What is an upsert?
Insert a row, or update it if it already exists (ON CONFLICT DO UPDATE).

Practice Exercises

  1. Add a JSONB field “colour” to products and query by it.
  2. Write an upsert that loads a list of products without creating duplicates.

Summary

PostgreSQL offers standard SQL plus JSONB, arrays, upserts and powerful extensions. Use psql to manage it and psycopg to query it from Python.

Next: MongoDB · Vector Databases

About Machine Learning

Check Also

SQL for Data Analytics: Revenue, Growth and Customer Queries

SQL patterns for analysts: monthly revenue, month-over-month growth with LAG, category share, top customers and SQL to pandas.