Log inSign up

Beyond text and integer: PostgreSQL types that save code

PostgreSQL can store structured data natively: jsonb for documents, arrays for short lists, hstore for flat key and value pairs, uuid for keys, enum for fixed choices, timestamptz for moments in time and range types for intervals. Create a practice database, try each type with the examples below, and add a GIN or GiST index wherever you filter on these columns.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

How do you set up a practice database?

Create a throwaway database owned by your normal role so you can experiment without touching application data. If PostgreSQL is not installed yet, follow the PostgreSQL install guide first.

sudo -u postgres createuser --pwprompt deploy
sudo -u postgres createdb --owner=deploy typelab
psql -h 127.0.0.1 -U deploy typelab

Everything below runs in that psql session. Two extensions used later ship in the contrib modules: on Debian and Ubuntu they come with the server package, while PGDG builds on Rocky and Alma need sudo dnf install -y postgresql18-contrib (match the number to your version). Creating an extension needs the database owner or a superuser.

SELECT version();
\dx

\dx lists extensions already enabled in the current database, and \dT+ lists custom types once you add some.

When should you use jsonb and how do you query it?

Use jsonb for data whose shape varies from row to row, such as API payloads or per-product attributes, and keep fields you join or sort on as normal columns. jsonb stores a parsed binary form, removes duplicate keys and supports indexing, so prefer it over plain json unless you must keep the exact original text.

CREATE TABLE products (
  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name  text NOT NULL,
  attrs jsonb NOT NULL DEFAULT '{}'
);
INSERT INTO products (name, attrs) VALUES
  ('Small VPS', '{"cpu": 1, "ram_gb": 2, "disk": {"type": "nvme", "gb": 50}, "tags": ["linux", "ssd"]}'),
  ('Large VPS', '{"cpu": 4, "ram_gb": 8, "disk": {"type": "nvme", "gb": 160}}');

SELECT name, attrs->'disk'->>'type' AS disk_type, (attrs->>'ram_gb')::int AS ram
FROM products WHERE attrs @> '{"cpu": 4}';

-> returns jsonb, ->> returns text, @> tests containment and ? checks whether a key exists. SQL/JSON path queries add more power:

SELECT name FROM products WHERE attrs @? '$.disk ? (@.gb > 100)';
UPDATE products SET attrs = jsonb_set(attrs, '{ram_gb}', '16') WHERE name = 'Large VPS';
CREATE INDEX products_attrs_gin ON products USING gin (attrs jsonb_path_ops);

The jsonb_path_ops index is smaller and fast for @> and @?; the default GIN operator class also covers the key-exists operators.

How do PostgreSQL arrays work?

Any type can be an array by adding []. Arrays suit short lists that belong to one row, such as tags; once you need to query the list items on their own or attach data to them, a separate table is the better design.

