Sub topic 11
When to Use JSON Columns and When to Normalize
This chapter assumes you know basic SELECT, INSERT, UPDATE, WHERE, and JOIN statements. You should also understand PostgreSQL data types and basic JSON objects and arrays. The examples use PostgreSQL's jsonb type.
The design choice
A JSON column stores a whole document in one column. A normalized design stores important values in separate columns and related records in separate tables.
For example, an order might contain optional delivery information:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
delivery jsonb
);The delivery value could contain:
{
"method": "courier",
"address": {
"city": "Oslo",
"postal_code": "0150"
},
"instructions": "Leave at the side door"
}This design is useful when delivery details vary between orders or when the application receives the document in this shape.
A normalized alternative might be:
CREATE TABLE order_delivery (
order_id bigint PRIMARY KEY REFERENCES orders(id),
method text NOT NULL,
city text NOT NULL,
postal_code text NOT NULL,
instructions text
);The second design gives each important value a known column, type, and constraint.
Choose based on how data is used
The most important question is not whether the data looks like JSON. Most data can be represented as JSON. Ask how the database must validate, search, join, and update the data.
| Requirement | Usually a good fit |
|---|---|
| The shape changes between records | `jsonb` |
| Every record has the same important fields | Normalized columns |
| You frequently join or aggregate by a value | Normalized columns |
| You mostly save and retrieve the document as a unit | `jsonb` |
| The database must enforce detailed rules | Normalized tables |
| The document contains application-specific extensions | `jsonb` alongside relational columns |
Use jsonb for flexible attributes, external payloads, event data, or configuration whose structure changes over time. Use ordinary columns for values that define the row's identity, lifecycle, or common queries.
A mixed design is often best. Store customer_id, status, and timestamps as relational columns, then store uncommon or evolving attributes in details jsonb.
Trade-offs and failure modes
JSON gives flexibility, but flexibility moves some work from the database to application code.
A JSON document does not automatically guarantee that a key exists, that its value has the right type, or that two records use the same structure. You can add CHECK constraints and indexes, but complex validation can become difficult to maintain.
JSON also makes relationships less direct. If products are stored inside an order document, enforcing that every product exists in a products table becomes harder. Updating every order that contains a product is also more complicated than updating one normalized row.
Repeated JSON values can create inconsistency. If an order stores a customer's name as a snapshot, that may be correct for historical reporting. If it stores the current customer name and expects it to stay synchronized, a foreign key and a join are safer.
Large documents can increase update costs. Updating one nested value may rewrite the jsonb value. Frequent changes to a large document can create more storage and write activity than updating a narrow relational column.
A practical decision process
Use these questions before choosing a design:
- Is the shape stable? If yes, prefer columns and tables.
- Is the value queried, sorted, grouped, or joined often? If yes, give it a typed column.
- Must PostgreSQL enforce uniqueness, foreign keys, ranges, or required fields? If yes, normalize that part.
- Does each record have different optional attributes? If yes, consider
jsonb. - Is the complete document exchanged with another system? If yes, retain it as
jsonb, possibly with extracted relational columns. - Can you describe useful indexes and constraints for the expected queries? If not, the design is not ready.
A mixed design example
Keep values used by ordinary queries in columns and preserve flexible data separately:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_type text NOT NULL,
occurred_at timestamptz NOT NULL,
account_id bigint NOT NULL,
payload jsonb NOT NULL,
CHECK (jsonb_typeof(payload) = 'object')
);
CREATE INDEX events_account_time_idx
ON events (account_id, occurred_at);
CREATE INDEX events_payload_gin_idx
ON events USING gin (payload);This design supports efficient time-based queries and account joins while allowing each event type to have its own payload fields.
Exercise
An application receives payment-provider responses with a changing structure, but it frequently filters payments by account, status, and creation time. Which values should be relational columns, and which could remain in JSONB?
Show answer
Store account, status, and creation time in typed relational columns because they are common filters. Store the provider response or changing provider-specific fields in a JSONB column.