Getting started with PostgreSQL
PostgreSQL is an open-source relational database server known for standards-compliant SQL, strong consistency and a large extension ecosystem. This walkthrough goes from an empty data directory to indexed JSONB queries, and every command was executed to capture the output shown.
Database profile: PostgreSQL (license, deployment options, alternatives and benchmarks).
Prerequisites
- Linux with PostgreSQL 16 server packages installed (on Ubuntu 24.04: sudo apt install postgresql)
- Shell access as the postgres OS user, for example via sudo -i -u postgres
- Python 3.10+ and pip for the final step (pip install "psycopg[binary]")
Steps
Initialise and start a database cluster
A cluster is a data directory managed by one server process. Ubuntu's postgresql package normally creates and starts one for you; doing it by hand with initdb and pg_ctl shows what happens and works without systemd. Run these commands as the postgres OS user (for example after sudo -i -u postgres).
bashexport PATH=/usr/lib/postgresql/16/bin:$PATH postgres --version initdb -D ~/tutorial-data --auth-local=peer --auth-host=scram-sha-256 --encoding=UTF8 --locale=C.UTF-8 > /dev/null pg_ctl -D ~/tutorial-data -o "-k /var/run/postgresql" -l ~/tutorial.log startExpected outputpostgres (PostgreSQL) 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1) waiting for server to start.... done server startedCreate a database and connect with psql
createdb makes a new database inside the cluster, and psql is the interactive SQL shell. Socket connections use peer authentication, so the postgres OS user maps to the postgres database role; TCP connections will require a password.
bashcreatedb shop psql -d shop -c "SELECT current_database(), current_user, version();" -xExpected output-[ RECORD 1 ]----+----------------------------------------------------------------------------------------------------------------------------------------- current_database | shop current_user | postgres version | PostgreSQL 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0, 64-bitCreate a table with a JSONB column
Run the remaining SQL inside psql -d shop. An identity column generates ids for you, and JSONB stores semi-structured attributes in a parsed binary form that can be indexed.
sqlCREATE TABLE products ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, category text NOT NULL, price numeric(10, 2) NOT NULL CHECK (price >= 0), attrs jsonb NOT NULL DEFAULT '{}', created_at timestamptz NOT NULL DEFAULT now() ); \d productsExpected outputCREATE TABLE Table "public.products" Column | Type | Collation | Nullable | Default ------------+--------------------------+-----------+----------+------------------------------ id | bigint | | not null | generated always as identity name | text | | not null | category | text | | not null | price | numeric(10,2) | | not null | attrs | jsonb | | not null | '{}'::jsonb created_at | timestamp with time zone | | not null | now() Indexes: "products_pkey" PRIMARY KEY, btree (id) Check constraints: "products_price_check" CHECK (price >= 0::numeric)Insert rows and get generated values back
A single INSERT can add several rows, and RETURNING hands back columns the server filled in, such as the identity id, without a second query.
sqlINSERT INTO products (name, category, price, attrs) VALUES ('Mechanical keyboard', 'peripherals', 89.00, '{"color": "black", "wireless": false, "tags": ["rgb", "tkl"]}'), ('Wireless mouse', 'peripherals', 29.50, '{"color": "white", "wireless": true}'), ('27-inch monitor', 'displays', 249.00, '{"color": "black", "resolution": "2560x1440"}'), ('USB-C hub', 'accessories', 39.90, '{"ports": ["hdmi", "usb-a", "sd"]}') RETURNING id, name;Expected outputid | name ----+--------------------- 1 | Mechanical keyboard 2 | Wireless mouse 3 | 27-inch monitor 4 | USB-C hub (4 rows) INSERT 0 4Query and aggregate
Standard SQL filtering and grouping work as expected. The FILTER clause lets one query compute several conditional aggregates at once.
sqlSELECT category, count(*) AS products, round(avg(price), 2) AS avg_price, count(*) FILTER (WHERE price < 50) AS under_50 FROM products GROUP BY category ORDER BY category;Expected outputcategory | products | avg_price | under_50 -------------+----------+-----------+---------- accessories | 1 | 39.90 | 1 displays | 1 | 249.00 | 0 peripherals | 2 | 59.25 | 1 (3 rows)Add a B-tree index and check the query plan
To see the planner choose an index, the table first gets 100,000 synthetic rows from generate_series. After ANALYZE refreshes statistics, EXPLAIN shows that a selective filter on category uses the new index instead of scanning the whole table.
sqlINSERT INTO products (name, category, price, attrs) SELECT 'Item ' || g, 'bulk-' || (g % 1000), (g % 500) + 0.99, jsonb_build_object('color', (ARRAY['red', 'green', 'blue'])[g % 3 + 1], 'batch', g % 10) FROM generate_series(1, 100000) AS g; CREATE INDEX idx_products_category ON products (category); ANALYZE products; EXPLAIN (COSTS OFF) SELECT id, name FROM products WHERE category = 'displays';Expected outputINSERT 0 100000 CREATE INDEX ANALYZE QUERY PLAN --------------------------------------------------- Bitmap Heap Scan on products Recheck Cond: (category = 'displays'::text) -> Bitmap Index Scan on idx_products_category Index Cond: (category = 'displays'::text) (4 rows)Query JSONB and index it with GIN
The ->> operator extracts a field as text, and @> tests whether a document contains a given JSON fragment. A GIN index over the whole column lets containment queries avoid a full scan.
sqlSELECT name, attrs ->> 'color' AS color, attrs -> 'tags' AS tags FROM products WHERE attrs @> '{"wireless": false}'; CREATE INDEX idx_products_attrs ON products USING gin (attrs jsonb_path_ops); ANALYZE products; EXPLAIN (COSTS OFF) SELECT name FROM products WHERE attrs @> '{"color": "white"}'; SELECT name FROM products WHERE attrs @> '{"color": "white"}';Expected outputname | color | tags ---------------------+-------+---------------- Mechanical keyboard | black | ["rgb", "tkl"] (1 row) CREATE INDEX ANALYZE QUERY PLAN ------------------------------------------------------------ Bitmap Heap Scan on products Recheck Cond: (attrs @> '{"color": "white"}'::jsonb) -> Bitmap Index Scan on idx_products_attrs Index Cond: (attrs @> '{"color": "white"}'::jsonb) (4 rows) name ---------------- Wireless mouse (1 row)Create a login role for your application
Applications should not connect as the postgres superuser. Create a role with a password and grant it only the privileges it needs.
sqlCREATE ROLE shop_app LOGIN PASSWORD 'change-me'; GRANT SELECT, INSERT, UPDATE ON products TO shop_app; \du shop_appExpected outputCREATE ROLE GRANT List of roles Role name | Attributes -----------+------------ shop_app |Connect from Python with psycopg 3
Applications usually connect through a driver. psycopg sends values separately from the SQL text when you use %s placeholders, which prevents SQL injection, and the connection block commits automatically when it exits without an error.
python# pip install "psycopg[binary]" import psycopg with psycopg.connect("host=localhost dbname=shop user=shop_app password=change-me") as conn: rows = conn.execute( "SELECT name, price FROM products WHERE category = %s ORDER BY price", ("peripherals",), ).fetchall() for name, price in rows: print(name, price) print("connected as", conn.info.user, "to server", conn.info.server_version)Expected outputWireless mouse 29.50 Mechanical keyboard 89.00 connected as shop_app to server 160015
Next steps
- Keep passwords out of code by using environment variables or a ~/.pgpass file
- Learn EXPLAIN ANALYZE to measure real execution times, not just plans
- Try extensions such as pg_stat_statements, PostGIS or pgvector
- Set up regular backups with pg_dump or continuous archiving
FAQ
- Should I use json or jsonb in PostgreSQL?
- Prefer jsonb for most uses. It is stored in a parsed binary form, supports GIN indexing and containment operators, and is faster to query; json keeps the exact input text, including key order and whitespace, which is rarely needed.
- Why does EXPLAIN show a sequential scan even though I created an index?
- On small tables reading every row is cheaper than using an index, so the planner skips it. Run ANALYZE after loading data and test with realistic volumes before concluding that an index is not working.
- What is the difference between a cluster and a database in PostgreSQL?
- A cluster is one server instance with one data directory and one port. It can hold many databases, which share roles and configuration but keep their tables separate.
More tested tutorials
- Getting started with ClickHouse SQL using chDB
- Getting started with DuckDB in Python
- Getting started with LanceDB in Python
- Getting started with Redis
- Getting started with SQLite in Python
Sources
Last verified:
- postgresql.org/docs/16/tutorial.html postgresql.org
- postgresql.org/docs/16/app-initdb.html postgresql.org
- postgresql.org/docs/16/datatype-json.html postgresql.org
- postgresql.org/docs/16/gin.html postgresql.org
- postgresql.org/docs/16/using-explain.html postgresql.org
- psycopg.org/psycopg3/docs/basic/usage.html psycopg.org
Found an error? See how to report a correction.