CREATE TABLE posts (
  id    serial PRIMARY KEY,
  title text,
  tags  text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
  ('Hardening SSH', ARRAY['security', 'ssh']),
  ('Tuning PostgreSQL', '{database,performance}');

SELECT title FROM posts WHERE 'ssh' = ANY (tags);
SELECT title FROM posts WHERE tags && ARRAY['database', 'security'];
SELECT title, tags[1] AS first_tag, cardinality(tags) FROM posts;
SELECT title, unnest(tags) AS tag FROM posts;
UPDATE posts SET tags = array_append(tags, 'linux') WHERE id = 1;
CREATE INDEX posts_tags_gin ON posts USING gin (tags);

Array indexes start at 1, not 0. The overlap operator && and containment @> use the GIN index, while = ANY does not, so rewrite hot queries as tags @> ARRAY['ssh'].

What is hstore good for?

hstore stores flat text keys and text values in one column. It predates jsonb and is still handy for simple settings maps, though new designs usually pick jsonb because it handles nesting and numbers.

CREATE EXTENSION IF NOT EXISTS hstore;
CREATE TABLE servers (
  host  text PRIMARY KEY,
  meta  hstore
);
INSERT INTO servers VALUES ('app1.example.net', 'role=>web, city=>frankfurt, os=>debian');
SELECT host, meta->'role' FROM servers WHERE meta ? 'city';
SELECT host FROM servers WHERE meta @> 'os=>debian';
UPDATE servers SET meta = meta || 'backup=>daily'::hstore;
SELECT hstore_to_jsonb(meta) FROM servers;

The conversion function at the end makes moving from hstore to jsonb a single ALTER TABLE ... USING statement if you change your mind later.

How do you use UUID keys?

Declare the column as uuid and let the server fill it with gen_random_uuid(), which is built in since PostgreSQL 13. On PostgreSQL 18 uuidv7() creates time-ordered values that keep B-tree indexes compact and insert-friendly.

CREATE TABLE orders (
  id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  created_at timestamptz NOT NULL DEFAULT now(),
  total      numeric(12,2) NOT NULL
);
INSERT INTO orders (total) VALUES (49.00), (120.50) RETURNING id;
-- PostgreSQL 18 and newer:
ALTER TABLE orders ALTER COLUMN id SET DEFAULT uuidv7();

UUIDs are useful when IDs are visible to customers or generated on several servers, because they reveal nothing about row counts and never collide in practice. The uuid type stores 16 bytes, far less than the 36 character text form.

When does an enum type make sense?

An enum fits a short, stable list of states such as order status; the database rejects any other value and stores each one in four bytes.

CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped', 'cancelled');
ALTER TABLE orders ADD COLUMN status order_status NOT NULL DEFAULT 'pending';
UPDATE orders SET status = 'paid' WHERE total > 100;
SELECT status, count(*) FROM orders GROUP BY status ORDER BY status;
ALTER TYPE order_status ADD VALUE 'refunded' AFTER 'shipped';
SELECT enum_range(NULL::order_status);

Enum values sort in declaration order, not alphabetically. You can add values cheaply, but removing or renaming one in use is awkward. For lists that change often, a small lookup table with a foreign key is easier to maintain.

How should you store dates and times?

Store moments as timestamptz: PostgreSQL saves them in UTC and converts to the session time zone on output, which avoids most daylight saving mistakes.

SHOW timezone;
SET timezone = 'UTC';
SELECT now(), now() AT TIME ZONE 'Asia/Tokyo' AS tokyo_wall_clock;
SELECT date_trunc('day', created_at) AS day, count(*) FROM orders GROUP BY 1 ORDER BY 1;
SELECT now() - interval '30 days' AS month_ago, age(now(), '2026-01-01');
SELECT extract(epoch FROM now())::bigint AS unix_seconds;

Use date for calendar days without a clock, and plain timestamp only when you deliberately mean wall-clock time with no zone. Set the server zone with timedatectl (see time zone and time sync) and keep the database default at UTC unless you have a reason not to.

How do range types prevent overlapping bookings?

Range types hold a lower and upper bound in one value, and an exclusion constraint can then forbid two rows whose ranges overlap.

CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
  room   int NOT NULL,
  during tstzrange NOT NULL,
  EXCLUDE USING gist (room WITH =, during WITH &&)
);
INSERT INTO bookings VALUES (1, '[2026-12-10 09:00+00, 2026-12-10 11:00+00)');
INSERT INTO bookings VALUES (1, '[2026-12-10 10:00+00, 2026-12-10 12:00+00)');  -- rejected
SELECT * FROM bookings WHERE during @> '2026-12-10 10:30+00'::timestamptz;
SELECT int4range(10, 20) * int4range(15, 30) AS intersection;

The square bracket includes the start, the round bracket excludes the end, so back-to-back bookings do not clash. Built-in kinds include int4range, numrange, daterange and tstzrange, and multirange types hold several ranges in one value. Next, combine these types with views, triggers and CTEs.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-2learning and small apps1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4jsonb-heavy production data2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months

Questions about PostgreSQL JSON, arrays and special types

Should I choose json or jsonb?

Pick jsonb almost always. It is faster to query and can be indexed. Plain json only helps when you must keep key order, whitespace and duplicate keys exactly as received.

Do arrays replace a join table?

Not for data you query on its own. Arrays work for short tag lists; a separate table with foreign keys is better when items have their own fields or when you need referential integrity.

Is gen_random_uuid built in?

Yes, since PostgreSQL 13 it needs no extension. Older guides mention uuid-ossp or pgcrypto, which are no longer required for this.

Why did my timestamp change hours?

A timestamptz value is shown in the session time zone. Run SHOW timezone; and set it per session or per role with ALTER ROLE deploy SET timezone = 'UTC'; if output looks shifted.

Can I index a single key inside jsonb?

Yes, with an expression index such as CREATE INDEX ON products ((attrs->>'sku'));. It is smaller than a full GIN index and ideal for equality lookups on one field.