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

Steps

  1. 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).

    bash
    export 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 start
    Expected output
    postgres (PostgreSQL) 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1)
    waiting for server to start.... done
    server started
  2. Create 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.

    bash
    createdb shop
    psql -d shop -c "SELECT current_database(), current_user, version();" -x
    Expected 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-bit
  3. Create 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.

    sql
    CREATE 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 products
    Expected output
    CREATE 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)
  4. 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.

    sql
    INSERT 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 output
     id |        name
    ----+---------------------
      1 | Mechanical keyboard
      2 | Wireless mouse
      3 | 27-inch monitor
      4 | USB-C hub
    (4 rows)
    
    INSERT 0 4
  5. Query and aggregate

    Standard SQL filtering and grouping work as expected. The FILTER clause lets one query compute several conditional aggregates at once.

    sql
    SELECT 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 output
      category   | products | avg_price | under_50
    -------------+----------+-----------+----------
     accessories |        1 |     39.90 |        1
     displays    |        1 |    249.00 |        0
     peripherals |        2 |     59.25 |        1
    (3 rows)
  6. 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.

    sql
    INSERT 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 output
    INSERT 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)
  7. 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.

    sql
    SELECT 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 output
            name         | 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)
  8. 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.

    sql
    CREATE ROLE shop_app LOGIN PASSWORD 'change-me';
    GRANT SELECT, INSERT, UPDATE ON products TO shop_app;
    \du shop_app
    Expected output
    CREATE ROLE
    GRANT
         List of roles
     Role name | Attributes
    -----------+------------
     shop_app  |
  9. 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 output
    Wireless mouse 29.50
    Mechanical keyboard 89.00
    connected as shop_app to server 160015

Next steps

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

All tutorials

Sources

Last verified:

  1. postgresql.org/docs/16/tutorial.html postgresql.org
  2. postgresql.org/docs/16/app-initdb.html postgresql.org
  3. postgresql.org/docs/16/datatype-json.html postgresql.org
  4. postgresql.org/docs/16/gin.html postgresql.org
  5. postgresql.org/docs/16/using-explain.html postgresql.org
  6. psycopg.org/psycopg3/docs/basic/usage.html psycopg.org

Found an error? See how to report a correction.