In the Choosing the Right Data Type lesson, every column got a basic type: a number, text, a time. But the details of Sunset Coffee's menu don't fit neatly there. Drinks have a temperature and a sugar level, toast has a topping, and every item has a list of tags (short labels such as "coffee"). You could put all of it into a TEXT column.
In that lesson, a data type is the kind of container for what a column holds. The trouble is that TEXT is like a plastic bag: it holds anything. But the database can't check what's inside, search for one detail within it, or put the right index on it. PostgreSQL has better containers, built-in data types that not every database has: JSONB, arrays, UUID, ENUM, ranges and timestamptz.
JSON and JSONB
The metadata column holds menu details of different shapes: drinks have a temperature and sugar, toast has a topping. The id column is a SERIAL, a number in sequence that PostgreSQL fills in automatically.
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
metadata JSONB
);
INSERT INTO products (name, metadata) VALUES
('Milk Coffee', '{"temperature":"cold", "sugar": "normal"}'),
('Palm Sugar Milk Coffee', '{"temperature": "cold", "sugar": "palm"}'),
('Milk Tea', '{"sugar": "normal", "temperature": "hot"}'),
('Toast', '{"topping": "cheese", "topping": "chocolate"}');
Look at the Toast row: the key topping appears twice. Guess what gets stored if the column is JSON, and what gets stored if it's JSONB.
The answer depends on how each type stores it. PostgreSQL has two types for JSON:
JSON |
JSONB |
|
|---|---|---|
| Stored as | raw text, exactly as sent | binary, already parsed |
| Spaces and key order | kept | tidied, keys sorted |
| Duplicate keys | both stored | only the last one |
The @> operator and GIN indexes |
no | yes |
Parsed means the JSON text has been split into keys and values, then stored in a binary format (a format for the computer, not text). So the JSON column stores Toast exactly as {"topping": "cheese", "topping": "chocolate"}, while JSONB stores {"topping": "chocolate"}. Milk Coffee in the JSONB column becomes {"sugar": "normal", "temperature": "cold"}. JSONB is a little slower to write (it has to be parsed first), but much faster to query.
The query below finds the items served cold, then takes their kind of sugar:
CREATE INDEX products_metadata_idx ON products USING GIN (metadata);
SELECT name, metadata ->> 'sugar' AS sugar
FROM products
WHERE metadata @> '{"temperature": "cold"}';
-- Milk Coffee | normal
-- Palm Sugar Milk Coffee | palm
->>takes one value out as text.->takes it out as JSONB.@>means "contains": rows whose metadata holds"temperature": "cold".- GIN is the kind of index you met in the Full-Text Search lesson. GIN also works for the contents of JSONB and arrays, and it makes
@>fast across millions of rows.
On a JSON column, the same query is refused: ERROR: operator does not exist: json @> unknown.
Arrays
An array is a list of values inside one column. TEXT[] means an array of text:
ALTER TABLE products ADD COLUMN tags TEXT[];
UPDATE products SET tags = ARRAY['coffee', 'milk', 'palm'] WHERE name = 'Palm Sugar Milk Coffee';
SELECT name, tags FROM products WHERE 'milk' = ANY(tags);
SELECT name, tags FROM products WHERE tags @> ARRAY['coffee', 'palm'];
'milk' = ANY(tags):milkis somewhere in the array.tags @> ARRAY['coffee', 'palm']: the array holds both values.&&means the two arrays share at least one value.- psql (PostgreSQL's command-line program) shows an array like this:
{coffee,milk,palm}.
Arrays fit short lists that need no extra data, such as tags or user roles. When each item has columns of its own (a price, a quantity), make a separate table.
UUID
You met the UUID in the Primary Key & Foreign Key lesson: a 128-bit id that is practically never the same twice, written as 36 characters like 3f8a2c1e-9b4d-4e7a-8c2f-1d5b6a7e9f00. PostgreSQL has a native UUID type that stores it in 16 bytes, while the same text in a VARCHAR(36) takes 37 bytes and is slower when the database compares two values.
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id INTEGER NOT NULL,
total INTEGER NOT NULL
);
gen_random_uuid()has been built in since PostgreSQL 13 and makes version 4 (random) UUIDs. PostgreSQL 18 addsuuidv7(), which starts with its creation time, so the ids come out in order.- Compared with
SERIAL(1, 2, 3, ...), a UUID can't be guessed. If Budi's order URL is/orders/42, a curious visitor just tries/orders/43. UUIDs can also be made on many servers at once without clashing (distributed systems).
Other options for a primary key in PostgreSQL:
| Option | When to pick it |
|---|---|
BIGINT GENERATED ALWAYS AS IDENTITY |
The default for ordinary tables: small and fast. It replaces SERIAL, which the examples in this lesson still use but which is now seen as the old way. |
UUID v7, uuidv7() (PostgreSQL 18) |
Ids are made on many servers or in the application. They sort by time, so the index stays tidy, but anyone who sees an id can read when the row was created (uuid_extract_timestamp). Laravel 13's HasUuids makes this version. |
UUID v4, gen_random_uuid() |
An id must not reveal any time at all. Because it is random, its index grows faster. |
BIGINT inside, UUID in the URL |
Relations between tables keep using small numbers, and a public_id UUID UNIQUE column is what appears in the URL. |
ENUM and ranges
An ENUM is a type with a fixed list of values. A value outside the list is refused, as in the last comment line:
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped');
ALTER TABLE orders ADD COLUMN status order_status DEFAULT 'pending';
-- status = 'sent' -> ERROR: invalid input value for enum order_status: "sent"
It fits statuses and categories that rarely change. Adding a value is easy (ALTER TYPE order_status ADD VALUE 'delivered';), but removing a value from the list can't be done directly.
A range stores a span in one column, such as tstzrange for a span of time. Ranges fit bookings and schedules, because PostgreSQL can refuse spans that overlap:
CREATE EXTENSION btree_gist; -- so table_id WITH = can go into a GIST index
CREATE TABLE bookings (
id SERIAL PRIMARY KEY,
table_id INTEGER NOT NULL,
during TSTZRANGE NOT NULL,
EXCLUDE USING GIST (table_id WITH =, during WITH &&)
);
EXCLUDE refuses two rows with the same table_id (=) and time spans that overlap (&&). Here table_id is the number of a table in the café, not a database table. GIST is another kind of index in PostgreSQL, and the btree_gist extension (an add-on) lets an ordinary number column such as table_id go into a GIST index. Booking the same table at overlapping times is refused with conflicting key value violates exclusion constraint.
📌 timestamp and timestamptz
timestamp stores a date and time with no zone: 2026-10-08 19:00:00 is 7 pm where? Nobody knows. timestamptz stores one point in time (in UTC) and shows it in the session's time zone, the time zone used by the connection that reads the data. Take an order at 19:00 Singapore time. If the session's time zone is Singapore, it shows as 2026-10-08 19:00:00+08. After SET TIME ZONE 'Asia/Tokyo', it shows as 2026-10-08 20:00:00+09. In UTC, it shows as 2026-10-08 11:00:00+00. For when things happen (an order placed, a payment received), use timestamptz.
Choosing a type
This table is also the rule in the exercise:
| Need | Type |
|---|---|
| settings, metadata | JSONB |
| tags, roles | ARRAY |
| public id, distributed | UUID |
| status, category | ENUM |
| booking, schedule | RANGE |
| anything else, such as a first name | VARCHAR |
⚠️ Operators that error, indexes that go unused
->>returns text.WHERE metadata ->> 'ram' = 16fails:operator does not exist: text = integer. Compare it with the text'16', cast with(metadata ->> 'ram')::int, or use@> '{"ram": 16}'.- Putting everything in JSONB. A column that's always there and often filtered (price, stock) stays a normal column, so it can have
NOT NULL,CHECKand foreign keys. - A GIN index isn't used by
= ANY(...). For an array with a GIN index, writetags @> ARRAY['milk']. - A range with EXCLUDE but no btree_gist. Without that extension:
data type integer has no default operator class for access method "gist". - In the exercise, the answers are uppercase.
"JSONB","ARRAY","UUID","ENUM","RANGE", and"VARCHAR"for everything else.
TL;DR: JSONB stores JSON in a parsed binary form, split into keys and values (spaces tidied, only the last of duplicate keys kept). It can be queried with ->> (take a value out as text) and @> (contains), and can take a GIN index; JSON is just raw text. Arrays (TEXT[], a list of values in one column) are for short lists such as tags and roles, searched with ANY and @>. A UUID is a 128-bit id stored in 16 bytes that can't be guessed, made with gen_random_uuid() (or uuidv7() in PostgreSQL 18). ENUM (a fixed list of values) is for a status. Use ranges (a span in one column) for bookings and schedules, and timestamptz (a date and time that takes the time zone into account) for when things happen. For the rest, a plain VARCHAR or TEXT.
⚡ JSONB: JSON you can query
Write:
SELECT name, metadata ->> 'sugar' AS sugar
FROM products
WHERE metadata @> '{"temperature": "cold"}';
Guess first: PostgreSQL has two types for JSON, JSON and JSONB. Which one stores JSON that is already parsed and can be queried with @>?
JSONB. It stores JSON in a parsed binary form (split into keys and values) and can take a GIN index. On a JSON column, the query above is refused.
Meaning: The metadata column holds each item's details, for example {"sugar": "normal", "temperature": "cold"}. ->> takes one value out as text, and @> means "contains". So this query takes the kind of sugar of the items served cold. The JSON type only stores raw text.
⚡ Arrays and UUID
Write:
SELECT name, tags FROM products WHERE tags @> ARRAY['coffee', 'palm'];
Meaning: An array is a list of values inside one column (TEXT[]: an array of text), and it fits short lists such as tags and roles. This query finds the items whose tags array holds both 'coffee' and 'palm'. A UUID is a 128-bit id (written as 36 characters) that can't be guessed, made with gen_random_uuid().
⚡ ENUM, ranges, timestamptz
Meaning: ENUM (a type with a fixed list of values) is for a status. Ranges (a span in one column, such as a span of time) are for bookings and schedules. Timestamptz (a date and time that takes the time zone into account) is for when things happen. For the rest, a plain VARCHAR or TEXT.
In the exercise, the answers are uppercase: "JSONB", "ARRAY", "UUID", "ENUM", "RANGE", and "VARCHAR" for everything else.