Sub topic 3
Semi-structured data with jsonb
This chapter assumes you know basic SQL (SELECT, INSERT, CREATE TABLE), can run queries in psql, and understand what a table, column and constraint are. It covers six types that store data in a shape a plain column cannot express.
Storing JSON with jsonb
jsonb stores a JSON document in a binary form that supports fast lookups. Use it when the fields of a record vary from row to row.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO events (payload) VALUES ('{"type": "signup", "plan": "pro"}');
SELECT payload ->> 'plan' AS plan
FROM events
WHERE payload @> '{"type": "signup"}';
CREATE INDEX events_payload_idx ON events USING gin (payload);The ->> operator extracts a field as text. The @> operator tests containment. The GIN index speeds up containment queries.
Arrays
Any type can have an array form, written with a trailing []. Arrays suit short ordered lists that you always read as a whole. For data you search by item, a separate table is usually better.
SELECT ARRAY[1, 2, 3] @> ARRAY[2] AS array_contains;Enumerated types
An enum is a fixed set of labels. Enum values compare in the order they were declared.
CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
SELECT 'happy'::mood > 'ok'::mood AS enum_order;Adding a value later is possible, but removing or renaming one is not simple. Use an enum only for sets that rarely change.
Range types
A range stores an interval of values, such as a span of dates. The @> operator tests whether a value falls inside it.
SELECT daterange('2026-01-01', '2026-02-01') @> DATE '2026-01-15' AS in_range;By default, a range includes its start and excludes its end.
Binary data with bytea
bytea stores raw bytes, such as a small file or a hash. Hex input starts with \x.
SELECT length('\xDEADBEEF'::bytea) AS byte_count;This returns 4. Large files usually belong in object storage, with the database holding a reference to them.
Domains and composite types
A domain is a named base type with a reusable constraint. A composite type groups several fields into one value.
CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0);
CREATE TABLE line_items (
order_id bigint NOT NULL,
quantity positive_int NOT NULL
);Network address types
inet stores an IP address, optionally with a prefix length. cidr stores a network and requires the host bits to be zero. The << operator tests whether an address lies inside a network.
SELECT '192.168.1.5'::inet << '192.168.0.0/16'::cidr AS in_net;Choosing types for a schema
| Value | Recommended type | Reason |
|---|---|---|
| Row identifier | bigint identity | Compact and sequential |
| Money | numeric(12,2) | Exact decimal arithmetic |
| Timestamp of an event | timestamptz | Stores a fixed instant |
| Varying attributes | jsonb | Flexible shape with indexing |
| Small fixed set of labels | enum | Enforced, ordered values |
Exercise
A table stores a customer's billing address and a list of tags. Which types would you use for each, and why?
Show answer
Use a composite type or separate columns for the address, because its fields are fixed and named. Use text[] for the tags, because it is a short ordered list read as a whole. If tags must be searched individually, use a separate table instead.